As far as I checked, the indentation is correct, no brackets are missing and I have only imported packages in the previous lines But I still get invalid syntax error.
#!/usr/bin/python
import bpy
import mathutils
import numpy as np
from math import radians
from mathutils import Vector
from math import radians
from mathutils import Matrix
from bpy import context
def transform_mesh('parent', 'obj_to_be_transformed', (translate_x, translate_y, translate_z), (rot_x,rot_y,rot_z)):
obj= bpy.data.objects[parent]
obj1= bpy.data.objects[obj_to_be_transformed]
initial_mat = obj1.matrix_world
...some code
(x,y,z) = (translate_x, translate_y, translate_z)
orig_loc_mat = Matrix.Translation(orig_loc+ mathutils.Vector((x,y,z)))
...some more code
eul = mathutils.Euler((radians(rot_x), radians(rot_y), radians(rot_z)), 'XYZ')
rot_mat = eul.to_matrix().to_4x4()
obj.matrix_world = orig_loc_mat * rot_mat * orig_rot_mat * orig_scale_mat
bpy.context.scene.update()
return [initial_loc,initial_rot,initial_scale,loc,rot,scale]
transform_result= transform_mesh('Armature','Coil',(5,0,0),(0,0,1))
print (transform_result)
And error is:
Error: File "D:\users\gayathri\Gayathri\Synthetic_data_generation\Final\HMI_Depth_coilA_final_final.blend\Untitled", line 18
def transform_mesh('parent', 'obj_to_be_transformed', (translate_x, translate_y, translate_z), (rot_x,rot_y,rot_z)):
^
SyntaxError: invalid syntax
location: <unknown location>:-1
def transform_mesh('parent', 'obj_to_be_transformed',
should be
def transform_mesh(parent, obj_to_be_transformed,
surely?
1- Remove strings from arguments
2- Remove tuples from arguments and attribute them in the function (It might be useful to add some checks)
So, here you are:
def transform_mesh(parent, obj_to_be_transformed, translate, rot):
translate_x, translate_y, translate_z= translate
rot_x,rot_y,rot_z = rot
# etc
transform_result= transform_mesh('Armature','Coil',(5,0,0),(0,0,1))
print (transform_result)
Tuple parameters are not supported in Python3, but you can pass it as a variable and unpack it after defining the function.
def transform_mesh(translate_xyz):
translate_x, translate_y, translate_z = translate_xyz
You need to provide variables as arguments to the function.
try something like:
def transform_mesh(parent, obj_to_be_transformed, t1, t2):
Although in the code you have shared, you are always using t1 and t2 as tuples. But in case you want to use x, y and z separately, you can do it by referencing the index:
x = t1[0]
y = t1[1]
In this line the function parameter are passed in incorrect way,
def transform_mesh('parent', 'obj_to_be_transformed', (translate_x, translate_y, translate_z), (rot_x,rot_y,rot_z)):
The Correct syntax would be:
def transform_mesh(parent, obj_to_be_transformed, *translate_xyz, *rot_xyz): #*translate_xyz and *rot-xyz are tuple parameter
Related
I have written the below code string and trying to execute it through the exec method. This code is running fine when I run it with global mode only.
codeRule = """import math
def fun (n):
data = n
data = data * math.pi
print(data)
return data
dd = fun(n)"""
codeObejct = compile(codeRule, 'sumstring', 'exec')
exec(codeObejct, dict(n = 10))
But my use case needs dd value outside of exec so I have used the below parameter to get dd value inside another dataframe.
loc = {}
exec(codeObejct, dict(n = 10), loc)
dd = loc["dd"]
But as soon as I use local it starts giving me an error regarding Lib Import such as
File "<stdin>", line 1, in <module>
File "sumstring", line 7, in <module>
File "sumstring", line 4, in fun
NameError: name 'math' is not defined
Can someone please help to solve this problem?
I have checked the below question's answer but I don't know how to fit it in my use case.
Why doesn't an import in an exec in a function work?
Finally, I got solution,
I was missing one point with exec. Below is the solution that I got and I hope it will work for my actual Use case
codeRule = """import math
def fun (n):
data = n
data = data * math.pi
return data
"""
#export Function
exec (codeRule, globals())
dd = fun(10)
dd
31.41592653589793
Your answer looks good. Here's another more-convoluted approach if you need a fallback for your use case:
codeRule = """\
import math
def fun(n):
data = n
data = data * math.pi
return data
loc['dd'] = fun(n)
"""
codeObject = compile(codeRule, 'sumstring', 'exec')
loc = {}
exec(codeObject, dict(n=10, loc=loc))
print(f"{loc['dd']=}") # -> loc['dd']=31.41592653589793
I am trying to cythonize my Python code to improve performance.
I didn't make any change to my original python code, I just run the setup.py and get the .c files.
Now I have this issue: when I perform a basic math operation in Python, it works fine, while in Cython it doesn't work as expected.
The code snippet is the following, here I try to calculate the y-coordinate of a given x on a circle of center [3,0] and radius 1:
import math
import numpy as np
def calculateY(x, center, radius):
a = -2*center[0]
b = -2*center[1]
c = center[0]**2 + center[1]**2 - radius**2
tmp = (b)**2 - 4*(c) - 4*(a)*x - 4*(x**2)
return 1/2*(-b + math.sqrt(tmp)) ###### I only want the y>0
C1, R1 = [3,0], 1
Pstart = np.array([2.13766028, 0.50633014])
print(calculateY(Pstart[0], C1, R1))
If I run this in Python, I get y = 0.5063301366799338 which is the right result.
If I cythonize the code and then run it by import my_code, I get y = 0.0 which tells me that the y is empty (actually the code doesn't even print anything, I got this from another function where I print the y)
Am I doing something wrong whit the syntax?
Thanks in advance.
Edit:
here's my setup.py:
import distutils.core
import Cython.Build
distutils.core.setup(
ext_modules = Cython.Build.cythonize("my_code.pyx"))
I run the cython version with:
import my_code
The output is empy.
EDIT 2:
Thanks to joni, I changed the division in my original code and now it works!
I suspect that cdivision=True is enabled inside your setup.py. In C, the division of two integer literals cuts off all decimal places. Consequently, the 1/2 inside your return statement equals 0.0. Instead, simply use floating-point literals, i.e.
# my_code.pyx
def calculateY(x, center, radius):
a = -2*center[0]
b = -2*center[1]
c = center[0]**2 + center[1]**2 - radius**2
tmp = (b)**2 - 4*(c) - 4*(a)*x - 4*(x**2)
return 1.0/2.0*(-b + math.sqrt(tmp)) # <--- Note the 1.0/2.0
Then, after installing the Cython module by python3 setup.py install, you can use it from Python:
# mwe.py
from my_code import calculateY
import numpy as np
C1, R1 = [3,0], 1
Pstart = np.array([2.13766028, 0.50633014])
print(calculateY(Pstart[0], C1, R1)) # Output: 0.5063301366799338
Note that a Cython .pyx file only contains the function and class definitions. You have to call your cythonized module's functions from Python.
I have wrote the following code in derivation.py:
def Interpolation(ableitungWinkel,x_values):
z = medfilt(derivation,3)
diff = abs(derivation-z)
new_smootheddata = np.where(diff>3,z,derivation)
x=np.arange(0,len(x_values[:-2]))
f = interp1d(x,new_smootheddata,kind="linear")
xnew = np.arange(0, len(x_values[:-3]),0.01)
ynew = f(xnew)
s=plt.plot(x, z,"o",xnew, ynew, "-")
return s
In my project there is also integration.py. In this Python file I need the values which z calculates in the function def interpolation for this calculation:
def horizontalAcceleration(strideData):
resultsHorizontal = list()
for i in range (len(strideData)):
yAngle = z
xAcceleration = strideData.to_numpy()[i, 4]
yAcceleration = strideData.to_numpy()[i, 5]
a = ((m.cos(m.radians(yAngle)))*yAcceleration)-((m.sin(m.radians(yAngle)))*xAcceleration)
resultsHorizontal.append(a)
resultsHorizontal.insert(0, 0)
return resultsHorizontal
As you can see I have already added z to the function def horizontalAcceleration at the place where it should go.
To use z there, I tried the following: from derivation import z
But that doesn't work. Because then I get the error: ImportError: cannot import name 'z' from 'derivation'
Have anybody an idea how I can solve this problem? Thanks for helping me.
I think that your misunderstanding is because you think a function is like a script that has been run and modified a.global state. That's not what a function is. A function is a series of actions performed on its inputs (ignoring closures for a minute) which returns some results. You can call it many times, but without calling it, it never executes. Once it stops executing all its variables go out of scope.
You can import and call a function though. So you can change the return type of Interpolation to return everything you need somewhere else. E.g.
def Interpolation(...):
...
return {'z': z, 's': s}
Then somewhere you import that function, call it, get back all the data you need, then pass that to your other function.
import Interpolation from derivation
# get z and s in a dict result
result = Interpolation(...)
# pass s as well as the other argument to your other function
horizontalAcceleration(strideData, result['s'])
I have a .py file with a function that calculates the gradient of a function at a point and returns the value of that gradient at the point. The function takes a np.array([2,]) as input and outputs another np.array([2,]). I am confused as to how I can call the function from the cmd line and run the function with a specified input.
Here is a code snippet:
import numpy as np
def grad(x):
x_1 = x[0]
x_2 = x[1]
df_dx_1 = 6*x
df_dx_2 = 8*x_2
df_dx = np.array([df_dx_1, df_dx_2])
return np.transpose(df_dx)
I would really appreciate your help!
EDIT: This question differs from the popular command line thread because I have a specific issue of not being able to recognise the numpy input
First change script to (Here it uses if __name__='__main__' to check if it is running from script, then import sys and pass first argument using sys.argv[0] to the function):
import numpy as np
def grad(x):
x_1 = x[0]
x_2 = x[1]
df_dx_1 = 6*x
df_dx_2 = 8*x_2
df_dx = np.array([df_dx_1, df_dx_2])
return np.transpose(df_dx)
if __name__ == '__main__':
import sys
grad(sys.argv[1])
And call it like:
python "YOURSCRIPTPATH.py" argument_1
You can have more than one command line argument:
import sys
import numpy as np
def grad(x):
# your grad function here
arr = np.array([int(sys.argv[1]), int(sys.argv[2])])
print(grad(arr))
Usage:
python gradient.py 10 5
You could just something like this in the command line:
$ python -c 'from YOURFILE import grad; print(grad(your_argument))'
I'm pretty new to python and I got stuck on this:
I'd like to use scipy.optimize.minimize to maximize a function and I'm having some problem with the extra arguments of the function I defined.
I looked for a solution in tons of answered questions but I can't find anything that solves my problem.
I saw in Structure of inputs to scipy minimize function how to pass extra arguments that one wants to be constant in the minimization of the function and my code seems fine to me from this point of view.
This is my code:
import numpy as np
from scipy.stats import pearsonr
import scipy.optimize as optimize
def min_pears_function(a,exp):
(b,c,d,e)=a
return (1-(pearsonr(b + exp[0] * c + exp[1] * d + exp[2],e)[0]))
a = (log_x,log_y,log_t,log_z) # where log_x, log_y, log_t and log_z are numpy arrays with same length
guess_PF=[0.6,2.0,0.2]
res = optimize.minimize(min_pears_function, guess_PF, args=(a,), options={'xtol': 1e-8, 'disp': True})
When running the code I get the following error:
ValueError: need more than 3 values to unpack
But I can't see what needed argument I'm missing. The function seems to work fine, so I guess the problem is in optimize.minimize call?
Your error occurs here:
def min_pears_function(a,exp):
# XXX: This is your error line
(b,c,d,e)=a
return (1-(pearsonr(b + exp[0] * c + exp[1] * d + exp[2],e)[0]))
This is because:
the initial value you pass to optimize.minimize is guessPF which has just three values ([0.6,2.0,0.2]).
this initial value is passed to min_pears_function as the variable a.
Did you mean for it to be passed as exp? Is it exp you wish to solve for? In that case, redefine the signature as:
def min_pears_function(exp, a):
...