How to get area of a mesh if subdivided into triangle?
I found the cross product for each triangle and computed the area.The area is coming wrong according to blender.I have looked up stack flow other posts but they are not of any help.Could you help me to figure out why I am get a low area of 16.3 something for my mesh.
for i in f:
# print("i",i)
for k in i:
# print("k",k)
for j in z:
# print("z",z)
if (k==z.index(j)):
f_v.append(j)
# print(f_v)
v0=np.array(f_v[0])
v1=np.array(f_v[1])
v2=np.array(f_v[2])
ax=np.subtract(f_v[1],f_v[0])
ax=np.subtract(f_v[2],f_v[1])
ay=np.subtract(f_v[3],f_v[1])
..
cxx=np.power(cx,2)
# cyy=np.power(ay,2)
#czz=np.power(cz,2)
I've created meshplex to help you with this kind of tasks, and do it quickly. Simply load the mesh and sum up the cell volumes:
import meshplex
points = numpy.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
cells = numpy.array([[0, 1, 2]])
mesh = meshplex.MeshTri(points, cells)
# or read it from a file
# mesh = meshplex.read("circle.vtk")
print(numpy.sum(mesh.cell_volumes))
Related
I am trying to achieve if two objects (let's say two cubes) with their locations and dimensions.
for example we have a function:
def isOverlapped(locationCube1, dimensionCube1, locationCube2, dimensionCube2)
It should return true if they overlapped and false otherwise. The parameters should be a tuple of x, y, z coordination.
For example: we have two cubes:
Cube 1: location = (2, 2, 2) , dimension = (1.0, 5.0, 1.0)
Cube 2: location = (1.0, -1.0, 1.0) , dimension = (2.0, 2.0, 2.0)
So, after I put this in simulation I found out that they overlapped each others.
Now, I am wondering how to program such a thing. Thank you!
The idea is that you check each axis separately. If ANY axis does not overlap, then the objects do not intersect. Assuming the lines are sorted, if the end of line 1 > start of line 2 and start of line 1 < end of line 2, then they overlap.
https://gamedevelopment.tutsplus.com/tutorials/collision-detection-using-the-separating-axis-theorem--gamedev-169
I need some coulomb matrices of molecules for a machine learning task.
Coulomb Matrix? Here's a paper describing it
I found the python package molml which has a method for it. However i can't figure out how to use the api for a single molecule only. In all examples they provide the method is called with two molecules, why?
How the example provides the method:
H2 = (['H', 'H'],
[[0.0, 0.0, 0.0],
[1.0, 0.0, 0.0]])
HCN = (['H', 'C', 'N'],
[[-1.0, 0.0, 0.0],
[ 0.0, 0.0, 0.0],
[ 1.0, 0.0, 0.0]])
feat.transform([H2, HCN])
I need something like this:
atomnames = [list of atomsymbols]
atomcoords = [list of [x,y,z] for the atoms]
coulombMatrice = CoulombMatrix((atomnames,atomcoords)
I also found another lib (QML) wich promises the possibility to generate coulomb matrices, but, i'm not able to install it on windows because it depends on linux gcc-fortran compilers, i already installed cygwin and gcc-fortran for this purpose.
Thank you, guys
I've implemented my own solution for the problem. There's much room for improvements. E.g. randomly sorted coulomb matrix and bag of bonds are still not implemented.
import numpy as np
def get_coulombmatrix(molecule, largest_mol_size=None):
"""
This function generates a coulomb matrix for the given molecule
if largest_mol size is provided matrix will have dimension lm x lm.
Padding is provided for the bottom and right _|
"""
numberAtoms = len(molecule.atoms)
if largest_mol_size == None or largest_mol_size == 0: largest_mol_size = numberAtoms
cij = np.zeros((largest_mol_size, largest_mol_size))
xyzmatrix = [[atom.position.x, atom.position.y, atom.position.z] for atom in molecule.atoms]
chargearray = [atom.atomic_number for atom in molecule.atoms]
for i in range(numberAtoms):
for j in range(numberAtoms):
if i == j:
cij[i][j] = 0.5 * chargearray[i] ** 2.4 # Diagonal term described by Potential energy of isolated atom
else:
dist = np.linalg.norm(np.array(xyzmatrix[i]) - np.array(xyzmatrix[j]))
cij[i][j] = chargearray[i] * chargearray[j] / dist # Pair-wise repulsion
return cij
This question already has answers here:
Range values to pseudocolor
(3 answers)
Closed 6 years ago.
I'm using a potentiometer that outputs a value 0-255. What I want it to do is change the color of an RGB LED in a way that contains 256 steps which will show all colors on the LED with as much precision you can get.
Question:
How would I convert that single value (0-255) to an rgb code that I can apply to the LED?
The most obvious solution is to create a dictionary with all 256 possible values and manually assing RGB codes to those values. I don't want to do this and I'm trying to find a more mathematical solution.
Use one of the matplotlib colormaps. I would recommend the jet colormap since most people are familiar with the interpretation that blue means small values and red means large values.
from matplotlib import cm
pot_values = [0, 51, 102, 153, 204, 255]
rgb = []
for x in pot_values:
val = cm.jet(float(x)/255)[:3] # The 4th element is gamma
rgb.append([round(x*255) for x in val])
print(rgb)
# Output:
# [[0.0, 0.0, 128.0],
# [0.0, 76.0, 255.0],
# [41.0, 255.0, 206.0],
# [206.0, 255.0, 41.0],
# [255.0, 104.0, 0.0],
# [128.0, 0.0, 0.0]]
I am translating MATLAB code into Python, but before worrying about the translation I would like to understand how MATLAB and specifically its ODE15s solver are interpreting an equation.
I have a function script, which is called upon in the master script, and this function script contains the equation:
function testFun=testFunction(t,f,dmat,releasevec)
testFun=(dmat*f)+(releasevec.');
Within testFunction, t refers to time, f to the value I am solving for, dmat to the matrix of constants I am curious about, and releasevec to a vector of additional constants.
The ODE15s solver in the master script works its magic with the following lines:
for i=1:1461
[~,f]=ode15s(#(t, f) testFunction(t, f, ...
[dAremoval(i), dFWtoA(i), dSWtoA(i), dStoA(i), dFSedtoA(i), dSSedtoA(i); ...
dAtoFW(i), dFWremoval(i), dSWtoFW(i), dStoFW(i), dFSedtoFW(i), dSSedtoFW(i); ...
dAtoSW(i), dFWtoSW(i), dSWremoval(i), dStoSW(i), dFSedtoSW(i), dSSedtoSW(i); ...
dAtoS(i), dFWtoS(i), dSWtoS(i), dSremoval(i), dFSedtoS(i), dSSedtoS(i); ...
dAtoFSed(i), dFWtoFSed(i), dSWtoFSed(i), dStoFSed(i), dFSedremoval(i), dSSedtoFSed(i); ...
dAtoSSed(i), dFWtoSSed(i), dSWtoSSed(i), dStoSSed(i), dFSedtoSSed(i), dSSedremoval(i)], ...
[Arelease(i), FWrelease(i), SWrelease(i), Srelease(i), FSedrelease(i), SSedrelease(i)]), [i, i+1], fresults(:, i),options);
fresults(:, i + 1) = f(end, :).';
fresults is a table initially of zeros that houses the f results. The options call odeset to get 'nonnegative' values. The d values matrix above is a 6x6 matrix. I already have all of the d values and release value calculated. My question is: how is ode15s performing the integration with a 6x6 matrix given in the testfunction equation? I have tried to solve this by hand, but have not been successful. Any help would be much appreciated!!
#
def func(y, t, params):
f = 5.75e-16
f = y
dmat, rvec = params
derivs = [(dmat*f)+rvec]
return derivs
# Parameters
dmat = np.array([[-1964977.10876756, 58831.976165, 39221.31744333, 1866923.81515922, 0.0, 0.0],
[58831.976165, -1.89800738e+09, 0.0, 1234.12447489, 21088.06180415, 14058.70786944],
[39221.31744333, 0.84352331, -7.59182852e+09, 0.0, 0.0, 0.0],
[1866923.81515922, 0.0, 0.0, -9.30598884e+08, 0.0, 0.0],
[0.0, 21088.10183616, 0.0, 0.0, -1.15427010e+09, 0.0],
[0.0, 0.0, 14058.73455744, 0.0, 0.0, -5.98519566e+09]], np.float)
new_d = np.ndarray.flatten(dmat)
rvec = np.array([[0.0], [0.0], [0.0], [0.0], [0.0], [0.0]])
f = 5.75e-16
# Initial conditions for ODE
y0 = f
# Parameters for ODE
params = [dmat, rvec]
# Times
tStop = 2.0
tStart = 0.0
tStep = 1.0
t = np.arange(tStart, tStop, tStep)
# Call the ODE Solver
soln = odeint(func, y0, t, args=(params,))
#y = odeint(lambda y, t: func(y,t,params), y0, t)
It says here that ode15s uses backward difference formula for differentiation.
Your differential equation is (as far as I understand) f' = testFunc(t,f) and it has some vector matrix calculations inside the function.
Then you can replace the differentiation by a backward difference formula that is:
f_next = f_prev + h*testFunc(t,f_next);
where f_prev is the initial values of the vector. Here there is no important difference in calculations just because testFunc(t,f) function includes a 6x6 matrix. Each time it solves an inverse problem to find f_next by creating Jacobian matrices numerically.
However, trying to code algorithms as matlab does may be harder than we think since matlab has some (optimization related or not) special treatments to the problems. You should be careful on each value you get.
Essentially, you need to change very few things. Use numpy.ndarray for the vectors and matrices. The time-stepping can be done using scipy.integrate.ode. You will need to re-initialize the integrator for every change in the ODE function or supply matrix and parameter as additional function parameters via set_f_parameter.
Closer to the matlab interface but restricted to lsoda is scipy.integrate.odeint. However, since you used a solver for stiff problems, this might be exactly what you need.
Using Python and VTK I am trying to render 10k cylinders to visualize gradient directions. I have reviewed multiple examples on the internet but none of them shows how you can, at the same time, change the position, orientation, color and height of each rendered cylinder independently.
I know it is possible to create an actor per cylinder but with 10k cylinders that would be very slow.
The following example code is my work in progress on this problem. I first define some data for 2 cylinders and next I try to visualize them with VTK.
What works is the position, orientation and color of the cylinders.
What does not work is the height of each cylinder.
Possible solutions might be to use different cylinder sources to get the heights right. Yet I don't know how to apply those.
Perhaps a more experienced VTK programmer can enlighten me?
from vtk import *
# input data, every row is for a different item
positions = [[0, 0, 0],
[1.5, 0, 0]]
orientations = [[1.0, 0.0, 0.0],
[0.0, 1.0, 1.0]]
colors = [[255, 0, 0],
[0, 255, 255]]
heights = [1,
2]
# rendering of those two defined cylinders
points = vtkPoints()
points.InsertNextPoint(*positions[0])
points.InsertNextPoint(*positions[1])
polydata = vtkPolyData()
polydata.SetPoints(points)
color_def = vtkUnsignedCharArray()
color_def.SetNumberOfComponents(3)
color_def.SetNumberOfTuples(polydata.GetNumberOfPoints())
color_def.InsertTuple3(0, *colors[0])
color_def.InsertTuple3(1, *colors[1])
polydata.GetPointData().SetScalars(color_def)
pointNormalsArray = vtkDoubleArray()
pointNormalsArray.SetNumberOfComponents(3)
pointNormalsArray.SetNumberOfTuples(polydata.GetNumberOfPoints())
pointNormalsArray.SetTuple(0, orientations[0])
pointNormalsArray.SetTuple(1, orientations[1])
polydata.GetPointData().SetNormals(pointNormalsArray)
cyl_source = vtkCylinderSource()
cyl_source.SetResolution(10)
cyl_source.SetHeight(0.8)
cyl_source.SetRadius(0.1)
cyl_source.Update()
glyph = vtkGlyph3D()
glyph.SetInputData(polydata)
glyph.SetSourceConnection(cyl_source.GetOutputPort())
glyph.SetColorModeToColorByScalar()
glyph.SetVectorModeToUseNormal()
glyph.ScalingOff()
mapper = vtkPolyDataMapper()
mapper.SetInputConnection(glyph.GetOutputPort())
actor = vtkActor()
actor.SetMapper(mapper)
ren = vtkRenderer()
ren.AddActor(actor)
renwin = vtk.vtkRenderWindow()
renwin.AddRenderer(ren)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renwin)
renwin.Render()
iren.Initialize()
iren.Start()
It seems that http://www.vtk.org/Wiki/VTK/Examples/Python/Visualization/ClampGlyphSizes has something similar to what you need (I haven't tried):
# Tell glyph which attribute arrays to use for what
glyph.SetInputArrayToProcess(0,0,0,0,'Elevation') # scalars
glyph.SetInputArrayToProcess(1,0,0,0,'RTDataGradient') # vectors
# glyph.SetInputArrayToProcess(2,0,0,0,'nothing') # normals
glyph.SetInputArrayToProcess(3,0,0,0,'RTData') # colors
From the documentation http://www.vtk.org/doc/nightly/html/classvtkGlyph3D.html#details :
You can set what arrays to use for the scalars, vectors, normals, and
color scalars by using the SetInputArrayToProcess methods in
vtkAlgorithm. The first array is scalars, the next vectors, the next
normals and finally color scalars.
vtkGlyphMapper and vtkGlyph3DMapper allow you to set a 3-dimensional ScaleArray, which you can then add to the point data:
glyph.SetScaleArray("CylinderScales")
scaleArray = vtkDoubleArray()
scaleArray.SetName("CylinderScales")
scaleArray.SetNumberOfComponents(3)
scaleArray.SetNumberOfTuples(polydata.GetNumberOfPoints())
scaleArray.SetTuple(0, (1, 1, 1))
scaleArray.SetTuple(1, (1, 1, 2))
polydata.GetPointData().AddArray(scaleArray)
The second cylinder should be twice as tall as the first, unless I got my axes wrong.