I'm looking for an algorithm that provides a way to generate graphical representations of knots (either 2D or 3D, but the former, with vector graphics is preferable).
I've seen many links to knot theory in general, spanning from punctual references to general information.
Before trying to devise something from scratch by myself, I'd like to know about the existence of some existing software that lets you not only represent them (in memory) but visualize in some of their graphical representations (there are many). It could come in the form of a library, or a simple function, or even a pseudocode algorithm that tries to specify how to properly draw a know on screen.
As the previous link suggests, there is a package in Wolfram Mathematica, named KnotTheory that does that (in an almost complete way). However, it is not portable, nor free software and accessing its modules would be very cumbersome for me (a free implementation in Java, just to name a language, but each language is fine, would be be ideal from the portability and openness perspectives).
I've seen that many softwares are available (but most of them are old and not reachable or usable).
Do you have some good pointers to share?
UPDATE:
Since two votes to close this question have appeared, I am restating it in a more pragmatic and clear way: are there algorithms to draw and generate knots? has something been already implemented
UPDATE 2 (for reopening)
The graphical representation could be a 3D rendered object or a 2D svg graphics (I am abstracting from it since I am looking forward a programming language as Processing (or the same Mathematica itself) that provides you the primitives to draw curves (splines, beziers, etc) on screen (and then export them to raster or vector graphics).
The algorithm shall take one knot parametrization as input (ie, if we are talking about knots described by their crossing properties, their values is what is needed), returning one of the graphical representation above (ie even a sequence of points in a 2d space). That is, any parametrization is fine, my objective is just to get introspection on how to draw knots so to get ONE algorithm that does that in a particular way, leading to a particular representation, would be fine (Mathematica's lib seems to be able to draw it in so many representations).
Something like this?
void setup() {
size(300, 300, P3D);
}
void draw() {
background(36, 10, 28);
int f = frameCount%360;
translate(width/2, height/2);
if (frameCount >= 360 && frameCount <= 1080 )
rotateY(radians(f));
stroke(0);
drawKnot(40);
translate(knotX(f)*40, knotY(f)*40, knotZ(f)*40);
noStroke();
fill(180,50,145);
sphere(10);
}
void drawKnot(float sz) {
stroke(200);
for (int i = 0; i < 360; i++) {
point(knotX(i)*sz, knotY(i)*sz, knotZ(i)*sz);
}
}
float knotX(int n) {
return sin(radians(n)) + 2*sin(radians(n*2));
}
float knotY(int n) {
return cos(radians(n)) - 2*cos(radians(n*2));
}
float knotZ(int n) {
return sin(radians(n*3))*-1;
}
Wolfram Mathematica has basic knot theory, including visualization, built in:
http://reference.wolfram.com/language/ref/KnotData.html
This webpage from the software documentation contains many examples of standard knot-theoretic visualization and computation that can be done with Mathematica.
Related
I am currently making a game. I have multiple users and for each user I have a id (UUID). I was hoping to use this id as like a key to generate a random pattern then to a image for that player.
boolean[] booleanPlayerID = BSUtility.bytesToBooleans(playerID.getBytes(UTF_8));
WritableImage image = new WritableImage(50, 50);
PixelWriter writer = image.getPixelWriter();
int booleanIndex = 0;
for(int y = 0; 50 > y; y++){
for(int x = 0; 50 > x; x++){
if(booleanIndex >= booleanPlayerID.length){
booleanIndex = 0;
}
if(booleanPlayerID[booleanIndex]){
writer.setColor(x, y, Color.BLACK);
}
booleanIndex++;
}
}
Assuming the image is going to be 50x50... What I have been doing is I take the player's id, convert to boolean array, cycle through image pixels, also cycle through boolean array, if the boolean value is true then set the pixel color to black. The if statement is to avoid indexing out of bounds (I know I should probably convert the boolean array to be the same length as how many pixels are in the image)...
This does produce some what of a pattern, but to be honest it is a really shitty pattern. The patterns generally tend to be very similar to one another. I was wondering if someone could provide tips/example of how to do this better. With my little research I really couldn't find much. I did however find patterns that I am hoping to somewhat obtain, I believe they are called tangle patterns. I would really hope to have each user have their own unique image/pattern but obvious it is fine if they are somewhat similar but not same. I don't know if this is possible to be honest.
If you need a complete example I can replace the code above. Although the code above should be pretty straight forward to making it a full example (only things missing is generating the userID and converting it to boolean array from bytes).
What you are talking about is known as IDENTICON.
I actually don't know how they work but i know that they use some sort of hashing with the UNIQUE TEXT and generate image with that hash.
Here are two website i found who do provide source code so if you are interested you can look into the code and extract any useful information from there.
http://identicon.net/
https://jdenticon.com/
PS. Code are in JavaScript and on one website its in .NET and PHP too.
I'm planning on creating a calculator for physics that would run off of a few equations. But, I realized that it would be a lot of code.
With the equation v = x/t (just one of many I want to include) , there's already three possible equations.
v = x/t x = vt t = x/v
What I was planning to have the program do is:
-Ask the user what equation they're going to use
-Ask what variable is missing
-Solve for it with a matching equation
My question is whether or not there is a way I can format the code more efficiently. Without knowing how, it seems like running a lot of very similar code for each variant of an equation.
I'm planning to create this using multiple classes, if it isn't clear.
There's 2 approaches I can think of that would make the most sense.
The first more traditional way would be to make a bunch of classes for each kind of equation you wanted to include.
public class Velocity implements Equation{
public double solveT(double v, double x){
if(v != 0)
return x / v;
else
return 0; //or whatever value is appropriate
}
public double solveX(double v, double t){
return v * t;
}
public double solveV(double t, double x){
if(t != 0)
return x / t;
else
return 0; //or whatever value is appropriate
}
}
This keeps all of your different equations separate, and if you define an empty Equation interface you can substitute different Equation objects as needed. The drawback is that you'd have a lot of classes to keep track of, and you would have to make sure that the Equation object you're trying to call methods on is the correct instance, i.e. trying to call solveX() on a Density instance that doesn't have a solveX() method. However, having each class separate is a nice way to organize and debug.
The other approach is using Java8 lambdas:
interface twoTermEq{
double solve(double a, double b);
}
public class Calculator{
public double solveTwoTermEq(twoTermEq eq, double a, double v){
eq.solve(a, b);
}
}
public static void main(String[] args){
twoTermEq velSolveX = (t, v) -> return t * v;
twoTermEq velSolveT = (x, v) -> v != 0.0 ? return x / v : 0.0;
twoTermEq velSolveV = (x, t) -> t != 0.0 ? return x / t : 0.0;
//define as many equations as needed...
Calculator c = new Calculator();
//select which equation to run, collect user input
....
//do the calculation
double result = c.solveTwoTermEq(velSolveX, t, v);
}
This lets you define your equations all in one place and doesn't need a boatload of classes. You could similarly define interfaces for ThreeTermEq, FourTermEq, etc., as well as solveThreeTermEq(), solveFourTermEq(), etc. methods for the Calculator class. The drawback here is that it might become more difficult to maintain and organize, and I believe there's an upper limit on how big a class file can be; if a class file becomes too big it won't compile, which could happen if you've defined tons of equations.
For me the choice would come down to how I wanted to organize the code; if I wanted to only include a (relatively) small number of (relatively) simple equations, I would probably use lambdas. If I wanted to include every physics equation across as many physics topics as possible, I'd probably use classes.
Either way, there's going to have to be some similar code written for different permutations of an equation - I don't think there's really any way around that. You could try for a novel approach using a bunch of Objects to try to circumvent that, but I think that would be overwrought and not worth the effort; it's not like flipping variables around is hard.
You would probably be best off using some kind of symbolic math toolbox. Maple and MatLab are good languages/environments for working with equations, as they recognize symbolic math and can manipulate equations fairly easily. Java does not have any built in libraries for this, and it is difficult to find any libraries that would support a 'Computer Algebra System' to manipulate the equations for you. You might want to look at JAS (Java Algebra System), but I'm not sure that will do what you're looking to do. Most likey, you will need to solve for each variable by hand and build functions for each individual expression.
If you're sticking with Java, this is how I would go about it. In terms of code formatting, I would just create one Equation class that holds an array of all the variations of a given equation. The variations (i.e. V=I*R, I=V/R, R=V/I) would all be passed into the constructor for the class. A solve method could then be implemented that takes the requested variable to be solved for, the other variables and their values (distinguished by two arrays- one for characters and one for values)
Usage could be as follows:
Equation ohmsLaw = new Equation(new String[] {"V=I*R", "I=V/R", "R=V/I"});
double resistance = ohmsLaw.solve('R', new char[] {'I', 'V'}, new double[] {0.5, 12.0});
You would need to write a little bit of symbolic parsing, but that makes it fun, right?
May or may not have been the answer you were looking for, but hopefully it's some help. Good luck!
I know in WorldWind Java you can find out the elevation and a particular location with something like this:
public Double getPositionElevationMeters(Double lat, Double lon) {
double elevation = getWorldWindCanvas().getModel().getGlobe()
.getElevation(Angle.fromDegrees(lat), Angle.fromDegrees(lon));
return elevation;
}
Is there a way to figure out if that lat/lon is actually a major body of water or land pro-grammatically? I've taken a "blind" approach of just considering elevation less than 0 to be water, but that's obviously not ideal.
I'd even use another library that would give me this information; I just need it to work offline.
You could possibly use a data source such as this from which you should be able to determine the polygons for all countries on Earth. Antarctica has also been added to that data set. This would get you most of the way there, depending on what you define as a "major" body of water.
From there, you can use GeoTools to import the shape data and calculate which polygons a given lat/lon pair fall in to. If none, then it is probably an ocean.
The following pseudocode illustrates the logical flow:
// pseudocode, not the actual GeoTools API
boolean isWater(Coordinate point)
{
ShapeDataStore countryShapes = loadShapeData("world.shp");
GeoShape shape = countryShapes.findShapeByPoint(point);
if (shape == null)
return true // not a country or Antarctica, must be international waters.
else
return false;
}
edit
See this answer for an answer to a similar question that describes this process in a bit more detail.
I want to tessellate country shape from GeoTools to display it in 3D on Earth surface. GeoTools use JTS topology suite inside which looks feature rich.
Does it contain utility to tessellate some shape? I see there is triangulation package, but can't figure out, how to use it for shapes with holes.
Also I with it not just connect existing vertices like here
it should fill shape with multiple vertices inside.
UPDATE
I found, that JTS contains class ConformingDelaunayTriangulationBuilder which allows to make wished tessellations somehow, but it works bad. First of all it allows only constraining, which means additional code is needed to remove triangles from concaved regions. And also it tries to conserve Delaunay nature of tessellation, which leads to creating many additional sections.
Finally it causes ConstraintEnforcementException for complex shapes like countries and unusable.
Also I found "triangle" package, which is written in C and implementing Chew's second algorithm and works well
Now I wonder, was it ported to Java or wrapped into it?
I know this post is relatively old, but I recently faced the same situation and needed some Java Library or similar tool to triangulate some complex Polygons (as I wanted to display them on OpenGL, which can only draw triangles as primitive operations).
After quite some search and testing, the library that worked for me was Poly2Tri from Orbgis. You can get that library from Maven here*.
This library has many features, including Polygons with holes, Steiner points to optimize your triangulation, and other stuff. A basic usage example would be the following (based from the example on the linked repo):
//Create the polygon passing a List of PolygonPoints
Polygon polygon = new Polygon(
Arrays.asList(
new PolygonPoint(0, 0, 0),
new PolygonPoint(10, 0, 1),
new PolygonPoint(10, 10, 2),
new PolygonPoint(0, 10, 3)));
//Here you could add holes as needed, passing them as Polygons
polygon.addHole(someHoleYouCreated);
//Next, proceed to calculate the triangulation of the polygon
Poly2Tri.triangulate(polygon);
//Finally, obtain the resulting triangles
List<DelaunayTriangle> triangles = polygon.getTriangles();
Edit: Don't know if you already tried, but JTS Topology Suite also has a DelaunayTriangulationBuilder class (that is without the Conforming part). It is found at org.locationtech.jts.triangulate.DelaunayTriangulationBuilder, and perhaps it works better than the other one you tried but performed badly.
*Note: careful not to use this one instead, as I did at first and found that it was not the correct dependency (wasn't the -core version)
Here's a quick and dirty way using JTS:
First:
Triangulate your geometry with JTS DelaunayTriangulationBuilder
Prepare a set of sites, sites; copy in vertex sites from the initial triangulation
Loop:
Iterate over triangle geometries of the triangulation, adding triangle centroids** to sites
Re-triangulate using sites(now comprised of the original sites and the new centroid sites)
Finally:
Intersect the triangulation with the original geometry to restore its concave hull and any holes
**For this dirty technique, I've found that using triangle centroids lead to better results than the triangle circumcenters even though the latter tends to be used in more formal refinements (Chew, Ruppert and so on..)).
Code
static Geometry refinedTriangulation(Geometry g, int nRefinements, double tolerance) {
DelaunayTriangulationBuilder builder = new DelaunayTriangulationBuilder();
builder.setSites(g); // set vertex sites
builder.setTolerance(tolerance); // set tolerance for initial triangulation only
Geometry triangulation = builder.getTriangles(geometryFactory); // initial triangulation
HashSet<Coordinate> sites = new HashSet<>();
for (int i = 0; i < triangulation.getCoordinates().length; i++) {
sites.add(triangulation.getCoordinates()[i]);
}
for (int refinement = 0; refinement < nRefinements; refinement++) {
for (int i = 0; i < triangulation.getNumGeometries(); i++) {
Polygon triangle = (Polygon) triangulation.getGeometryN(i);
if (triangle.getArea() > 50) { // skip small triangles
sites.add(new Coordinate(triangle.getCentroid().getX(), triangle.getCentroid().getY()));
}
}
builder = new DelaunayTriangulationBuilder();
builder.setSites(sites);
triangulation = builder.getTriangles(geometryFactory); // re-triangulate using new centroid sites
}
triangulation = triangulation.intersection(g); // restore concave hull and any holes
return triangulation;
}
You can use triangle.getExteriorRing().getLength() > N or triangle.getArea() > N to skip over refining already-small triangles.
Example
Raw shape
JTS triangulation
JTS triangulation w/ intersection
1 Refinement
3 Refinements
I am trying to display a single magnetic field vector (point in space, with arrow from origin) using data from Android phone sensors. I wrote a simple server in Python to poll the phone for sensor data, and I want to plot the data received in real time. I'm looking for a simple solution, but I can't find any.
I looked at matplotlib, blender, and visual python but I couldn't find a simple enough solution that simply takes the 3 coordinates and plots. The data received is simply a vector with 3 points. The arrow from the origin is not so important, I just want to be able to visualize the moving point in 3d space.
Also, if necessary, I can rewrite the server in Java and use a Java plotting library. I just need some suggestions, and short code examples that achieve this.
You can draw scene by VPython very easily:
from visual import *
import math
def make_grid(unit, n):
nunit = unit * n
f = frame()
for i in xrange(n+1):
if i%5==0:
color = (1,1,1)
else:
color = (0.5, 0.5, 0.5)
curve(pos=[(0,i*unit,0), (nunit, i*unit, 0)],color=color,frame=f)
curve(pos=[(i*unit,0,0), (i*unit, nunit, 0)],color=color,frame=f)
return f
arrow(pos=(0,0,0), axis=(5,0,0), color=(1,0,0), shaftwidth=0.1)
arrow(pos=(0,0,0), axis=(0,5,0), color=(0,1,0), shaftwidth=0.1)
arrow(pos=(0,0,0), axis=(0,0,5), color=(0,0,1), shaftwidth=0.1)
grid_xy = make_grid(0.5, 10)
grid_xz = make_grid(0.5, 10)
grid_xz.rotate(angle=pi/2, axis=(1,0,0), origin=(0,0,0))
grid_yz = make_grid(0.5, 10)
grid_yz.rotate(angle=-pi/2, axis=(0,1,0), origin=(0,0,0))
sphere(radius=0.3)
obj = arrow(pos=(0,0,0), axis=(1,2,3), shaftwidth=0.3)
th = 0
while True:
rate(20)
obj.axis = (3*math.cos(th), 3*math.sin(th), 2)
th += 0.04
VPython is very simple:
pointer = arrow(pos=(0,0,0), axis=(1,2,3), shaftwidth=1)
Just change the axis=(1,2,3) to the 3 points in your vector. More information can be found here.
If c++ is an option you should really take a look at VTK
http://www.vtk.org/
It is very powerful to display 3D vector fields, and is pretty easy to use