I am trying to solve a very simple ODE using the dsolve sympy function:
from sympy import*
init_printing()
t = symbols('t', real = True)
A = symbols('A', complex = True)
f = Function('rho')(t)
dsolve(Derivative(f, t)+A*f, f)
But, then I get:
Traceback (most recent call last):
File "<ipython-input-9-3d1f21a5ef22>", line 1, in <module>
dsolve(Derivative(f, t)+A*f, f)
File "/home/ted/anaconda3/lib/python3.6/site-packages/sympy/solvers/ode.py", line 566, in dsolve
hints = _desolve(eq, func=func, hint=hint, simplify=True, xi=xi, eta=eta, type='ode', ics=ics, x0=x0, n=n, **kwargs)
File "/home/ted/anaconda3/lib/python3.6/site-packages/sympy/solvers/deutils.py", line 205, in _desolve
n=terms, x0=x0, prep=prep)
File "/home/ted/anaconda3/lib/python3.6/site-packages/sympy/solvers/ode.py", line 1251, in classify_ode
r = _nth_linear_match(reduced_eq, func, order)
File "/home/ted/anaconda3/lib/python3.6/site-packages/sympy/solvers/ode.py", line 3723, in _nth_linear_match
terms[f.derivative_count] += c
AttributeError: 'Derivative' object has no attribute 'derivative_count'
The sympy version is 1.1.1, the python version is 3.6.4 and the ipython version is 6.2.1.
My bad! I tried to use one of the files (ode.py) from the current development version without updating the rest. Now I have it working. Thanks!
Related
So I was working on a project and I came across this error related to sympy:
Traceback (most recent call last):
File "c:\Users\Andres\OneDrive - Centre d'Estudis Monlau\z.ottro\final program try 1\testing area 2.py", line 4, in <module>
Ymin = minimum(root(x,3), x, domain=Interval(-7,7))
File "C:\Users\Andres\AppData\Local\Programs\Python\Python39\lib\site-packages\sympy\calculus\util.py", line 837, in minimum
return function_range(f, symbol, domain).inf
File "C:\Users\Andres\AppData\Local\Programs\Python\Python39\lib\site-packages\sympy\calculus\util.py", line 220, in function_range range_int += Interval(vals.inf, vals.sup, left_open, right_open)
File "C:\Users\Andres\AppData\Local\Programs\Python\Python39\lib\site-packages\sympy\sets\sets.py", line 274, in inf
return self._inf
File "C:\Users\Andres\AppData\Local\Programs\Python\Python39\lib\site-packages\sympy\sets\sets.py", line 1910, in _inf
return Min(*self)
File "C:\Users\Andres\AppData\Local\Programs\Python\Python39\lib\site-packages\sympy\functions\elementary\miscellaneous.py", line 391, in __new__
args = frozenset(cls._new_args_filter(args))
File "C:\Users\Andres\AppData\Local\Programs\Python\Python39\lib\site-packages\sympy\functions\elementary\miscellaneous.py", line 564, in _new_args_filter
raise ValueError("The argument '%s' is not comparable." % arg)
ValueError: The argument '(-7)**(1/3)' is not comparable.
I was able to isolate where happened and recreate the error with these lines:
from sympy import *
x = Symbol("x")
Ymin = minimum(root(x,3), x, domain=Interval(-7,7))
I'm not undrestanding why it's happening, as when is root(x,2) it doasn't have this problem. Does anyone have a clue?
Okey i found an answer online posted by user6655984(stackoverflow) and i wanted to share it online:
expression = root(Abs(x), 3)*sign(x)
This is my first question and I might be doing something wrong.
I am trying to implement a Python application with a library already written in C.
I have created the shared library and I am using ctypes to use it in my Python script.
This is a small part of the script.
from ctypes import *
KYBER_SYMBITES = 32
CRYPTO_PUBLICKEYBITES = 800
CRYPTO_SECRETKEYBITES = 1664
def key_generation():
out_lib = CDLL("./PQCgenKAT_kem.so")
out_lib.crypto_kem_keypair.restype = c_int
out_lib.crypto_kem_keypair.argtypes(POINTER(c_char_p),
POINTER(c_char_p))
pk = [] * CRYPTO_PUBLICKEYBITES
sk = [] * CRYPTO_SECRETKEYBITES
ret_val = out_lib.crypto_kem_keypair(pk,sk)
couple = [] * 2
couple.insert(0,pk)
couple.insert(1,sk)
if ret_val != 0 :
print("ERROR")
return couple
But when I try to test a main file that calls this method I get this error
ale#ale-VirtualBox:~/Desktop/TEST$ /bin/python3
/home/ale/Desktop/TEST/main.py
Traceback (most recent call last):
File "/home/ale/Desktop/TEST/main.py", line 4, in <module>
lista = r.key_generation()
File "/home/ale/Desktop/TEST/RING.py", line 12, in key_generation
out.crypto_kem_keypair.argtypes = [(POINTER(c_char_p),
File "/usr/lib/python3.9/ctypes/__init__.py", line 387, in __getattr__
func = self.__getitem__(name)
File "/usr/lib/python3.9/ctypes/__init__.py", line 392, in __getitem__
func = self._FuncPtr((name_or_ordinal, self))
AttributeError: ./PQCgenKAT_kem.so: undefined symbol: crypto_kem_keypair
This is my first approach to shared libraries. Can anyone help me solve this problem and figure out where am I wrong?
I have defined a new derived dimension with
[molar_energy] = [energy] / [substance]
However, if I do the following it complains:
>>> UR.get_compatible_units('[molar_energy]')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/cedric/.local/share/virtualenvs/MatDB--uGOYMXa/lib/python3.9/site-packages/pint/registry.py", line 881, in get_compatible_units
equiv = self._get_compatible_units(input_units, group_or_system)
File "/Users/cedric/.local/share/virtualenvs/MatDB--uGOYMXa/lib/python3.9/site-packages/pint/registry.py", line 2082, in _get_compatible_units
ret = super()._get_compatible_units(input_units, group_or_system)
File "/Users/cedric/.local/share/virtualenvs/MatDB--uGOYMXa/lib/python3.9/site-packages/pint/registry.py", line 1835, in _get_compatible_units
ret = super()._get_compatible_units(input_units, group_or_system)
File "/Users/cedric/.local/share/virtualenvs/MatDB--uGOYMXa/lib/python3.9/site-packages/pint/registry.py", line 891, in _get_compatible_units
return self._cache.dimensional_equivalents[src_dim]
KeyError: <UnitsContainer({'[length]': 2, '[mass]': 1, '[substance]': -1, '[time]': -2})
I saw that there is a conversion included in a context but I don't use it. What I am doing wrong?
Thanks for your help
PS: logged issue https://github.com/hgrecco/pint/issues/1418
Just leaving the solution here for anyone who faces this issue as well.
I just added a made-up unit and it worked
# Molar Energy
[molar_energy] = [energy] / [substance]
mol_en = J / mol
I am learning OpenMDAO with the first Paraboloid Tutorial. However, where I run the code with the constrained case (add_constraint(...)) I get the error: AttributeError: 'float' object has no attribute 'size'.
I just copied-pasted the code from the tutorial but I can not fine the error. Here is the code:
from __future__ import print_function
from openmdao.api import IndepVarComp, Component, Problem, Group
from openmdao.api import ScipyOptimizer
from openmdao.api import ExecComp
class Paraboloid(Component):
def __init__(self):
super(Paraboloid, self).__init__()
self.add_param('x', val=0.0)
self.add_param('y', val=0.0)
self.add_output('f_xy', shape=1)
def solve_nonlinear(self, params, unknowns, resids):
"""f(x,y) = (x-3)^2 + xy + (y+4)^2 - 3
"""
x = params['x']
y = params['y']
unknowns['f_xy'] = (x-3.0)**2 + x*y + (y+4.0)**2 - 3.0
def linearize(self, params, unknowns, resids):
""" Jacobian for our paraboloid."""
x = params['x']
y = params['y']
J = {}
J['f_xy', 'x'] = 2.0*x - 6.0 + y
J['f_xy', 'y'] = 2.0*y + 8.0 + x
return J
if __name__ == "__main__":
top = Problem()
root = top.root = Group()
root.add('p1', IndepVarComp('x', 3.0))
root.add('p2', IndepVarComp('y', -4.0))
root.add('p', Paraboloid())
# Constraint Equation
root.add('con', ExecComp('c = x-y'))
root.connect('p1.x', 'p.x')
root.connect('p2.y', 'p.y')
root.connect('p.x', 'con.x')
root.connect('p.y', 'con.y')
top.driver = ScipyOptimizer()
top.driver.options['optimizer'] = 'SLSQP'
top.driver.add_desvar('p1.x', lower=-50, upper=50)
top.driver.add_desvar('p2.y', lower=-50, upper=50)
top.driver.add_objective('p.f_xy')
top.driver.add_constraint('con.c', lower=15.0)
top.setup()
top.run()
print('\n')
print('Minimum of %f found at (%f, %f)' % (top['p.f_xy'], top['p.x'], top['p.y']))
I run the script and I get the following:
##############################################
Setup: Checking root problem for potential issues...
No recorders have been specified, so no data will be saved.
Setup: Check of root problem complete.
##############################################
Traceback (most recent call last):
File "paraboloid.py", line 65, in <module>
top.run()
File "/home/sim/.local/lib/python2.7/site-packages/openmdao/core/problem.py", line 1151, in run
self.driver.run(self)
File "/home/sim/.local/lib/python2.7/site-packages/openmdao/drivers/scipy_optimizer.py", line 211, in run
options=self.opt_settings)
File "/home/sim/.local/lib/python2.7/site-packages/scipy/optimize/_minimize.py", line 458, in minimize
constraints, callback=callback, **options)
File "/home/sim/.local/lib/python2.7/site-packages/scipy/optimize/slsqp.py", line 390, in _minimize_slsqp
g = append(fprime(x),0.0)
File "/home/sim/.local/lib/python2.7/site-packages/scipy/optimize/optimize.py", line 292, in function_wrapper
return function(*(wrapper_args + args))
File "/home/sim/.local/lib/python2.7/site-packages/openmdao/drivers/scipy_optimizer.py", line 334, in _gradfunc
return_format='array')
File "/home/sim/.local/lib/python2.7/site-packages/openmdao/core/driver.py", line 834, in calc_gradient
sparsity=sparsity, inactives=inactives)
File "/home/sim/.local/lib/python2.7/site-packages/openmdao/core/problem.py", line 1310, in calc_gradient
inactives=inactives)
File "/home/sim/.local/lib/python2.7/site-packages/openmdao/core/problem.py", line 1561, in _calc_gradient_ln_solver
root._sys_linearize(root.params, unknowns, root.resids)
File "/home/sim/.local/lib/python2.7/site-packages/openmdao/core/system.py", line 947, in _sys_linearize
self._jacobian_cache = linearize(params, unknowns, resids)
File "/home/sim/.local/lib/python2.7/site-packages/openmdao/core/group.py", line 836, in linearize
sub._sys_linearize(sub.params, sub.unknowns, sub.resids)
File "/home/sim/.local/lib/python2.7/site-packages/openmdao/core/system.py", line 947, in _sys_linearize
self._jacobian_cache = linearize(params, unknowns, resids)
File "/home/sim/.local/lib/python2.7/site-packages/openmdao/components/exec_comp.py", line 273, in linearize
J[(u, param)] = numpy.zeros((jval.size, psize))
AttributeError: 'float' object has no attribute 'size'
The error message appear only when I put the constraint equation.
I believe it is a silly error but, can anyone point me the right direction?
Thank you in advance of your help !
This was actually a bug caused by a small change in numpy between 1.12 and 1.13. We have a fix up on the Master branch of the github repository now.
I think you may be using an older version of numpy, under which the imag method doesn't return an array. Can you try upgrading to a later version of numpy? I am using 1.12.0 and the code works for me.
I keep getting
Exception: 'numpy.float64' object is not callable
when trying to minimize a function.
I can call the function I'm trying to minimize as
def testLLCalc():
mmc = MortalityModelCalibrator()
a = mmc.log_likelihood(2000, np.array([[0.6, 0.2, 0.8]]))
but when I try and minimize it by doing
x0 = np.array([0, 0, 0])
res = minimize(-a[0], x0)
I get the exception above. Any help would be appreciated. Full traceback is:
Error
Traceback (most recent call last):
File "C:\Program Files (x86)\JetBrains\WinPython-64bit-3.5.3.0Qt5\python-3.5.3.amd64\lib\unittest\case.py", line 59, in testPartExecutor
yield
File "C:\Program Files (x86)\JetBrains\WinPython-64bit-3.5.3.0Qt5\python-3.5.3.amd64\lib\unittest\case.py", line 601, in run
testMethod()
File "C:\Program Files (x86)\JetBrains\WinPython-64bit-3.5.3.0Qt5\python-3.5.3.amd64\lib\site-packages\nose\case.py", line 198, in runTest
self.test(*self.arg)
File "C:\Users\Matt\Documents\PyCharmProjects\Mortality\src\PennanenMortalityModel_test.py", line 57, in testLLCalc
res = minimize(-a[0], x0)
File "C:\Program Files (x86)\JetBrains\WinPython-64bit-3.5.3.0Qt5\python-3.5.3.amd64\lib\site-packages\scipy\optimize\_minimize.py", line 444, in minimize
return _minimize_bfgs(fun, x0, args, jac, callback, **options)
File "C:\Program Files (x86)\JetBrains\WinPython-64bit-3.5.3.0Qt5\python-3.5.3.amd64\lib\site-packages\scipy\optimize\optimize.py", line 913, in _minimize_bfgs
gfk = myfprime(x0)
File "C:\Program Files (x86)\JetBrains\WinPython-64bit-3.5.3.0Qt5\python-3.5.3.amd64\lib\site-packages\scipy\optimize\optimize.py", line 292, in function_wrapper
return function(*(wrapper_args + args))
File "C:\Program Files (x86)\JetBrains\WinPython-64bit-3.5.3.0Qt5\python-3.5.3.amd64\lib\site-packages\scipy\optimize\optimize.py", line 688, in approx_fprime
return _approx_fprime_helper(xk, f, epsilon, args=args)
File "C:\Program Files (x86)\JetBrains\WinPython-64bit-3.5.3.0Qt5\python-3.5.3.amd64\lib\site-packages\scipy\optimize\optimize.py", line 622, in _approx_fprime_helper
f0 = f(*((xk,) + args))
File "C:\Program Files (x86)\JetBrains\WinPython-64bit-3.5.3.0Qt5\python-3.5.3.amd64\lib\site-packages\scipy\optimize\optimize.py", line 292, in function_wrapper
return function(*(wrapper_args + args))
Exception: 'numpy.float64' object is not callable
scipy's minimize expects a callable function as first argument.
As you did not show your complete code it's just a guessing-game here, but this
res = minimize(-a[0], x0)
has to mean that the first element of a should be a function.
Seeing this line:
a = mmc.log_likelihood(2000, np.array([[0.6, 0.2, 0.8]]))
it does not look like that as probably a scalar is returned.
The effect is simple: scipy want's to call this given function with some argument (x0 at the beginning), but calls some numpy-array value with some argument in your case (which is not valid of course).
Review the docs:
minimize(fun, x0, args=(),...
fun : callable
Objective function.
x0 : ndarray
Initial guess.
args : tuple, optional
Extra arguments passed to the objective function and its derivatives
Do you know what a 'callable' is? It's a function (or equivalent), something can be 'called' with fun(x0, arg0, arg1, ...).
The error tells us that -a[0] is an element of a numpy array, a.
It's not clear whether you are trying to minimize this function, or whether this is part of using minimize. It can't be source of a, because it doesn't return anything.
def testLLCalc():
mmc = MortalityModelCalibrator()
a = mmc.log_likelihood(2000, np.array([[0.6, 0.2, 0.8]]))
# return a ????
So - review your understanding of basic Python, especially the idea of a 'callable'. And run some the minimize examples, to get a better feel for how to use this function.