How do you use the maxDistance flag in OpenMaya.MMeshIntersector.getClosestPoint - python

I'm trying to find the closest point on a mesh using the OpenMaya MMeshIntersector class but I want to limit the distance it searches. I'm using this so I can get the barycentricCoords to get a more accurate value.
Whenever I enter in a value to limit the distance, I get a RuntimeError: (kFailure): Unexpected Internal Failure. However if I enter in a value higher than 47.0, it works, but that's too high a value for my usage, I'm hoping to use values lower than 1.
I'm not sure how to use the maxDistance flag, and there isn't much documentation on how to use it. Does anyone have any links or info on how to use it?
I've google searched and gone through the maya documents, haven't had much of luck getting any concrete info
import maya.OpenMaya as OpenMaya
def getBarycentricCoords(sourceMesh, targetMesh, distanceThreshold):
selectionList = OpenMaya.MSelectionList()
selectionList.add(sourceMesh)
sourceMeshDag = OpenMaya.MDagPath()
selectionList.getDagPath(0, sourceMeshDag)
selectionList = OpenMaya.MSelectionList()
selectionList.add(targetMesh)
targetMeshDag = OpenMaya.MDagPath()
selectionList.getDagPath(0, targetMeshDag)
mObj = OpenMaya.MObject()
currentFace = OpenMaya.MItMeshPolygon( sourceMeshDag, mObj )
targetMeshMPointArray = OpenMaya.MPointArray()
targetMeshMFnMesh = OpenMaya.MFnMesh(targetMeshDag)
targetMeshMFnMesh.getPoints(targetMeshMPointArray, OpenMaya.MSpace.kWorld)
matrix = sourceMeshDag.inclusiveMatrix()
node = sourceMeshDag.node()
intersector = OpenMaya.MMeshIntersector()
intersector.create( node, matrix )
pointInfo = OpenMaya.MPointOnMesh()
uUtil = OpenMaya.MScriptUtil(0.0)
uPtr = uUtil.asFloatPtr()
vUtil = OpenMaya.MScriptUtil(0.0)
vPtr = vUtil.asFloatPtr()
pointArray = OpenMaya.MPointArray()
vertIdList = OpenMaya.MIntArray()
for idx in range(targetMeshMPointArray.length()):
intersector.getClosestPoint( targetMeshMPointArray[idx], pointInfo, distanceThreshold )
pointInfo.getBarycentricCoords(uPtr,vPtr)
I expect any float value as the maxDistance should work, but I get RuntimeError: (kFailure): Unexpected Internal Failure from maya that doesn't really help me debug the error itself.

Related

How to fix attribute Error in Pyomo model python

