Converting Python (PyKinect) Skeleton data to Points (X,Y) - python

This is a pretty simple issue but I am new to Python and I can't seem to accomplish it.
I want to convert Skeleton data co-ordinates in Python (PyKinect) to Points (X,Y). I know that the similar task can be achieved in C# (using Microsoft.Kinect libraries) like the below code:
var p = new Point[6];
Point shoulderRight = new Point(), shoulderLeft = new Point();
foreach (Joint j in data.Joints)
{
switch (j.ID)
{
case JointID.HandLeft:
p[0] = new Point(j.Position.X, j.Position.Y);
// ...
In Python (using PyKinect) though, I am able to get the data object:
for index, data in enumerate(skeletons):
p2 = data.SkeletonPositions[JointId.wrist_left] #test left wrist joint data object
print ('p2', p2)
The output is:
('p2', <x=-0.5478253364562988, y=-0.5376561880111694, z=1.7154035568237305, w=1.0>)
But, I can't seem to convert it into Point(X,Y) format. Will I need to use NumPy or some other external Python library for this? Any suggestions would really be appreciated.

You can use regex to extract the values, I am not sure if this is what you are looking for but try this:
import re
p2 = "<x=-0.5478253364562988, y=-0.5376561880111694, z=1.7154035568237305, w=1.0>"
p2 = re.findall("-?\d+.\d+",p2)
p2_xy = p2[0],p2[1]
print ("p2",p2_xy)
Output:
('ps', ('-0.5478253364562988', '-0.5376561880111694'))
Or if you want a more cleaner version:
import re
p2 = "<x=-0.5478253364562988, y=-0.5376561880111694, z=1.7154035568237305, w=1.0>"
p2 = re.findall("-?\d+.\d+",p2)
print ("p2",p2[0],p2[1])
Output:
('p2', '-0.5478253364562988', '-0.5376561880111694')

Related

Find neighbouring polygons in Python QGIS

I am using code I found and slightly modified for my purposes. The problem is, it is not doing exactly what I want, and I am stuck with what to change to fix it.
I am searching for all neighbouring polygons, that share common borded (a line), that is not a point
My goal: 135/12 is neigbour with 319/2 135/4, 317 but not with 320/1
What I get in my QGIS table after I run my script
NEIGBOURS are the neighbouring polygons,
SUM is the number of neighbouring polygons
The code I use also includes 320/1 as a neighbouring polygon. How to fix it?
from qgis.utils import iface
from PyQt4.QtCore import QVariant
_NAME_FIELD = 'Nr'
_SUM_FIELD = 'calc'
_NEW_NEIGHBORS_FIELD = 'NEIGHBORS'
_NEW_SUM_FIELD = 'SUM'
layer = iface.activeLayer()
layer.startEditing()
layer.dataProvider().addAttributes(
[QgsField(_NEW_NEIGHBORS_FIELD, QVariant.String),
QgsField(_NEW_SUM_FIELD, QVariant.Int)])
layer.updateFields()
feature_dict = {f.id(): f for f in layer.getFeatures()}
index = QgsSpatialIndex()
for f in feature_dict.values():
index.insertFeature(f)
for f in feature_dict.values():
print 'Working on %s' % f[_NAME_FIELD]
geom = f.geometry()
intersecting_ids = index.intersects(geom.boundingBox())
neighbors = []
neighbors_sum = 0
for intersecting_id in intersecting_ids:
intersecting_f = feature_dict[intersecting_id]
if (f != intersecting_f and
not intersecting_f.geometry().disjoint(geom)):
neighbors.append(intersecting_f[_NAME_FIELD])
neighbors_sum += intersecting_f[_SUM_FIELD]
f[_NEW_NEIGHBORS_FIELD] = ','.join(neighbors)
f[_NEW_SUM_FIELD] = neighbors_sum
layer.updateFeature(f)
layer.commitChanges()
print 'Processing complete.'
I have found somewhat a workaround for it. Before using my script, I create a small (for my purposes, 0,01 m was enough) buffer around all joints. Later, I use a Difference tool to remove the buffer areas from my main layer, thus removing not-needed neighbouring polygons. Using the code now works fine

Printing tip labels when using the python module dendropy to calculate pairwise distances between nodes on a phylogenetic tree?

I'm trying to create an array in python that will contain all the pairwise distances between every pair of nodes on a phylogenetic tree. I'm currently using dendropy to do this. (I initially looked at biopython but couldn't find an option to do this). The code I have so far looks like this:
import dendropy
tree_data = []
tree = dendropy.Tree.get(path="gonno_microreact_tree.nwk",schema="newick")
pdc = tree.phylogenetic_distance_matrix()
for i, t1 in enumerate(tree.taxon_namespace[:-1]):
for t2 in tree.taxon_namespace[i+1:]:
tip_pair = {}
tip_dist_list = []
tip_pair[t1] = t2
distance = pdc(t1, t2)
tip_dist_list.append(tip_pair)
tip_dist_list.append(distance)
tree_data.append(tip_dist_list)
print tree_data
This works well except for the way it writes the tip labels. For example an entry in the tree_data list looks like this:
[{<Taxon 0x7fc4c160b090 'ERS135651'>: <Taxon 0x7fc4c160b150 'ERS135335'>}, 0.0001294946558138355]
But the tips in the newick file are just labelled ERS135651 and ERS135335 respectively. How can I get dendropy to write the array with just the original tip labels so this entry would look like this:
[{ERS135651:ERS135335}, 0.0001294946558138355]
(Also I read the dendropy documentation and I'm aware that it says to use treecalc to do this, like this:
pdc = treecalc.PatristicDistanceMatrix(tree)
But I just get an error saying the command does not exist:
AttributeError: 'module' object has no attribute 'PairisticDistanceMatrix'
)
Any suggestions for how I can get this working?
Converting the tip labels to a string converted them to the name surrounded by speech marks, e.g.:
t1 = str(t1)
print t1
Gives:
"'ERS135651'"
So using string splicing to remove the extra speech marks works to convert the tip label back to it's proper name, e.g.:
t1 = t1.replace("'","")

Using subset from arules package in rpy2

It's easy to use apriori algorithm from package arules as:
import rpy2.interactive as r
arules = r.packages.importr("arules")
from rpy2.robjects.vectors import ListVector
od = OrderedDict()
od["supp"] = 0.0005
od["conf"] = 0.7
od["target"] = 'rules'
result = ListVector(od)
my_rules = arules.apriori(dataset, parameter=result)
However, apriori subset uses a different format in subset param:
rules.sub <- subset(rules, subset = rhs %in% "marital-status=Never-married" & lift > 2)
It's possible to use this subset function with rpy2?
If subset is (re)defined in the R package arules, the object arules obtained from importr will contain it. In your python code this will look like arules.subset.
The parameter subset is a slightly different story because it is an R expression. There can be several ways to tackle this. One of them is to wrap it in an ad-hoc R function.
from rpy2.robjects import r
def mysubset(rules, subset_str):
return r("function(rules) { arules::subset(rules, subset = %s) }" % \
subset_str)
rules_sub = mysubset(rules,
"rhs %in% "marital-status=Never-married" & lift > 2)

interpolation of data in dictionary python 3

I have a python program which performs calculations using nested dictionaries. The problem is, if someone enters a value not in one of the dictionaries it won't work. I can either force the user to choose from the values but I'd rather perform interpolation to get the 'expected' value. I cannot figure out how to unpack these dictionaries, get them ordered, and perform the interpolation though.
Any help would be greatly appreciated. My code is below.
Dictionaries like this:
from decimal import *
pga_values = {
"tee": {
100:2.92, 120:2.99, 140:2.97, 160:2.99, 180:3.05, 200:3.12, 240:3.25, 260:3.45, 280:3.65,
300:3.71, 320:3.79, 340:3.86, 360:3.92, 380:3.96, 400:3.99, 420:4.02, 440:4.08, 460:4.17,
480:4.28, 500:4.41, 520:4.54, 540:4.65, 560:4.74, 580:4.79, 600:4.82
},
"fairway": {
5:2.10,10:2.18,20:2.40,30:2.52,40:2.60,50:2.66,60:2.70,70:2.72,80:2.75,
ETC... (edited to be concise)
lie_types = set(pga_values.keys())
user_preshot_lie = input("What was your pre-shot lie type?")
user_preshot_distance_to_hole = Decimal(input('How far away from the hole were you before your shot?'))
user_postshot_lie = input("What was your post-shot lie type?")
user_postshot_distance_to_hole = Decimal(input('How far away from the hole were you?'))
assert user_preshot_lie in lie_types
assert user_postshot_lie in lie_types
preshot_pga_tour_shots_to_hole_out = pga_values[user_preshot_lie][user_preshot_distance_to_hole]
postshot_pga_tour_shots_to_hole_out = pga_values[user_postshot_lie][user_postshot_distance_to_hole]
user_strokes_gained = Decimal((preshot_pga_tour_shots_to_hole_out - postshot_pga_tour_shots_to_hole_out)-1)
print(user_strokes_gained)
Given e.g to isolate the problem a bit:
tee = {
100:2.92, 120:2.99, 140:2.97, 160:2.99, 180:3.05, 200:3.12, 240:3.25, 260:3.45, 280:3.65,
300:3.71, 320:3.79, 340:3.86, 360:3.92, 380:3.96, 400:3.99, 420:4.02, 440:4.08, 460:4.17,
480:4.28, 500:4.41, 520:4.54, 540:4.65, 560:4.74, 580:4.79, 600:4.82
}
you could have...:
import bisect
teekeys = sorted(tee)
def lookup(aval):
where = bisect.bisect_left(teekeys, aval)
lo = teekeys[where-1]
hi = teekeys[where]
if lo==hi: return tee[lo]
delta = float(aval-lo)/(hi-lo)
return delta*tee[hi] + (1-delta)*tee[lo]
So for example:
print(lookup(110))
2.955
print(lookup(530))
4.595
Not sure what you want to do if the value is <min(tee) or >max(tee) -- is raising an exception OK in such anomalous cases?

Embed R code in python

I need to make computations in a python program, and I would prefer to make some of them in R. Is it possible to embed R code in python ?
You should take a look at rpy (link to documentation here).
This allows you to do:
from rpy import *
And then you can use the object called r to do computations just like you would do in R.
Here is an example extracted from the doc:
>>> from rpy import *
>>>
>>> degrees = 4
>>> grid = r.seq(0, 10, length=100)
>>> values = [r.dchisq(x, degrees) for x in grid]
>>> r.par(ann=0)
>>> r.plot(grid, values, type=’lines’)
RPy is your friend for this type of thing.
The scipy, numpy and matplotlib packages all do simular things to R and are very complete, but if you want to mix the languages RPy is the way to go!
from rpy2.robjects import *
def main():
degrees = 4
grid = r.seq(0, 10, length=100)
values = [r.dchisq(x, degrees) for x in grid]
r.par(ann=0)
r.plot(grid, values, type='l')
if __name__ == '__main__':
main()
When I need to do R calculations, I usually write R scripts, and run them from Python using the subprocess module. The reason I chose to do this was because the version of R I had installed (2.16 I think) wasn't compatible with RPy at the time (which wanted 2.14).
So if you already have your R installation "just the way you want it", this may be a better option.
Using rpy2.objects. (Tried and ran some sample R programs)
from rpy2.robjects import r
print(r('''
# Create a vector.
apple <- c('red','green',"yellow")
print(apple)
# Get the class of the vector.
print(class(apple))
##########################
# Create the data for the chart.
v <- c(7,12,28,3,41)
# Give the chart file a name.
png(file = "line_chart.jpg")
# Plot the bar chart.
plot(v,type = "o")
# Save the file.
dev.off()
##########################
# Give the chart file a name.
png(file = "scatterplot_matrices.png")
# Plot the matrices between 4 variables giving 12 plots.
# One variable with 3 others and total 4 variables.
pairs(~wt+mpg+disp+cyl,data = mtcars,
main = "Scatterplot Matrix")
# Save the file.
dev.off()
install.packages("plotly") # Please select a CRAN mirror for use in this session
library(plotly) # to load "plotly"
'''))

Categories

Resources