Place comments inside a multi-line list literal - python

I am doing an optimization problem and writing a gigantic list. I would like to insert comments inside the list like below
my_rhs = [1.0, 1.0, 0.0, 0.0, 0.0,\ #comment1
-1.0, -1.0, -1.0,\ #comment2
0.0, 0.0, 0.0]
but when I do this Python gives an error. How can I comment in the places shown? I tried defining each line as a new list and using + to append but that doesn't seem to work either. Like below
my_rhs = [1.0, 1.0, 0.0, 0.0, 0.0]+\ #comment1
[-1.0, -1.0, -1.0]+\ #comment2
[0.0, 0.0, 0.0]
How can I comment in the shown locations without Python giving an error?

You simply need to remove the backslash characters:
my_rhs = [1.0, 1.0, 0.0, 0.0, 0.0, # comment1
-1.0, -1.0, -1.0, # comment2
0.0, 0.0, 0.0]
Below is a demonstration:
>>> my_rhs = [1.0, 1.0, 0.0, 0.0, 0.0, # comment1
... -1.0, -1.0, -1.0, # comment2
... 0.0, 0.0, 0.0]
>>> my_rhs
[1.0, 1.0, 0.0, 0.0, 0.0, -1.0, -1.0, -1.0, 0.0, 0.0, 0.0]
>>>
The \ character tells Python that the following line is part of the current line. So, it interprets this:
my_rhs = [1.0, 1.0, 0.0, 0.0, 0.0,\ #comment1
-1.0, -1.0, -1.0,\ #comment2
0.0, 0.0, 0.0]
As being equivalent to this:
my_rhs = [1.0, 1.0, 0.0, 0.0, 0.0, #comment1 -1.0, -1.0, -1.0, #comment2 0.0, 0.0, 0.0]
It is noteworthy that PEP 8, the official style-guide for Python code, has a section on wrapping long lines:
The preferred way of wrapping long lines is by using Python's implied
line continuation inside parentheses, brackets and braces. Long lines
can be broken over multiple lines by wrapping expressions in
parentheses. These should be used in preference to using a backslash
for line continuation.
This excerpt from Explicit Line Joining is also relevant:
A line ending in a backslash cannot carry a comment. A backslash does
not continue a comment. A backslash does not continue a token except
for string literals (i.e., tokens other than string literals cannot be
split across physical lines using a backslash). A backslash is illegal
elsewhere on a line outside a string literal.

Related

Problem while doing vector manipulation in Python.(vector component perpendicular to reference vector)

I have a set of coordinates which I would like to manipulate and get desired results. I need to find the horizontal projection of some vector with respect to a reference vector ie, if v1(x1,y1,z1) represent the reference unit vector and v2(x2,y2,z2) be some random vector, I want to find the projection of v2 perpendicular to the direction of v1.
The figurative representation of the required is given as,
https://drive.google.com/file/d/1i3RQm--nLc1dIdZGMpt7oc5KLahOJySk/view?usp=sharing
The vectorial representation is required as
https://drive.google.com/file/d/12QLIoIJ0wckLa8sIgJ8ynMaD33PWrgxQ/view?usp=sharing
The code that I have written is as follows,
catalog=ascii.read("catalog.txt",'r',format='fixed_width_no_header', fast_reader=False, delimiter="\s",names=x,col_starts=y,col_ends=z)
x=[]
y=[]
z=[]
for i in range(0,len(catalog['PSRJ'])):
catalog['DECJD'][i] = catalog['DECJD'][i]+90
x.append(sin(catalog['DECJD'][i])*cos(catalog['RAJD'][i]))
y.append(sin(catalog['DECJD'][i])*sin(catalog['RAJD'][i]))
z.append(cos(catalog['DECJD'][i]))
coord=[]
for i in range(0,len(catalog['PSRJ'])):
coord.append([x[i],y[i],z[i]])
def norm(k):
p=[0.0,0.0,0.0]
p[0]=k[0]/(k[0]**2+k[1]**2+k[2]**2)**0.5
p[1]=k[1]/(k[0]**2+k[1]**2+k[2]**2)**0.5
p[2]=k[2]/(k[0]**2+k[1]**2+k[2]**2)**0.5
return([p[0],p[1],p[2]])
direc = norm(coord[]) #insert key for required coordinate
pix=[]
print(direc)
for i in range(0,len(catalog['PSRJ'])):
if a-5<=catalog['RAJD'][i]<=a+5 and b-5<=catalog['DECJD'][i]<=b+5:
pix.append(coord[i])
if pix[-1]==f:
p=len(pix)
print('p',pix)
val=pix
count=count+1
for i in range(0,count):
for j in range(0,3):
if not(i==p-1):
k=np.dot(direc,pix[i])
val[i][j]=direc[j]*k
val[i][j]=pix[i][j]-val[i][j]
else:
val[i][j]=0.0
print(val)
coord is list containing position vectors,
eg:[[x1,y1,z1],[x2,y2,z2]...]
f is the reference coordinate,
eg:[a,b,c]
OUTPUTS:
[0.049780917594520344, 0.9791671435583665, -0.19685925230782697]
p= 1
[[0.049780917594520344, 0.9791671435583665, -0.19685925230782697]]
[[0.0, 0.0, 0.0]]
[-0.813400538291293, 0.4058994949023155, 0.41668353020665466]
p= 2
[[0.683288067396023, -0.16836586544306054, -0.7104719222515533], [-0.813400538291293, 0.4058994949023155, 0.41668353020665466]]
[[-0.0, -0.0, -0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
[0.15331177729205145, -0.40555298841701465, 0.9011227843804535]
p= 2
[[0.08556174481590322, 0.8925106169941267, -0.4428362974924498], [0.15331177729205145, -0.40555298841701465, 0.9011227843804535]]
[[-0.0, -0.0, -0.0], [0.0, 0.0, 0.0], [-0.0, -0.0, -0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
[0.4561283699625753, 0.08868628538946206, 0.8854838524214335]
p= 3
[[0.016015167632180395, 0.07982154161648915, -0.9966805084377242], [-0.39320614327231507, 0.918593873485819, -0.03967649792044076], [0.4561283699625753, 0.08868628538946206, 0.8854838524214335]]
[[-0.0, -0.0, -0.0], [-0.0, 0.0, -0.0], [0.0, 0.0, 0.0]]
The end result I am getting is null vectors, I don't know if it is my calculation causing the issue, Any insight into the problem would be helpful.

If I put two different dictionaires into a list. I get wrong result. One Dictionary is overwritting the keys/values from the other in the list

I am writing my own rigging framework in maya for learning purposes. And one of the essential thing of my framework is collecting meta data from the scene and put that into a dictionary. So that you can rebuild the rig from that dictionary.
In one method I want to put two dictionaries into a list. But when I do that, it seems that one is overwriting the values of the keys! Like I would use the update function for a dictionary.
Here are the two dictionaries:
{nt.RootOpMetaNode(u'M_ROOT_op_0_METAND'): [{'component_type': u'single_control', 'component_side': u'M', 'main_op_nd_ws_matrix': Matrix([[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]), 'sub_op_nd_ws_matrix': [], 'connection_types': [u'translate', u'rotate', u'scale'], 'ik_spaces_ref': None, 'connect_nd': None, 'child_nd': [], 'parent_nd': None, u'control_shape': 0, 'component_index': 0, 'component_name': u'Test'}]}
{nt.RootOpMetaNode(u'M_ROOT_op_0_METAND1'): [{'component_type': u'single_control', 'component_side': u'L', 'main_op_nd_ws_matrix': Matrix([[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]), 'sub_op_nd_ws_matrix': [], 'connection_types': [u'translate', u'rotate', u'scale'], 'ik_spaces_ref': None, 'connect_nd': None, 'child_nd': [], 'parent_nd': None, u'control_shape': 0, 'component_index': 1, 'component_name': u'Mom'}]}
And here the wrong result after I append them to a list:
[{nt.RootOpMetaNode(u'M_ROOT_op_0_METAND'): [{'component_type': u'single_control', 'component_side': u'L', 'main_op_nd_ws_matrix': Matrix([[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]), 'sub_op_nd_ws_matrix': [], 'connection_types': [u'translate', u'rotate', u'scale'], 'ik_spaces_ref': None, 'connect_nd': None, 'child_nd': [], 'parent_nd': None, u'control_shape': 0, 'component_index': 1, 'component_name': u'Mom'}]}, {nt.RootOpMetaNode(u'M_ROOT_op_0_METAND1'): [{'component_type': u'single_control', 'component_side': u'L', 'main_op_nd_ws_matrix': Matrix([[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]), 'sub_op_nd_ws_matrix': [], 'connection_types': [u'translate', u'rotate', u'scale'], 'ik_spaces_ref': None, 'connect_nd': None, 'child_nd': [], 'parent_nd': None, u'control_shape': 0, 'component_index': 1, 'component_name': u'Mom'}]}]
Here is the metod which create the list:
def get_operators_meta_data_from_god_node(self):
"""
Collect the operators meta data from all root meta nodes in the scene.
Return:
List: Filled with a dictionary for each root_meta_nd.
[{"root_meta_nd":pmc.PyNode(), "meta_data":List}]
"""
result = []
# get the god meta node from scene.
self.get_god_meta_nd_from_scene()
if self.god_meta_nd:
# get all other meta nodes from scene.
all_meta_nodes = self.god_meta_nd.list_meta_nodes()
# get all root meta nodes from all meta nodes.
all_root_nodes = [
root
for root in all_meta_nodes
if root.attr(constants.META_TYPE).get() == constants.META_TYPE_A
]
# iterate about all root nodes and collect the meta data from it.
for root_meta_node in all_root_nodes:
# Gives back a dictionary with meta data from root node.
temp = self.get_operators_meta_data_from_root_meta_node(
root_meta_node)
# Append the meta data dictonary to the result list.
result.append(temp)
return result
Can anybody help me please? It's driving me nuts :-(

Hausdorff Distance 2D

i am new to programming and currently working with Python. Can someone explain to me why is it that by changing the order of variable will end up with different results as compared to Euclidean distance obtaining the same results?
Below is the array i used for this experiment to understand the use
u = np.array([[1.0, 0.0], [0.0, 1.0], [-1.0, 0.0], [0.0, -1.0]])
v = np.array([[2.0, 0.0], [0.0, 2.0], [-2.0, 0.0], [0.0, -4.0]])
(directed_hausdorff(u, v)[:])) --> output = (2.23606797749979, 3, 0) and
(directed_hausdorff(v, u)[:])) --> output = v,u = (3.0, 3, 3)
Thank you!

Recommender System : ValueError at / could not convert string to float:

I am trying to build a movie recommender web application using python and django. I am trying to use a command to take the movie's descriptions and create an information retrieval system to allow the user to find movies typing some relevant words. This tf-idf model is then saved in the Django cache together with the initial recommendation systems models (CF item-based and log-likelihood ratio).
The command to load data is
python manage.py load_data --input=plots.csv --nmaxwords=30000 --umatrixfile=umatrix.csv
Terminal Error
File "/home/anthra/server_movierecsys/books_recsys_app/management/commands/load_data.py", line 80, in handle
matr[0]=newrow
ValueError: could not convert string to float: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
plot.csv screenshot
The code is as follows:
matr = np.empty([1,ndims])
titles = []
cnt=0
for m in xrange(nmovies):
moviedata = MovieData()
moviedata.title=tot_titles[m]
moviedata.description=tot_textplots[m]
moviedata.ndim= ndims
moviedata.array=json.dumps(vec_tfidf[m].toarray()[0].tolist())
moviedata.save()
newrow = moviedata.array
if cnt==0:
matr[0]=newrow
else:
matr = np.vstack([matr, newrow])
titles.append(moviedata.title)
cnt+=1
moviedata.array output
json.dumps generates a string to the newrow variable. And you're then trying to write the variable you serialized to a numpy array.
As I understand it, numpy arrays are confined to a declared type (implicit if you don't provide one explicitly), so when you have initialized the array with floats, the code tries to type-cast your string var newrow to a float value - which fails because you're not passing in a string representing a number but an iterable of numbers.
Minor change gave awesome result. Changed
moviedata.array=json.dumps(vec_tfidf[m].toarray()[0].tolist())"
to
moviedata.array=vec_tfidf[m].toarray()[0]

gaussian fit with scipy.optimize.curve_fit in python with wrong results

I am having some trouble to fit a gaussian to data. I think the problem is that most of the elements are close to zero, and there not many points to actually be fitted. But in any case, I think they make a good dataset to fit, and I don't get what is confussing python. Here is the program, I have also added a line to plot the data so you can see what I am trying to fit
#Gaussian function
def gauss_function(x, a, x0, sigma):
return a*np.exp(-(x-x0)**2/(2*sigma**2))
# program
from scipy.optimize import curve_fit
x = np.arange(0,21.,0.2)
# sorry about these data!
y = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2.2888599818864958e-275, 1.0099964933708256e-225, 4.9869496866403137e-184, 4.4182929795060327e-149, 7.2953754336628778e-120, 1.6214815763354974e-95, 2.5845990267696154e-75, 1.2195550372375896e-58, 5.6756631456872126e-45, 7.2520963306599953e-34, 6.0926453402093181e-25, 7.1075523112494745e-18, 2.1895584709541657e-12, 3.1040093615952226e-08, 3.2818874974043519e-05, 0.0039462011337049593, 0.077653596114448178, 0.33645159419151383, 0.40139213808285212, 0.15616093582013874, 0.0228751827752081, 0.0014423440677009125, 4.4400754532288282e-05, 7.4939123408714068e-07, 7.698340466102054e-09, 5.2805658851032628e-11, 2.6233358880470556e-13, 1.0131613609937094e-15, 3.234727006243684e-18, 9.0031014316344088e-21, 2.2867065482392331e-23, 5.5126221075296919e-26, 1.3045106781768978e-28, 3.1185031969890313e-31, 7.7170036365830092e-34, 2.0179753504732056e-36, 5.6739187799428708e-39, 1.7403776988666581e-41, 5.8939645426573027e-44, 2.2255784749636281e-46, 9.4448944519959299e-49, 4.5331936383388069e-51, 2.4727435506007072e-53, 1.5385048936078214e-55, 1.094651071873419e-57, 8.9211199390945735e-60, 8.3347561634783632e-62, 8.928140776588251e-64, 1.0960564546383266e-65, 1.5406342485015278e-67, 2.4760905399114866e-69, 4.5423744881977258e-71, 9.4921949220625905e-73, 2.2543765002199549e-74, 6.0698995872666723e-76, 1.8478996852922248e-77, 6.3431644488676084e-79, 0.0, 0.0, 0.0, 0.0]
plot(x,y) #Plot the curve, the gaussian is quite clear
plot(x,y,'ok') #Overplot the dots
# Try to fit the result
popt, pcov = curve_fit(gauss_function, x, y)
The problem is that the results for popt is
print popt
array([ 7.39717176e-10, 1.00000000e+00, 1.00000000e+00])
Any hint on why this could be happening?
Thanks!
Your problem is with the initial parameters of the curve_fit. By default, if no other information is given, it will start with an array of 1, but this obviously lead to a radically wrong result. This can be corrected simply by giving a reasonable starting vector.
To do this, I start from the estimated mean and standard deviation of your dataset
#estimate mean and standard deviation
meam = sum(x * y)
sigma = sum(y * (x - m)**2)
#do the fit!
popt, pcov = curve_fit(gauss_function, x, y, p0 = [1, mean, sigma])
#plot the fit results
plot(x,gauss_function(x, *popt))
#confront with the given data
plot(x,y,'ok')
This will perfectly approximate your results. Remember that curve fitting in general cannot work unless you start from a good point (inside the convergence basin, to be clear), and this doesn't depend on the implementation. Never do blind fit when you can use your knowledge!

Categories