NotImplementedError: Initial conditions produced too many solutions for constants [SymPy] - python

I attempted to solve this differential equation by adapting the code found here.
import sympy as sp
t = sp.symbols('t', real=True)
x = sp.Function('x', real=True)
diffeq = sp.Eq(x(t).diff(t), sp.sqrt(1 - x(t)**2))
res = sp.dsolve(diffeq, ics={x(0): 0})
The math.se post suggests that a piecewise function satisfies the equation, but perhaps my code does not add all the necessary assumptions. I get the following traceback:
Traceback (most recent call last):
File "/usr/lib/python3.10/idlelib/run.py", line 578, in runcode
exec(code, self.locals)
File "/home/galen/testing.py", line 7, in <module>
res = sp.dsolve(diffeq, ics={x(0): 0})
File "/usr/lib/python3/dist-packages/sympy/solvers/ode/ode.py", line 639, in dsolve
return _helper_simplify(eq, hint, hints, simplify, ics=ics)
File "/usr/lib/python3/dist-packages/sympy/solvers/ode/ode.py", line 694, in _helper_simplify
solved_constants = solve_ics([rv], [r['func']], cons(rv), ics)
File "/usr/lib/python3/dist-packages/sympy/solvers/ode/ode.py", line 808, in solve_ics
raise NotImplementedError("Initial conditions produced too many solutions for constants")
NotImplementedError: Initial conditions produced too many solutions for constants
How do I change my code to correctly solve the ODE?

First, the solver treats the equation as algebraic, that is, it solves x'²=1-x², and it does not get the piecewise solution that are possible, only the fully analytical.
For some reason returning a tuple of possible solutions is not implemented, you can do that manually, see https://stackoverflow.com/a/46979535/3088138
res = sp.dsolve(diffeq)
sol = res.rhs
print([ sol.subs(coeffs) for coeffs in sp.solve(sol.subs(t,0), dict=True) ])
which returns [sin(t), -sin(t)]. The second is not compatible with the ODE in its given form.

Related

Scipy Interpolate PiecewisePolynomial - Error on input data

Hello I am using the following code to try to use scipy's interpolation.
I am getting the following error:
Traceback (most recent call last):
File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 3.4.1\helpers\pydev\pydevd.py", line 1733, in <module>
debugger.run(setup['file'], None, None)
File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 3.4.1\helpers\pydev\pydevd.py", line 1226, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:/Users/%user%/PycharmProjects/price_options_multithread/curve_interpolation.py", line 81, in <module>
tck = interpolate.PiecewisePolynomial(moneyness_,vols_, orders = 2)
File "C:\Users\%user%\Miniconda\lib\site-packages\scipy\interpolate\polyint.py", line 731, in __init__
self._set_yi(yi0)
File "C:\Users\%user%\Miniconda\lib\site-packages\scipy\interpolate\polyint.py", line 131, in _set_yi
self._y_axis = (axis % yi.ndim)
ZeroDivisionError: integer division or modulo by zero
With the code to call the interpolation reading as:
tck = interpolate.PiecewisePolynomial(X,Y, orders = 2)
Where Y is:
[0.2015, 0.3469, 0.2985, 0.2113, 0.19989999999999997, 0.4262, 0.21355000000000002, 0.22260000000000002, 0.21194999999999997, 0.1846, 0.2627, 0.2058, 0.2276, 0.21715, 0.23099999999999998, 0.20235, 0.2165, 0.21165, 0.3836, 0.19594999999999999, 0.20450000000000002, 0.20375, 0.20145000000000002, 0.23525000000000001, 0.2242, 0.22645, 0.27455, 0.22425, 0.2232, 0.1977, 0.19635000000000002, 0.21995, 0.30325, 0.22565]
And X is:
[0.91157701638785, 0.586013796249332, 0.820419314749065, 0.937622073998931, 1.17202759249866, 0.520901152221628, 0.872509429971228, 0.989712189221094, 1.0548248332488, 1.02877977563772, 0.807396785943524, 0.92459954519339, 1.30225288055407, 1.01575724683218, 0.859486901165687, 0.976689660415553, 1.00273471802663, 1.23714023652637, 0.455788508193925, 1.10691494847096, 0.846464372360146, 0.963667131610013, 1.09389241966542, 0.781351728332443, 0.898554487582309, 1.08086989085988, 0.716239084304739, 0.833441843554605, 0.950644602804472, 1.04180230444326, 1.1199374772765, 1.06784736205434, 0.651126440277035, 0.885531958776768]
type(X) and type(Y) give: <type 'list'>
If I do a polynomial interpolation in excel it looks like the following:
Any pointers on what is generating this error would be super helpful.
Thank you!
The parallel fit using python would be best accomplished using numpy polyfit.
Hope this helps someone else in the future.
This is unrelated to the source error - but I will leave to hopefully help someone else.

Sage for Graph Theory, KeyError

