Error: _print_LambertW() got an unexpected keyword argument 'exp' - python

I am trying multiply the following equation with its derivative using Python, I made the following code
from sympy.abc import x, y, z, a,b
from sympy import *
a, b, n, t,N_0,x = symbols('a b n t N_0 x')
f=-LambertW(-N_0*b**(-a)*log(b)*log(t + 1))/((t + 1)*log(b)*log(t + 1))
f_a=diff(f,a)
d=f*f_a
d
When I try to run the code:
TypeError Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/IPython/core/formatters.py in __call__(self, obj)
336 method = get_real_method(obj, self.print_method)
337 if method is not None:
--> 338 return method()
339 return None
340 else:
10 frames
/usr/local/lib/python3.7/dist-packages/sympy/printing/printer.py in _print(self, expr, **kwargs)
327 printmethod = '_print_' + cls.__name__
328 if hasattr(self, printmethod):
--> 329 return getattr(self, printmethod)(expr, **kwargs)
330 # Unknown object, fall back to the emptyPrinter.
331 return self.emptyPrinter(expr)
TypeError: _print_LambertW() got an unexpected keyword argument 'exp'

This error is no longer raised in the most recent version of SymPy (or at least the development version).

Related

How to correct solve trigonometric functions equation by sympy?

I have an equation with trigonometric functions as below:
eq = Eq(cos(theta_3), a_2*a_3*(-a_2**2/2 - a_3**2/2 + b**2/2 + z_4**2/2))
Then I try solve θ by sympy and code as below:
solve([eq, theta_3 < pi ], theta_3)
But it raise a exception and part of the information as follows:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
File E:\conda\lib\site-packages\sympy\polys\polyutils.py:211, in _parallel_dict_from_expr_if_gens(exprs, opt)
209 base, exp = decompose_power_rat(factor)
--> 211 monom[indices[base]] = exp
212 except KeyError:
KeyError: cos(_theta_3)
During handling of the above exception, another exception occurred:
PolynomialError Traceback (most recent call last)
File E:\conda\lib\site-packages\sympy\solvers\inequalities.py:809, in _solve_inequality(ie, s, linear)
808 try:
--> 809 p = Poly(expr, s)
810 if p.degree() == 0:
File E:\conda\lib\site-packages\sympy\polys\polytools.py:182, in Poly.__new__(cls, rep, *gens, **args)
181 else:
--> 182 return cls._from_expr(rep, opt)
File E:\conda\lib\site-packages\sympy\polys\polytools.py:311, in Poly._from_expr(cls, rep, opt)
310 """Construct a polynomial from an expression. """
--> 311 rep, opt = _dict_from_expr(rep, opt)
312 return cls._from_dict(rep, opt)
Why does such an exception raise?
How to correct solve trigonometric functions equation by sympy?

How to plot SymPy's built-in functions using sympy.plotting

Hey I am pretty new to SymPy. I am trying to use SymPy's built-in plotting to plot some functions. My codes are as follows:
from sympy import Symbol, sin, Function, pi,exp
from sympy.plotting import plot
t = Symbol('t')
source = t**2
plot(source,(t,0,1))
This works perfectly. However, notice that I have also imported functions such as sin and exp above. However, I am finding anything involving these functions, SymPy will not plot. For example,
source1 = exp(t)
source2= sin(t)
plot(source1,(t,0,1))
plot(source2,(t,0,1))
Neither of these will work. The error I received is as follows, using the case with sin as an example:
TypeError Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/sympy/plotting/experimental_lambdify.py in __call__(self, args, kwargs)
194 #The result can be sympy.Float. Hence wrap it with complex type.
--> 195 result = complex(self.lambda_func(args))
196 if abs(result.imag) > 1e-7 * abs(result):
TypeError: complex() first argument must be a string or a number, not 'FunctionClass'
During handling of the above exception, another exception occurred:
AttributeError Traceback (most recent call last)
<ipython-input-45-85c4f08c25e4> in <module>
1 f0 = 15
2 source = sin(t)
----> 3 plot(exp(t),(t,0,1))
/usr/local/lib/python3.6/dist-packages/sympy/plotting/plot.py in plot(*args, **kwargs)
1556 plots = Plot(*series, **kwargs)
1557 if show:
-> 1558 plots.show()
1559 return plots
1560
/usr/local/lib/python3.6/dist-packages/sympy/plotting/plot.py in show(self)
189 self._backend.close()
190 self._backend = self.backend(self)
--> 191 self._backend.show()
192
193 def save(self, path):
/usr/local/lib/python3.6/dist-packages/sympy/plotting/plot.py in show(self)
1246
1247 def show(self):
-> 1248 self.process_series()
1249 #TODO after fixing https://github.com/ipython/ipython/issues/1255
1250 # you can uncomment the next line and remove the pyplot.show() call
/usr/local/lib/python3.6/dist-packages/sympy/plotting/plot.py in process_series(self)
1243 if isinstance(self.parent, PlotGrid):
1244 parent = self.parent.args[i]
-> 1245 self._process_series(series, ax, parent)
1246
1247 def show(self):
/usr/local/lib/python3.6/dist-packages/sympy/plotting/plot.py in _process_series(self, series, ax, parent)
1072 # Create the collections
1073 if s.is_2Dline:
-> 1074 collection = self.LineCollection(s.get_segments())
1075 ax.add_collection(collection)
1076 elif s.is_contour:
/usr/local/lib/python3.6/dist-packages/sympy/plotting/plot.py in get_segments(self)
661 list_segments.append([p, q])
662
--> 663 f_start = f(self.start)
664 f_end = f(self.end)
665 sample(np.array([self.start, f_start]),
/usr/local/lib/python3.6/dist-packages/sympy/plotting/experimental_lambdify.py in __call__(self, args, kwargs)
234 ' problematic. We are trying a failback method'
235 ' that may still work. Please report this as a bug.')
--> 236 if abs(result.imag) > 1e-7 * abs(result):
237 return None
238 else:
AttributeError: type object 'exp' has no attribute 'imag'
This might be something trivial, but as a beginner I am having quite a hard time figuring these out. Really appreciate your help!!