I am trying to write a pyomo model in python3, but I am facing this error that I can't seem to figure out - 'list' object has no attribute 'is_expression_type'. Below is my pyomo model, any help would be appreciated.
R_avg_tolist = [[0.00043159478649482775,
0.00045388639592182584,
0.0006735271301199177,
0.00044026758948786,
0.0037176592984565836]]
Cov_list = [[5.884677519869241e-05,
5.756542207262417e-05,
6.017027849080026e-05,
6.180151597797322e-05,
-0.0005074353586106837],
[5.756542207262417e-05,
6.0380562653096757e-05,
6.613608499966434e-05,
6.737370769879904e-05,
-0.0005362752804115953],
[6.017027849080026e-05,
6.613608499966434e-05,
8.206495000024503e-05,
8.01694525889321e-05,
-0.0005958716888916681],
[6.180151597797322e-05,
6.737370769879904e-05,
8.01694525889321e-05,
0.00010129901491226823,
-0.000608829853150321],
[-0.0005074353586106837,
-0.0005362752804115953,
-0.0005958716888916681,
-0.000608829853150321,
0.007373689071617548]]
import pyomo.environ as pyo
# Optimization Problem
def create_model(rho,R_avg,Cov):
m = pyo.ConcreteModel()
init_x = {}
m.idx = pyo.Set(initialize=[0,1,2,3,4])
for i in m.idx:
init_x[i] = 0
m.x = pyo.Var(m.idx,initialize=init_x,bounds=(0,None))
def Obj_func(m):
b = []
mult_result = 0
for i in m.idx:
a = 0
for j in m.idx:
a+= m.x[j]*Cov[j][i]
b.append(a)
for i in m.idx:
mult_result += b[i]*m.x[i]
return mult_result
m.OBJ = pyo.Objective(rule=Obj_func)
def constraint1(m):
sum=0
for i in m.idx:
sum+=m.x[i]
return sum ==100
m.C1 = pyo.Constraint(rule=constraint1(m))
def constraint2(m):
sum=0
for i in m.idx:
sum += R_avg_tolist[i]*m.x[i]
return sum >=0.08
m.C2 = pyo.Constraint(rule=constraint2(m))
return m
When I run model using below code, I face the attribute error - 'list' object has no attribute 'is_expression_type'.
rho = 0.0008
model1 = create_model(rho,R_avg_tolist,Cov_list)
solver = SolverFactory('ipopt')
results = solver.solve(model1, tee = True)
Probably not what you want to hear, but your model has many syntax probs. It's obviously a course assignment... Do you have somebody (instructor/TA) to go over this with who can advise a bit?
You didn't include enough info about which line of code caused the issue, but there are several problem areas. I've posted many simple pyomo examples if you scan through some of them, you'll get some ideas, along with the documentation and whatever you have from your course notes....
A few pointers may help:
Do NOT overwrite keywords/functions by using them as variables. When you write:
sum = 0
sum ....
you are nuking the python function sum by making that name a variable and assigning it the value of 0. You should be using sum in several of your functions with verbiage like:
sum(m.X[i] for i in m.idx) # or similar
You seem to be confused on making valid pyomo expressions. That is the core job of pyomo ... to make expressions and fill the model. For example, in your constraint1, you can just make an expression (without a function) and add it to your model. You can do a 1-liner there because the constraint is not a "for each". You could:
m.C1 = pyo.Constraint(expr=sum(m.x[i] for x in m.idx) == 100)
In general, when you are starting:
Add 1 thing to your model, and then print the model:
model.pprint()
See if it looks right, if not, fix it. Then repeat!

Python route finder for aviation

I made an app that besides all other things try to find a valid route between 2 airports.
I have all the required data in a sqlite3 database witch i query and plot in a basemap embeded in PyQt5 with signals live.
My problem is i can't find the algorithm to make all possible variations(with disqualify some, as all possibilies are enormous ) and store them to output the final valid routes.
Dijkstra's algorithm i think can't implemented as any time a route can reach a dead end.
My main problem is the algorithm and its implementation and not the data so don't hesitate and write any data required for any possible algorithm.
The algorith hints are:
I have a starting waypoint.
I find all routes that includes this starting point(disqualifying oposite headings)(each route have various waypoints).
Find next waypoint for each route.
Now this waypoint can be connected to other route and so on.
Routes then tested and disquilyfied by various variants or reaching dead ends.
Continue until you reach to the final(target waypoint).
Output the somehow stored route(s)
What i got so far with stack issues:
##finding base direction##
base_radians = math.atan2(self.dest_coord[0]-self.dep_coord[0], self.dest_coord[1]-self.dep_coord[1])
base_degrees = math.degrees(base_radians)
print(base_degrees)
if base_degrees < 0 :
base_heading = 'W'
else:
base_heading = 'E'
### finding all routes connected to first waypoint###
self.cursor.execute("select DISTINCT ats_ident,seq_num from dafif_ats where wpt1_ident = ? AND ats_icao = ? AND direction = ? ORDER BY ats_ident,seq_num ASC",('ATV','LGGG',base_heading))
sub_ats_idents = self.cursor.fetchall()
#### for each route find next waypoints###
for i in sub_ats_idents:
self.cursor.execute("select wpt1_ident,wpt2_ident from dafif_ats where ats_ident = ? and ats_icao = ? and direction = ? and seq_num >= ? ORDER BY seq_num ASC",(i[0],'LGGG',base_heading,i[1]))
each_wpt_combo = self.cursor.fetchall()
#### for each next waypoint find possible routes###
for x in each_wpt_combo:
self.cursor.execute("select DISTINCT ats_ident,seq_num from dafif_ats where wpt1_ident = ? AND ats_icao = ? AND direction = ? ORDER BY ats_ident,seq_num ASC",(x[0],'LGGG',base_heading))
each_ats = self.cursor.fetchall()
print(each_ats)
#### for each subroute plot waypoints###
for z in each_ats:
self.cursor.execute("select wpt1_dlon,wpt1_dlat,wpt2_dlon,wpt2_dlat from dafif_ats where wpt1_ident = ? AND ats_icao = ? AND direction = ? ORDER BY ats_ident,seq_num ASC",(x[0],'LGGG',base_heading))
plot_var = self.cursor.fetchall()
self.route_sender.emit(plot_var)
time.sleep(0.1)
Any material or example to read will be super.
Thx in advance.
For future readers , A* algorithm with hieristics is the solution for these kind of problems.

