'Map' object has no attribute 'on_displayed - python

I get an error when I run the code below in jupiter lab. How can I fix ?
# Set study area using ipyleaflet
m = Map(center=(14, -90), zoom = 6)
draw_control = DrawControl(polyline={}, circlemarker={}, polygon={})
draw_control.rectangle = {
"shapeOptions": {
"fillColor": "#fca45d",
"color": "#fca45d",
"fillOpacity": 0.2
}
}
m.add_control(draw_control)
m
AttributeError Traceback (most recent call last)
Cell In[36], line 2
1 # Set study area using ipyleaflet
----> 2 m = Map(center=(14, -90), zoom = 6)
3 draw_control = DrawControl(polyline={}, circlemarker={}, polygon={})
4 draw_control.rectangle = {
5 "shapeOptions": {
6 "fillColor": "#fca45d",
(...)
9 }
10 }
File ~/.local/lib/python3.10/site-packages/ipyleaflet/leaflet.py:457, in Map.__init__(self, **kwargs)
455 def __init__(self, **kwargs):
456 super(Map, self).__init__(**kwargs)
--> 457 self.on_displayed(self._fire_children_displayed)
458 if self.default_tiles is not None:
459 self.layers = (self.default_tiles,)
AttributeError: 'Map' object has no attribute 'on_displayed'
I get an error when I run the code below in jupiter lab. How can I fix ?

Related

AttributeError: module 'PIL.Image' has no attribute 'Resampling'