I'll start with my code, because this may just be an obvious problem to those with better understanding of the language:
g = graphs.CompleteGraph(60).complement()
for i in range(1,180):
a = randint(0,59)
b = randint(0,59)
h = copy(g)
h.add_edge(a,b)
if h.is_circular_planar():
g.add_edge(a,b)
strong = copy(strong_resolve(g))
S = strong.vertex_cover()
d = {'#00FF00': [], '#FF0000': []}
for v in G.vertices():
if v in S:
d['#FF0000'].append(v)
else:
d['#00FF00'].append(v)
g.plot(layout="spring", vertex_colors=d).show()
strong.plot(vertex_colors=d).show()
new_strong = copy(strong)
for w in new_strong.vertices():
if len(new_strong.neighbors(w)) == 0: #trying to remove
new_strong.delete_vertex(w) #disconnected vertices
new_strong.plot(vertex_colors=d).show()
A couple notes: strong_resolve is a function which takes in a graph and outputs another graph. The first two blocks of code work fine.
My problem is that once I add the third block things don't work anymore. In fiddling around I've gotten variants of this code that when added cause errors, and when removed the errors remain somehow. What happens now is that the for loop seems to go until its end and only then it will give the following error:
Traceback (most recent call last): if h.is_circular_planar():
File "", line 1, in <module>
File "/tmp/tmprzreop/___code___.py", line 30, in <module>
exec compile(u'new_strong.plot(vertex_colors=d).show()
File "", line 1, in <module>
File "/usr/lib/sagemath/local/lib/python2.7/site-packages/sage/misc/decorators.py", line 550, in wrapper
return func(*args, **options)
File "/usr/lib/sagemath/local/lib/python2.7/site-packages/sage/graphs/generic_graph.py", line 15706, in plot
return self.graphplot(**options).plot()
File "/usr/lib/sagemath/local/lib/python2.7/site-packages/sage/graphs/generic_graph.py", line 15407, in graphplot
return GraphPlot(graph=self, options=options)
File "/usr/lib/sagemath/local/lib/python2.7/site-packages/sage/graphs/graph_plot.py", line 247, in __init__
self.set_vertices()
File "/usr/lib/sagemath/local/lib/python2.7/site-packages/sage/graphs/graph_plot.py", line 399, in set_vertices
pos += [self._pos[j] for j in vertex_colors[i]]
KeyError: 0
this can vary in that KeyError: 0 is occasionally 1 or 2 depending on some unknown factor.
I apologize in advance for my horrible code and acknowledge that I really have no idea what I'm doing but I'd really appreciate if someone could help me out here.
I figured it out! It turns out the error came from d having entries that made no sense in new_strong, namely those for vertices that were deleted already. This caused the key error when plot() tried to colour the vertices according to d.

How do I fix the 'TypeError: hasattr(): attribute name must be string' error?

I have the following code:
import pymc as pm
from matplotlib import pyplot as plt
from pymc.Matplot import plot as mcplot
import numpy as np
from matplotlib import rc
res = [18.752, 12.450, 11.832]
v = pm.Uniform('v', 0, 20)
errors = pm.Uniform('errors', 0, 100, size = 3)
taus = 1/(errors ** 2)
mydist = pm.Normal('mydist', mu = v, tau = taus, value = res, observed = True)
model=pm.Model([mydist, errors, taus, v, res])
mcmc=pm.MCMC(model) # This is line 19 where the TypeError originates
mcmc.sample(20000,10000)
mcplot(mcmc.trace('mydist'))
For some reason it doesn't work, I get the 'TypeError: hasattr(): attribute name must be string' error, with the following trace:
Traceback (most recent call last):
File "<ipython-input-49-759ebaf4321c>", line 1, in <module>
runfile('C:/Users/Paul/.spyder2-py3/temp.py', wdir='C:/Users/Paul/.spyder2-py3')
File "C:\Users\Paul\Miniconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 685, in runfile
execfile(filename, namespace)
File "C:\Users\Paul\Miniconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "C:/Users/Paul/.spyder2-py3/temp.py", line 19, in <module>
mcmc=pm.MCMC(model)
File "C:\Users\Paul\Miniconda3\lib\site-packages\pymc\MCMC.py", line 82, in __init__
**kwds)
File "C:\Users\Paul\Miniconda3\lib\site-packages\pymc\Model.py", line 197, in __init__
Model.__init__(self, input, name, verbose)
File "C:\Users\Paul\Miniconda3\lib\site-packages\pymc\Model.py", line 99, in __init__
ObjectContainer.__init__(self, input)
File "C:\Users\Paul\Miniconda3\lib\site-packages\pymc\Container.py", line 606, in __init__
conservative_update(self, input_to_file)
File "C:\Users\Paul\Miniconda3\lib\site-packages\pymc\Container.py", line 549, in conservative_update
if not hasattr(obj, k):
TypeError: hasattr(): attribute name must be string
How do I make it work and output "mydist"?
Edit: I posted a wrong trace at first by accident.
Edit2: It all must be because res doesn't have a name, because it's an array, but I don't know how to assign a name to it, so it'll make this work.
I must admit that I'm not familiar with pymc, but changing it to the following at least made the application run:
mydist = pm.Normal('mydist', mu = v, tau = taus, value = res, observed = False)
mcmc=pm.MCMC([mydist, errors, taus, v, res])
This seems to be because you were wrapping everything in a Model which is an extension of ObjectContainer, but since you passed it a list, MCMC file_items in Container.py tried to assign index 4 in a list to something using replace, but since Model is an ObjectContainer it assigned the key 4 in it's __dict__ causing the weird TypeError you got. Removing the wrapping Model caused MCMC to correctly use an ListContainer instead.
Now, there's probably a bug in Model.py on line 543 where observable stochastics aren't stored in the database - the expression is for object in self.stochastics | self.deterministics: but I suspect it should include self.observable_stochastics too - so I needed to change observable to False or the last line would throw a KeyError.
I'm not familiar enough with pymc to determine if it's actually or bug or desired behaviour so I leave it up to you to submit an issue about it.
You simply need to define res as a numpy array:
res = np.array([18.752, 12.450, 11.832])
Then you'll get an error here mcmc.trace('mydist')because mydist is observed data, and therefore is not sampled. You probably want to plot other variables...