Python (Maybe Shapely) to create a buffer and count points

I'm trying to do a fairly simple analysis by buffering points (SEPTA subway stations [below]) and counting the number of 'incidents' (also points) that lie within the buffer. That's it.
I've done some looking online, but I can't find anything specific. Maybe it's so easy that nobody needs to ask. I could really use some help.
I was able to fix the code and create a buffer for the points, but I can't seem to be able to count the points that come within the buffer. Also, there was an issue with the 'incidents' point set that I was using, so I switched it with 'Farmers Markets'. Below is what I've got so far. Again, I just need to count the points.
from osgeo import ogr
septaclip = ogr.Open(r'/home/user/Downloads/SEPTAclip.shp')
septalyr = septaclip.GetLayer(0)
citylimits = ogr.Open(r'/home/user/Downloads/City_Limits.shp')
citylyr = citylimits.GetLayer(0)
crimestat = ogr.Open(r'/home/user/Downloads/Farmers_Markets.shp')
crimelyr = crimestat.GetLayer(0)
memory_driver = ogr.GetDriverByName('Memory')
memory_ds = memory_driver.CreateDataSource('Temp')
buff_lyr = memory_ds.CreateLayer('Buffer')
buff_feat = ogr.Feature(buff_lyr.GetLayerDefn())
multipoly = ogr.Geometry(ogr.wkbMultiPolygon)
for septafeat in septalyr:
buff_geo = septafeat.geometry().Buffer(3000)
multipoly.AddGeometry(buff_geo)
#multipoly = (multipoly.UnionCascaded())
for crimefeat in crimelyr:
buffcrime = crimefeat.geometry().Intersection(multipoly)
Try this for counting the points after intersection:
count = 0
for crimefeat in crimelyr:
if not crimefeat.geometry().Intersection(multipoly).IsEmpty():
count += 1
Or using OGR's capabilities:
crime_multipoint = ogr.Geometry(ogr.wkbMultiPoint)
for crimefeat in crimelyr:
crime_multipoint.AddGeometry(crimefeat.geometry())
crime_multipoint.Intersection(multipoly).GetGeometryCount()

Find closest point on mesh in specific axis (maya)

Let's say I have one locator above a polyPlane. What I want to do is a lookup or trace from the locator in negative or positive y until it hits the polyPlane and return the position of the closest point/vertex/uv/
I imagine this have been done one million times but the only examples I have found works by locating the closest point based on all axis which in my case is close to useless.
I would appreciate any help I could get!
Edit:
Added image of the difference between the first suggested solution and what I want to achieve
What we can do is use OpenMaya (Maya's API) to loop over the faceVerts gathered in an array, check to see which is shortest distance from the locator position compared to the current facevert, if it is shorter than the last shortest distance, save it as the closestVertex variable.
import maya.OpenMaya as OpenMaya
from pymel.core import *
geo = PyNode('pSphere1')
pos = PyNode('locator1').getRotatePivot(space='world')
nodeDagPath = OpenMaya.MObject()
try:
selectionList = OpenMaya.MSelectionList()
selectionList.add(geo.name())
nodeDagPath = OpenMaya.MDagPath()
selectionList.getDagPath(0, nodeDagPath)
except:
warning('OpenMaya.MDagPath() failed on %s' % geo.name())
mfnMesh = OpenMaya.MFnMesh(nodeDagPath)
pointA = OpenMaya.MPoint(pos.x, pos.y, pos.z)
pointB = OpenMaya.MPoint()
space = OpenMaya.MSpace.kWorld
util = OpenMaya.MScriptUtil()
util.createFromInt(0)
idPointer = util.asIntPtr()
mfnMesh.getClosestPoint(pointA, pointB, space, idPointer)
idx = OpenMaya.MScriptUtil(idPointer).asInt()
faceVerts = [geo.vtx[i] for i in geo.f[idx].getVertices()]
closestVertex = None
minLength = None
for v in faceVerts:
thisLength = (pos - v.getPosition(space='world')).length()
if minLength is None or thisLength < minLength:
minLength = thisLength
closestVertex = v
select(closestVertex)
This could probably be done with python without the API, but if you've got maya, you've got access to the API :)
I hope this helps