While implementing "layoutparser" I get this error. What is wrong with this?
model = lp.Detectron2LayoutModel('lp://PubLayNet/mask_rcnn_X_101_32x8d_FPN_3x/config',
extra_config=["MODEL.ROI_HEADS.SCORE_THRESH_TEST", 0.5],
label_map={0: "Text", 1: "Title", 2: "List", 3:"Table", 4:"Figure"})
AttributeError Traceback (most recent call last)
<ipython-input-8-d8a245fa8739> in <module>()
----> 1 model = lp.Detectron2LayoutModel('lp://PubLayNet/mask_rcnn_X_101_32x8d_FPN_3x/config',
2 extra_config=["MODEL.ROI_HEADS.SCORE_THRESH_TEST", 0.5],
3 label_map={0: "Text", 1: "Title", 2: "List", 3:"Table", 4:"Figure"}) 34 frames /usr/local/lib/python3.7/dist-packages/PIL/Image.py in
__getattr__(name)
63 stacklevel=2,
64 )
---> 65 return categories[name]
66 elif name in ("NEAREST", "NONE"):
67 warnings.warn( AttributeError: module 'PIL.Image' has no attribute 'Resampling'
Convert image to numpy array.
import numpy as np
image = np.asarray(image)
model.detect(image)
If you are using Colab tool then this error might occur if your code is using GPU but your Colab is configured with CPU version.
Runtime --> Change Runtime Type --> Select "GPU"

how can I resolve this key error in this section of program

I have a problem with this section of my code
that it returns to the diffusion analysts of
materials
from pymatgen.analysis.diffusion.analyzer import (
DiffusionAnalyzer,
fit_arrhenius,
get_conversion_factor,
)
import json
from pymatgen.analysis.diffusion.aimd.van_hove import VanHoveAnalysis
%matplotlib inline
data = json.load(open(".../py.pro/mp-1138_LiF.json", "r"))
new_obj = DiffusionAnalyzer.from_dict(data)
vhfunc = VanHoveAnalysis(diffusion_analyzer=new_obj, avg_nsteps=5, ngrid=101, rmax=10.0,
step_skip=5, sigma=0.1, species = ["Li", "F"])
vhfunc.get_3d_plot(mode="self")
vhfunc.get_3d_plot(mode="distinct")
and the key error says this
KeyError Traceback (most recent call last)
<ipython-input-4-17584fdb7b1f> in <module>
3 data = json.load(open("J:/py.pro/mp-1138_LiF.json", "r"))
4
----> 5 new_obj = DiffusionAnalyzer.from_dict(data)
6
7 vhfunc = VanHoveAnalysis(diffusion_analyzer=new_obj, avg_nsteps=5, ngrid=101, rmax=10.0,
~\Anaconda3\lib\site-packages\pymatgen\analysis\diffusion\analyzer.py in from_dict(cls, d)
766 return cls(
767 structure,
--> 768 np.array(d["displacements"]),
769 specie=d["specie"],
770 temperature=d["temperature"],
KeyError: 'displacements'
how it resolves?
does it return to the program?

RRuntimeError: Error in qr.lm(object) : lm object does not have a proper 'qr' component. Rank zero or should not have used lm(.., qr=FALSE)

I am using rpy2 to access a function which accepts the variables and then predicts the output for a GAM Model.
However, I am facing the following error during python runtime:
RRuntimeError Traceback (most recent call last)
<ipython-input-12-e571fb4e8082> in <module>
----> 1 gam_model(0.1, 13000, 1300, .5, 9000, 4, 10)
{PATH_TO_ENV}\lib\site-packages\rpy2\robjects\functions.py in __call__(self, *args, **kwargs)
176 v = kwargs.pop(k)
177 kwargs[r_k] = v
--> 178 return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs)
179
180 pattern_link = re.compile(r'\\link\{(.+?)\}')
{PATH_TO_ENV}\lib\site-packages\rpy2\robjects\functions.py in __call__(self, *args, **kwargs)
104 for k, v in kwargs.items():
105 new_kwargs[k] = conversion.py2ri(v)
--> 106 res = super(Function, self).__call__(*new_args, **new_kwargs)
107 res = conversion.ri2ro(res)
108 return res
RRuntimeError: Error in qr.lm(object) : lm object does not have a proper 'qr' component.
Rank zero or should not have used lm(.., qr=FALSE)
There does not seem to be a problem in in the R side as I tried the script alone and was able to run the function as expected. Following is the code for the R function and the Python call respectively. Also I tested the integration on a simple Linear regression model with one variable and it was working fine as well.
The R function:
gam_model <- function(var1, var2,
var3, var4, var5,
var6, var7, ...){
x <- data.frame(var1=var1, var2=var2,
var3=var3, var4=var4,
var5=var5, var6=var6, var7=var7)
model <- readRDS("models/gam_1.rds")
result <- predict(model, x)
return(result)
}
The python call:
from rpy2 import robjects
from rpy2.robjects import pandas2ri
r = robjects.r
r['source']('model_functions.R')
gam_model = robjects.globalenv['gam_model']
y_pred = gam_model(0.1, 13000, 1300, .5, 9000, 4, 10)
I have identified the issue as the package 'mgcv' is not installed. Installing will resolve the issue.

geoseries.to_crs() failed when use geopandas to calculate distance

I want to calculate distance between two lat/log point using geopandas series.distance and measure the result by unit meters, I know I should define crs first, but I tried several times to use to_crs(), but it is showing an error: b'no arguments in initialization list' seems like the function never worked. Anyone can help me on this problem?
def wgs84_to_CGCS2000(df,code):
result=df.to_crs(from_epsg(code))
return result
city=wgs84_to_CGCS2000(city,4549)
kfc=wgs84_to_CGCS2000(kfc,4549)
RuntimeError Traceback (most recent call last)
<ipython-input-42-c0d1c4e6af6a> in <module>
2 result=df.to_crs(from_epsg(code))
3 return result
----> 4 city=wgs84_to_CGCS2000(city,4549)
5 kfc=wgs84_to_CGCS2000(kfc,4549)
<ipython-input-42-c0d1c4e6af6a> in wgs84_to_CGCS2000(df, code)
1 def wgs84_to_CGCS2000(df,code):
----> 2 result=df.to_crs(from_epsg(code))
3 return result
4 city=wgs84_to_CGCS2000(city,4549)
5 kfc=wgs84_to_CGCS2000(kfc,4549)
C:\ProgramData\Anaconda3\lib\site-packages\geopandas\geodataframe.py in to_crs(self, crs, epsg, inplace)
441 else:
442 df = self.copy()
--> 443 geom = df.geometry.to_crs(crs=crs, epsg=epsg)
444 df.geometry = geom
445 df.crs = geom.crs
C:\ProgramData\Anaconda3\lib\site-packages\geopandas\geoseries.py in to_crs(self, crs, epsg)
302 except TypeError:
303 raise TypeError('Must set either crs or epsg for output.')
--> 304 proj_in = pyproj.Proj(self.crs, preserve_units=True)
305 proj_out = pyproj.Proj(crs, preserve_units=True)
306 project = partial(pyproj.transform, proj_in, proj_out)
C:\ProgramData\Anaconda3\lib\site-packages\pyproj\__init__.py in __new__(self, projparams, preserve_units, **kwargs)
360 # on case-insensitive filesystems).
361 projstring = projstring.replace('EPSG','epsg')
--> 362 return _proj.Proj.__new__(self, projstring)
363
364 def __call__(self, *args, **kw):
_proj.pyx in _proj.Proj.__cinit__()
RuntimeError: b'no arguments in initialization list'

Error when trying to apply log method to pandas data frame column in Python

So, I am very new to Python and Pandas (and programming in general), but am having trouble with a seemingly simple function. So I created the following dataframe using data pulled with a SQL query (if you need to see the SQL query, let me know and I'll paste it)
spydata = pd.DataFrame(row,columns=['date','ticker','close', 'iv1m', 'iv3m'])
tickerlist = unique(spydata[spydata['date'] == '2013-05-31'])
After that, I have written a function to create some new columns in the dataframe using the data already held in it:
def demean(arr):
arr['retlog'] = log(arr['close']/arr['close'].shift(1))
arr['10dvol'] = sqrt(252)*sqrt(pd.rolling_std(arr['ret'] , 10 ))
arr['60dvol'] = sqrt(252)*sqrt(pd.rolling_std(arr['ret'] , 10 ))
arr['90dvol'] = sqrt(252)*sqrt(pd.rolling_std(arr['ret'] , 10 ))
arr['1060rat'] = arr['10dvol']/arr['60dvol']
arr['1090rat'] = arr['10dvol']/arr['90dvol']
arr['60dis'] = (arr['1060rat'] - arr['1060rat'].mean())/arr['1060rat'].std()
arr['90dis'] = (arr['1090rat'] - arr['1090rat'].mean())/arr['1090rat'].std()
return arr
The only part that I'm having a problem with is the first line of the function:
arr['retlog'] = log(arr['close']/arr['close'].shift(1))
Which, when I run, with this command, I get an error:
result = spydata.groupby(['ticker']).apply(demean)
Error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-196-4a66225e12ea> in <module>()
----> 1 result = spydata.groupby(['ticker']).apply(demean)
2 results2 = result[result.date == result.date.max()]
3
C:\Python27\lib\site-packages\pandas-0.11.0-py2.7-win32.egg\pandas\core\groupby.pyc in apply(self, func, *args, **kwargs)
323 func = _intercept_function(func)
324 f = lambda g: func(g, *args, **kwargs)
--> 325 return self._python_apply_general(f)
326
327 def _python_apply_general(self, f):
C:\Python27\lib\site-packages\pandas-0.11.0-py2.7-win32.egg\pandas\core\groupby.pyc in _python_apply_general(self, f)
326
327 def _python_apply_general(self, f):
--> 328 keys, values, mutated = self.grouper.apply(f, self.obj, self.axis)
329
330 return self._wrap_applied_output(keys, values,
C:\Python27\lib\site-packages\pandas-0.11.0-py2.7-win32.egg\pandas\core\groupby.pyc in apply(self, f, data, axis, keep_internal)
632 # group might be modified
633 group_axes = _get_axes(group)
--> 634 res = f(group)
635 if not _is_indexed_like(res, group_axes):
636 mutated = True
C:\Python27\lib\site-packages\pandas-0.11.0-py2.7-win32.egg\pandas\core\groupby.pyc in <lambda>(g)
322 """
323 func = _intercept_function(func)
--> 324 f = lambda g: func(g, *args, **kwargs)
325 return self._python_apply_general(f)
326
<ipython-input-195-47b6faa3f43c> in demean(arr)
1 def demean(arr):
----> 2 arr['retlog'] = log(arr['close']/arr['close'].shift(1))
3 arr['10dvol'] = sqrt(252)*sqrt(pd.rolling_std(arr['ret'] , 10 ))
4 arr['60dvol'] = sqrt(252)*sqrt(pd.rolling_std(arr['ret'] , 10 ))
5 arr['90dvol'] = sqrt(252)*sqrt(pd.rolling_std(arr['ret'] , 10 ))
AttributeError: log
I have tried changing the function to np.log as well as math.log, in which case I get the error
TypeError: only length-1 arrays can be converted to Python scalars
I've tried looking this up, but haven't found anything directly applicable. Any clues?
This happens when the datatype of the column is not numeric. Try
arr['retlog'] = log(arr['close'].astype('float64')/arr['close'].astype('float64').shift(1))
I suspect that the numbers are stored as generic 'object' types, which I know causes log to throw that error. Here is a simple illustration of the problem:
In [15]: np.log(Series([1,2,3,4], dtype='object'))
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-15-25deca6462b7> in <module>()
----> 1 np.log(Series([1,2,3,4], dtype='object'))
AttributeError: log
In [16]: np.log(Series([1,2,3,4], dtype='float64'))
Out[16]:
0 0.000000
1 0.693147
2 1.098612
3 1.386294
dtype: float64
Your attempt with math.log did not work because that function is designed for single numbers (scalars) only, not lists or arrays.
For what it's worth, I think this is a confusing error message; it once stumped me for awhile, anyway. I wonder if it can be improved.

Categories

Resources