python error using PaCal statistical package

I recently started exploring Python and have encountred a problem with a package named PaCal
Everything looks to be working fine except that I keep having this error anytime I want to print out some data (like in print A.mean() )
the error line is :
Traceback (most recent call last):
File "C:\Users\rmobenta\Desktop\tt.py", line 12, in <module>
print A.interval(0.95)
File "C:\Python27\lib\site-packages\pacal\distr.py", line 229, in interval
return self.quantile(p_lim), self.quantile(1.0 - p_lim)
File "C:\Python27\lib\site-packages\pacal\distr.py", line 215, in quantile
return self.get_piecewise_cdf().inverse(y)
File "C:\Python27\lib\site-packages\pacal\segments.py", line 1721, in inverse
x = findinv(segi.f, a = segi.a, b = segi.b, c = y, rtol = params.segments.cumint.reltol, maxiter = params.segments.cumint.maxiter) # TODO PInd, MInf
File "C:\Python27\lib\site-packages\pacal\utils.py", line 384, in findinv
return brentq(lambda x : fun(x) - c, a, b, **kwargs)
File "C:\Python27\lib\site-packages\scipy\optimize\zeros.py", line 414, in brentq
raise ValueError("rtol too small (%g < %g)" % (rtol, _rtol))
ValueError: rtol too small (1e-16 < 4.44089e-16)
I am using a two-line script that I got for a demo (given by the author of this package) and have no idea how to tackle this issue.
Here is the script:
from pacal import *
Y = UniformDistr(1, 2)
X = UniformDistr(3, 4)
A = atan(Y / X)
A.plot()
print A.mean()
print A.interval(0.95)
The problem comes from PaCal that defines in l.141 of params.py: segments.vumint.reltol = 1e-16.
This is the value passed as rtol in segments.py to the SciPy function brentq().
Finally it is compared to numpy.finfo(float).eps * 2 (l.413 and l.10 of scipy/optimize/zeros.py) and is unfortunately lesser.
So it could be a problem of PaCal implementation, not related to your code.
Note that the value you provided to interval() corresponds to the default value (l.222 of distr.py).
I think you should contact the PaCal developers to get more informations and probably open an issue.

Vector-valued Constraints in NLOpt

I'm trying to add some equality and inequality constraints to my minimization problem.
I am using nlopt Python API.
In particular I would like to add some vector-valued constraints.
My code looks like this example:
def eqconstr(result,x,grad):
if grad.size > 0:
print "gradient to be implemented"
for i in range(len(x)):
if condition: result[i] = 0.
initvect = # some initial guess of the parameters
opt = nlopt.opt(nlopt.LN_PRAXIS,len(initvect))
opt.set_min_objective(function)
tol = np.asarray([0.1]*len(initvect))
opt.add_equality_mconstraint(eqconstr, tol) # this is the call of the constraints (!!!)
opt.set_lower_bounds(-1.) # other parameters to set. not important for this question
opt.set_upper_bounds(1.)
opt.set_initial_step([0.1]*len(initvect))
opt.set_xtol_abs(10e-6)
opt.set_ftol_abs(10e-6)
res = opt.optimize(initvect)
This follows precisely the instructions in the nlopt wiki.
Now if I run this I get:
Traceback (most recent call last):
File "main.py", line 158, in <module>
opt.add_equality_mconstraint(eqconstr, tol)
File "/usr/local/lib/python2.7/dist-packages/nlopt.py", line 269, in add_equality_mconstraint
def add_equality_mconstraint(self, *args): return _nlopt.opt_add_equality_mconstraint(self, *args)
ValueError: nlopt invalid argument
Make sure that your function eqcontr has the same form as your objective function function. Maybe post it as well, so it'll be easy to understand. Also, I cannot see where condition is defined.

Categories