python function not recurving properly (adding nodes to graph)

I'm having a rare honest-to-goodness computer science problem (as opposed to the usual how-do-I-make-this-language-I-don't-write-often-enough-do-what-I-want problem), and really feeling my lack of a CS degree for a change.
This is a bit messy, because I'm using several dicts of lists, but the basic concept is this: a Twitter-scraping function that adds retweets of a given tweet to a graph, node-by-node, building outwards from the original author (with follower relationships as edges).
for t in RTs_list:
g = nx.DiGraph()
followers_list=collections.defaultdict(list)
level=collections.defaultdict(list)
hoppers=collections.defaultdict(list)
retweets = []
retweeters = []
try:
u = api.get_status(t)
original_tweet = u.retweeted_status.id_str
print original_tweet
ot = api.get_status(original_tweet)
node_adder(ot.user.id, 1)
# Can't paginate -- can only get about ~20 RTs max. Need to work on small data here.
retweets = api.retweets(original_tweet)
for r in retweets:
retweeters.append(r.user.id)
followers_list["0"] = api.followers_ids(ot.user.id)[0]
print len(retweets),"total retweets"
level["1"] = ot.user.id
g.node[ot.user.id]['crossover'] = 1
if g.node[ot.user.id]["followers_count"]<4000:
bum_node_adder(followers_list["0"],level["1"], 2)
for r in retweets:
rt_iterator(r,retweets,0,followers_list,hoppers,level)
except:
print ""
def rt_iterator(r,retweets,q,followers_list,hoppers,level):
q = q+1
if r.user.id in followers_list[str(q-1)]:
hoppers[str(q)].append(r.user.id)
node_adder(r.user.id,q+1)
g.add_edge(level[str(q)], r.user.id)
try:
followers_list[str(q)] = api.followers_ids(r.user.id)[0]
level[str(q+1)] = r.user.id
if g.node[r.user.id]["followers_count"]<4000:
bum_node_adder(followers_list[str(q)],level[str(q+1)],q+2)
crossover = pull_crossover(followers_list[str(q)],followers_list[str(q-1)])
if q<10:
for r in retweets:
rt_iterator(r,retweets,q,followers_list,hoppers,level)
except:
print ""
There's some other function calls in there, but they're not related to the problem. The main issue is how Q counts when going from a (e.g.) a 2-hop node to a 3-hop node. I need it to build out to the maximum depth (10) for every branch from the center, whereas right now I believe it's just building out to the maximum depth for the first branch it tries. Hope that makes sense. If not, typing it up here has helped me; I think I'm just missing a loop in there somewhere but it's tough for me to see.
Also, ignore that various dicts refer to Q+1 or Q-1, that's an artifact of how I implemented this before I refactored to make it recurve.
Thanks!
I'm not totally sure what you mean by "the center" but I think you want something like this:
def rt_iterator(depth, other-args):
# store whatever info you need from this point in the tree
if depth>= MAX_DEPTH:
return
# look at the nodes you want to expand from here
for each node, in the order you want them expanded:
rt_iterator(depth+1, other-args)
think I've fixed it... this way Q isn't incremented when it shouldn't be.
def rt_iterator(r,retweets,q,depth,followers_list,hoppers,level):
def node_iterator (r,retweets,q,depth,followers_list,hoppers,level):
for r in retweets:
if r.user.id in followers_list[str(q-1)]:
hoppers[str(q)].append(r.user.id)
node_adder(r.user.id,q+1)
g.add_edge(level[str(q)], r.user.id)
try:
level[str(q+1)] = r.user.id
if g.node[r.user.id]["followers_count"]<4000:
followers_list[str(q)] = api.followers_ids(r.user.id)[0]
bum_node_adder(followers_list[str(q)],level[str(q+1)],q+2)
crossover = pull_crossover(followers_list[str(q)],followers_list[str(q-1)])
if q<10:
node_iterator(r,retweets,q+1,depth,followers_list,hoppers,level)
except:
print ""
depth = depth+1
q = depth
if q<10:
rt_iterator(r,retweets,q,depth,followers_list,hoppers,level)

Categories