How to exclude duplicate edges from 3D Delaunay tessellation in SciPy? - scipy

I am using scipy.spatial.Delaunay together with Grasshopper (PythonGH module) to generate a 3D Delaunay tessellation. I do get the connectivity matrix from the simplices option, but this matrix contains a lot of duplicate edges (edges that overlap in the resulting tessellation). Is there a simple and efficient way to remove duplicate edges? My final script will contain a significant amount of nodes and edges...
Please be aware that I am not at all experienced in Python. I merely use scipy.spatial.Delaunay since Grasshopper has no 3D Delaunay tessellation module. My current script looks like this, where ‘Connectivity’ will generate a lot of duplicate edges when connecting the array:
import scriptcontext
import ghpythonremote
np = scriptcontext.sticky['numpy']
rpy = scriptcontext.sticky['rpy']
spy = scriptcontext.sticky['scipy']
Points = ghpythonremote.deliver(rpy, [x,y,z])
array = np.array(Points).transpose()
Connectivity = spy.spatial.Delaunay(array).simplices
Connectivity = ghpythonremote.obtain(Connectivity.tolist())
from ghpythonlib.treehelpers import list_to_tree
Connectivity = list_to_tree(Connectivity, source=[0,0])
Thanks in advance!
Regards,
Rowin
I have found this resource, but I do not get it to work by myself… https://groups.google.com/g/scipy-user/c/ZZb58FeeSKo?pli=1
I tried to remove duplicate edges in Grasshopper, but this becomes very slow very fast...

Related

Remove self loops and multiple edges from configuration multigraph

I am trying to draw a random network with a real sequence of degrees, using configuration model.
As I understood, the function returns a multigraph with self-loops and multiple edges.
How can I remove all self-loops and change all multiple edges for one simple edge?
I would appreciate any help!

How to identify Points Outside a 3D mesh in Matlab

I have two large data sets, one that is the outside of an object, and on that represents the fluid flow inside of the object. I am worried that with the mesh I have, some of the data might be mis-represented, or not modeled well, and is outside the first data set.
In Matlab, I used trisurf to create a mesh from the first data set and was curious if there was a way to check for points outside the mesh. Ive seen the 2D version of inpolygon, and some threshold functions, but the surface is not super regular and those don't really account for meshes. Thanks for the help!
You didn't specify how what kind of data/format your object is defined as. If for example you have a Delaunay tetrahdralization/mesh of your object (if not you can use delaunay to create one from a point cloud), you can use the tsearchn function to determine if points are in/out of the object (mesh).
https://www.mathworks.com/help/matlab/ref/tsearchn.html

Check intersections between points and polygons in QGIS