Error when using pandas dataframe in R cell, in rpy2, Jupyter Notebook

I want to use ggplot2 within Jupyter Notebook. However, when I try to make an R magic cell and introduce a variable, I get an error.
Here is the code (one paragraph indicates one cell):
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import rpy2
%matplotlib inline
from rpy2.robjects import pandas2ri
pandas2ri.activate()
%load_ext rpy2.ipython
%%R
library(ggplot2)
data = pd.read_csv('train_titanic.csv')
%%R -i data -w 900 -h 480 -u px
With this last cell, I get the following error (incl traceback):
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/robjects/pandas2ri.py in py2rpy_pandasdataframe(obj)
54 try:
---> 55 od[name] = conversion.py2rpy(values)
56 except Exception as e:
~/anaconda3/envs/catenv/lib/python3.7/functools.py in wrapper(*args, **kw)
839
--> 840 return dispatch(args[0].__class__)(*args, **kw)
841
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/robjects/pandas2ri.py in py2rpy_pandasseries(obj)
125 if type(x) is not homogeneous_type:
--> 126 raise ValueError('Series can only be of one type, or None.')
127 # TODO: Could this be merged with obj.type.name == 'O' case above ?
ValueError: Series can only be of one type, or None.
During handling of the above exception, another exception occurred:
TypeError Traceback (most recent call last)
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/rinterface_lib/sexp.py in from_object(cls, obj)
367 try:
--> 368 mv = memoryview(obj)
369 res = cls.from_memoryview(mv)
TypeError: memoryview: a bytes-like object is required, not 'Series'
During handling of the above exception, another exception occurred:
AttributeError Traceback (most recent call last)
<ipython-input-14-75e210679e4a> in <module>
----> 1 get_ipython().run_cell_magic('R', '-i data -w 900 -h 480 -u px', '\n\n')
~/anaconda3/envs/catenv/lib/python3.7/site-packages/IPython/core/interactiveshell.py in run_cell_magic(self, magic_name, line, cell)
2360 with self.builtin_trap:
2361 args = (magic_arg_s, cell)
-> 2362 result = fn(*args, **kwargs)
2363 return result
2364
</home/morgan/anaconda3/envs/catenv/lib/python3.7/site-packages/decorator.py:decorator-gen-130> in R(self, line, cell, local_ns)
~/anaconda3/envs/catenv/lib/python3.7/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
185 # but it's overkill for just that one bit of state.
186 def magic_deco(arg):
--> 187 call = lambda f, *a, **k: f(*a, **k)
188
189 if callable(arg):
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/ipython/rmagic.py in R(self, line, cell, local_ns)
721 raise NameError("name '%s' is not defined" % input)
722 with localconverter(converter) as cv:
--> 723 ro.r.assign(input, val)
724
725 tmpd = self.setup_graphics(args)
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/robjects/functions.py in __call__(self, *args, **kwargs)
190 kwargs[r_k] = v
191 return (super(SignatureTranslatedFunction, self)
--> 192 .__call__(*args, **kwargs))
193
194
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/robjects/functions.py in __call__(self, *args, **kwargs)
111
112 def __call__(self, *args, **kwargs):
--> 113 new_args = [conversion.py2rpy(a) for a in args]
114 new_kwargs = {}
115 for k, v in kwargs.items():
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/robjects/functions.py in <listcomp>(.0)
111
112 def __call__(self, *args, **kwargs):
--> 113 new_args = [conversion.py2rpy(a) for a in args]
114 new_kwargs = {}
115 for k, v in kwargs.items():
~/anaconda3/envs/catenv/lib/python3.7/functools.py in wrapper(*args, **kw)
838 '1 positional argument')
839
--> 840 return dispatch(args[0].__class__)(*args, **kw)
841
842 funcname = getattr(func, '__name__', 'singledispatch function')
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/robjects/pandas2ri.py in py2rpy_pandasdataframe(obj)
59 'The error is: %s'
60 % (name, str(e)))
---> 61 od[name] = StrVector(values)
62
63 return DataFrame(od)
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/robjects/vectors.py in __init__(self, obj)
382
383 def __init__(self, obj):
--> 384 super().__init__(obj)
385 self._add_rops()
386
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/rinterface_lib/sexp.py in __init__(self, obj)
286 super().__init__(obj)
287 elif isinstance(obj, collections.abc.Sized):
--> 288 super().__init__(type(self).from_object(obj).__sexp__)
289 else:
290 raise TypeError('The constructor must be called '
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/rinterface_lib/sexp.py in from_object(cls, obj)
370 except (TypeError, ValueError):
371 try:
--> 372 res = cls.from_iterable(obj)
373 except ValueError:
374 msg = ('The class methods from_memoryview() and '
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/rinterface_lib/conversion.py in _(*args, **kwargs)
26 def _cdata_res_to_rinterface(function):
27 def _(*args, **kwargs):
---> 28 cdata = function(*args, **kwargs)
29 # TODO: test cdata is of the expected CType
30 return _cdata_to_rinterface(cdata)
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/rinterface_lib/sexp.py in from_iterable(cls, iterable, populate_func)
317 if populate_func is None:
318 cls._populate_r_vector(iterable,
--> 319 r_vector)
320 else:
321 populate_func(iterable, r_vector)
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/rinterface_lib/sexp.py in _populate_r_vector(cls, iterable, r_vector)
300 r_vector,
301 cls._R_SET_VECTOR_ELT,
--> 302 cls._CAST_IN)
303
304 #classmethod
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/rinterface_lib/sexp.py in _populate_r_vector(iterable, r_vector, set_elt, cast_value)
237 def _populate_r_vector(iterable, r_vector, set_elt, cast_value):
238 for i, v in enumerate(iterable):
--> 239 set_elt(r_vector, i, cast_value(v))
240
241
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/rinterface_lib/sexp.py in _as_charsxp_cdata(x)
430 return x.__sexp__._cdata
431 else:
--> 432 return conversion._str_to_charsxp(x)
433
434
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/rinterface_lib/conversion.py in _str_to_charsxp(val)
118 s = rlib.R_NaString
119 else:
--> 120 cchar = _str_to_cchar(val)
121 s = rlib.Rf_mkCharCE(cchar, _CE_UTF8)
122 return s
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/rinterface_lib/conversion.py in _str_to_cchar(s, encoding)
97 def _str_to_cchar(s, encoding: str = 'utf-8'):
98 # TODO: use isStrinb and installTrChar
---> 99 b = s.encode(encoding)
100 return ffi.new('char[]', b)
101
AttributeError: 'float' object has no attribute 'encode'
So I find that it is not possible to even start an R magic cell while importing my pandas dataframe object. However, I have tried creating R vectors inside the cell, and find I can plot these using ggplot2 with no issues.
I am using Python 3.7.6, rpy2 3.1.0, jupyter-notebook 6.0.3and am using Ubuntu 18.04.2 LTS on Windows Subsystem for Linux.
The problem is most likely with one (or more) columns having more than one type - therefore it is impossible to transfer the data into an R vector (which can hold only one data type). The traceback may be overwhelming, but here is the relevant part:
ValueError: Series can only be of one type, or None.
Which column it is? Difficult to say without looking at the dataset that you load, but my general solution is to check the types in the columns:
types = data.applymap(type).apply(set)
types[types.apply(len) > 1]
Anything returned by the snippet above would be a candidate culprit. There are many different ways of dealing with the problem, depending on the exact nature of the data. Workarounds that I frequently use include:
calling data = data.infer_objects() - helps if the pandas did not catch up with a dtype change and still stores the data with (suboptimal) Python objects
filling NaN with an empty string or a string constant if you have missing values in a string column (e.g. str_columns = str_columns.fillna(''))
dates.apply(pd.to_datetime, axis=1) if you have datetime objects but the dtype is object
using df.applymap(lambda x: datetime.combine(x, datetime.min.time()) if not isinstance(x, datetime) else x) if you have a mixture of date and datetime objects
In some vary rare cases pandas stores the data differently than expected by rpy2 (following certain manipulations); then writing the dataframe down to a csv file and reading it from the disk again helps - but this is likely not what you are facing here, as you start from a newly read dataframe.
I just noticed there might be an even simpler reason for the problem. For some reason, pandas2ri requires you to call pandas2ri.activate()after importing it. This solved the problem for me.

ValueError invalid literal error with Python Multiprocessing Pool

I have a function that i'm trying to run in parallel. The function is of the form
def parallelFunc(curUser):
if curUser in neighbors.getUsers(): #neighbors is a global object of a class
userData = createData.createData(inpMat1,inpMat2,inpMat3, neighbors.getNeighbors(curUser) )
#inpMatX are numpy arrays/scipy sparse arrays/lists with global scope
return userData # tried returning a double value too, get the same error
else:
return 0
pp = Pool(4) # tried with different values
ret = pp.map(parallelFunc, userList)
When I try running this, I get the following error
ValueError: invalud literal for float(): 1.235443508738e
The error is in multiprocessing/pool.pyc . I'm doing this in an IPython notebook. Any ideas as to why this would happen?
Stack Trace :
ValueError Traceback (most recent call last)
<ipython-input-99-2731048b72e2> in <module>()
3
4 #st = time.time()
----> 5 ret = pp.map(parallelFunc, userList)
6 #ft = time.time()
7
/opt/Anaconda/lib/python2.7/multiprocessing/pool.pyc in map(self, func, iterable, chunksize)
249 '''
250 assert self._state == RUN
--> 251 return self.map_async(func, iterable, chunksize).get()
252
253 def imap(self, func, iterable, chunksize=1):
/opt/Anaconda/lib/python2.7/multiprocessing/pool.pyc in get(self, timeout)
565 return self._value
566 else:
--> 567 raise self._value
568
569 def _set(self, i, obj):
ValueError: invalid literal for float(): 1.34716296703.978260894942e+06

PyMC3 & Theano - Theano code that works stop working after pymc3 import

Some simple theano code that works perfectly, stop working when I import pymc3
Here some snipets in order to reproduce the error:
#Initial Theano Code (this works)
import theano.tensor as tsr
x = tsr.dscalar('x')
y = tsr.dscalar('y')
z = x + y
#Snippet 1
import pymc3 as pm
import theano.tensor as tsr
x = tsr.dscalar('x')
y = tsr.dscalar('y')
z = x + y
#Snippet 2
import theano.tensor as tsr
import pymc3 as pm
x = tsr.dscalar('x')
y = tsr.dscalar('y')
z = x + y
#Snippet 3
import pymc3 as pm
x = pm.theano.tensor.dscalar('x')
y = pm.theano.tensor.dscalar('y')
z = x + y
And I get the following error for each of the previous snippets:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/Users/tom/anaconda/lib/python3.4/site-packages/theano/gof/op.py in __call__(self, *inputs, **kwargs)
516 try:
--> 517 storage_map[ins] = [self._get_test_value(ins)]
518 compute_map[ins] = [True]
/Users/tom/anaconda/lib/python3.4/site-packages/theano/gof/op.py in _get_test_value(cls, v)
478
--> 479 raise AttributeError('%s has no test value' % v)
480
AttributeError: x has no test value
During handling of the above exception, another exception occurred:
ValueError Traceback (most recent call last)
<ipython-input-2-ef8582b040f8> in <module>()
3 x = pm.theano.tensor.dscalar('x')
4 y = pm.theano.tensor.dscalar('y')
----> 5 z = x + y
/Users/tom/anaconda/lib/python3.4/site-packages/theano/tensor/var.py in __add__(self, other)
126 def __add__(self, other):
127 try:
--> 128 return theano.tensor.basic.add(self, other)
129 # We should catch the minimum number of exception here.
130 # Otherwise this will convert error when Theano flags
/Users/tom/anaconda/lib/python3.4/site-packages/theano/gof/op.py in __call__(self, *inputs, **kwargs)
523 run_perform = False
524 elif config.compute_test_value == 'raise':
--> 525 raise ValueError('Cannot compute test value: input %i (%s) of Op %s missing default value' % (i, ins, node))
526 elif config.compute_test_value == 'ignore':
527 # silently skip test
ValueError: Cannot compute test value: input 0 (x) of Op Elemwise{add,no_inplace}(x, y) missing default value
Any Ideas ?
Thanks in advance
I think this is related to pymc3 setting theano.config.compute_test_value = 'raise': https://github.com/pymc-devs/pymc3/blob/master/pymc3/model.py#L395
You can explicitly set theano.config.compute_test_value back to 'ignore' to get rid of the error.
Solution proposed here lasts a bit longer than setting the flag. In your shell type:
theano-cache purge

Categories

Resources