I have two data layers, one with points and one with polygons. Both layers have ID's and I would like to check whether the points with ID x lay inside or outside the polygon with ID x.
Does someone know how to do this?
Thanks,
Marie
One potential solution which gives you a comma separated list in the python console is to run a small script from the python console:
mapcanvas = iface.mapCanvas()
layers = mapcanvas.layers()
for a in layers[0].getFeatures():
for b in layers[1].getFeatures():
if a.geometry().intersects(b.geometry()):
print a.id(),",",b.id()
This should produce a result of cases where one feature intersects the other. The order of the layers did not matter in my testing, however, both layers had to use the same coordinate reference system, so you might need to re-project your data if both layers have different reference systems. This worked for points in polygons and polygons intersecting polygons (I'm sure it would work with lines as well).
Answers such as this: https://gis.stackexchange.com/questions/168266/pyqgis-a-geometry-intersectsb-geometry-wouldnt-find-any-intersections may help with further refinement of such a script, and was a primary source on this answer.

Over-segmentation of Watershed algorithm

I followed the 2-D Watershed example in Mathworks.com to separate the connected objects, like the image below:
The code is summarize as:
bw = imread('some_binary_image.tif');
D = -bwdist(~bw);
D(~bw) = -Inf;
L = watershed(D);
The result is:
The particle in the center has been separated into two. Are there any ways to avoid the over-segmentation here?
Thanks, lennon310, chessboard does work well for most of my images, but there are still some cases that it doesn't. For example, the following binary image:
Using chessboard will result in:
As I have hundreds of images, it seems that it is difficult to find one combination of parameters that work for all images. I am wondering if I need to combine the good results got from using chessboard, cityblock, etc...
Use max(abs(x1-x2),abs(y1-y2)) as the distance metric (chessboard), and use eight-connected neighborhood in watershed function:
bw=im2bw(I);
D = -bwdist(~bw,'chessboard');
imagesc(D)
D(~bw) = -Inf;
L = watershed(D,8);
figure,imagesc(L)
Result:
I have been dealing with the same issue for a while. For me, the solution was to use a marker based watershed method instead. Looks for examples on watershed method given on the Matlab Blog by Steve: http://blogs.mathworks.com/steve/
This method given by him worked best for me: http://blogs.mathworks.com/steve/2013/11/19/watershed-transform-question-from-tech-support/
Now, in an ideal world, we would be able to segment everything properly using a single method. But watershed does over or under-segment some particle, no matter which method you use (unless you manually give the markers). So, currently I am using a semi-automatic segmentation method; i.e., use watershed to segment the image as best as possible, and then take that image into MSPaint and edit it manually to correct whatever under/over-segmentation remains.
Region growing seems to have been used by some people in the past. But my image processing knowledge is limited so I can't help you out with that. It would be great if anyone could post something about how to use region-growing to segment such an image.
Hope this helps.

Visualizing a 3D datastructure

I have a 3D datastructure in C code that I want to visualize as boxes and points in 3D space. So I have a bunch of coordinates, some for points and some for boxes and I want to plot these in 3D to visualize the data structure. Anyone have experience doing anything similar to this? I started trying to use paraview. My plan being to generate a paraview statefile (xml-type file) and then just open it with paraview. The problem is those state files are massive and complex. To try and figure out the xml structure I was creating Boxes and Point sources in paraview and then looking at the state files it generated. It looks awful.
I just want to be able to say display a box with these coordinates and a point with these coordinates in a minimalistic way. Anyone have any ideas? Doesn't have to be in C or paraview necessarily as I can output the coordinates and input in whatever to generate the final product. Python + Matlab would work just as well if it works.
So I figured out a nice compromise. I started with the git code as described here:
http://www.shocksolution.com/microfluidics-and-biotechnology/visualization/python-vtk-paraview/
It's only one python file. The gist is the code there lets you give x,y,z positions and radius for points and outputs an XML file that is in VTK format. So to do the particles I just hand it the x,y,z positions and then a constant for the radius for all particles. Then I just make a spherical glyph on the datasets.
For the boxes I use the exact same code. For each box I still output x,y,z coordinates where the x,y,z values are the coordinates of the center of the box. Then for the "radius" parameter I use the edge length of the cube. This works because again in paraview I just glyph the datapoints for the boxes. I use the box glyph, and scale by scalar where the scalar is the radius. If you don't orient the box glyphs and set the scalar factor to 1 you get the desired result. Here's a simple example with everything uniform:
So I just output the coordinates in my C datastructure to CSV files and then in python pull in the files and use the code at the link and open the result with paraview. Here's how I used the code at the link:
from vtktools import VTK_XML_Serial_Unstructured
import sys
if len(sys.argv) > 2:
treeFile = sys.argv[1]
bodyFile = sys.argv[2]
else:
print 'No input files'
exit(4)
x = []
y = []
z = []
r = []
f = open(treeFile, 'r')
for line in f:
v = line.split(',')
x.append(float(v[0].strip()))
y.append(float(v[1].strip()))
z.append(float(v[2].strip()))
r.append(float(v[3].strip()))
f.close()
temp = treeFile.split('/')
if (len(temp) == 1):
temp = temp[0]
else:
temp = temp[-1]
tree_writer = VTK_XML_Serial_Unstructured()
tree_writer.snapshot(temp.split('.',1)[0] + '.vtu', x, y, z, [], [], [], [], [], [], r)
tree_writer.writePVD("octree.pvd")
x = []
y = []
z = []
r = []
f = open(bodyFile, 'r')
for line in f:
v = line.split(',')
x.append(float(v[0].strip()))
y.append(float(v[1].strip()))
z.append(float(v[2].strip()))
r.append(float(v[3].strip()))
f.close()
temp = bodyFile.split('/')
if (len(temp) == 1):
temp = temp[0]
else:
temp = temp[-1]
body_writer = VTK_XML_Serial_Unstructured()
body_writer.snapshot(temp.split('.',1)[0] + '.vtu', x, y, z, [], [], [], [], [], [], r)
body_writer.writePVD("distribution.pvd")
Since your data doesn't seem to be complex... Why don't you export it to a CSV file?
You'll be able to open it from ParaView, MATLAB, etc... Besides, it is a really straightforward implementation.
I would choose this if your data is not going to get more complex than that.
Happy coding!
If your algorithm is pure C and it's producing static or canned animated data you may like to export to an XML format or proprietary format that will open up many options.
Collada is an XML format designed for representing 3D objects in a software agnostic fashion and certainly worth a peek. You can then open in in a multitude of applications to view it, even Max and Maya which means no coding required to view it. There are also engines available that will read these exports natively.
As for other specific ways to visualize it this could be a totally open ended answer so depending on how many items you're trying to visualize and how much interatction you need here are a few suggestions but I know this is just the tip of the iceberg.
Matlab seems very good at plotting mathematical graphics but my rather dated memory of it was it was very slow and cumbersome to manipulate.
If it's simple gouraud shaded textured stuff and you want full control just go for a native OpenGL program as there's nothing too scary in there these days. It also means you get to keep you C code. Downside is it does take longer, especially if you need to handle camera controls or 'pixel quality' matters. I.e. if you're looking for shadowing, animation, shader effects, etc... please read on...
If it requires some user interaction, a stand alone app, more sophisticated rendering and the dataset isn't vast or you can compile it as C# (i.e. no pointers used) you may like to take a look at Unity. It simplifies 3D rendering for you by an order of magnitude and you just need to write C# to generate the mesh/particles you want to render and chuck some simple camera controls in (or import your collada file). The tricky bit is if you're new to it it'll take a day or two to get familiar with generating their meshes for your purpose.
Alternatively you could code it up in WebGL via HTML5 or better yet use someone else's WebGL system to do it for you!
There are a few items out there worth a peek if you opt for this route. My favourite is PlayCanvas and I believe it'll take your collada files too if you just need to generate them.
There's also SceneJS.org which is more raw and not personally tried that yet but mentioning it should that appeal too.