TypeError: hasattr(): attribute name must be string in pymc - pymc

I have looked at the following links but none of them provide the solution I am looking for
https://github.com/pymc-devs/pymc/issues/125
PyMC error : hasattr(): attribute name must be string
I have to write a function which given the priors (and other stuff like data etc) returns a pymc model.
eg
m = pym.Model([fittable_params.values(), rv])
return m
and the in the calling function, when I do mcmc = pymc.MCMC(model)
It gives a long error
Traceback (most recent call last):
File "model_constructor.py", line 81, in <module>
mcmc = pm.MCMC(model)
File "/usr/local/lib/python2.7/dist-packages/pymc-2.3.2-py2.7-linux-i686.egg/pymc/MCMC.py", line 81, in __init__
**kwds)
File "/usr/local/lib/python2.7/dist-packages/pymc-2.3.2-py2.7-linux-i686.egg/pymc/Model.py", line 195, in __init__
Model.__init__(self, input, name, verbose)
File "/usr/local/lib/python2.7/dist-packages/pymc-2.3.2-py2.7-linux-i686.egg/pymc/Model.py", line 98, in __init__
ObjectContainer.__init__(self, input)
File "/usr/local/lib/python2.7/dist-packages/pymc-2.3.2-py2.7-linux-i686.egg/pymc/Container.py", line 605, in __init__
conservative_update(self, input_to_file)
File "/usr/local/lib/python2.7/dist-packages/pymc-2.3.2-py2.7-linux-i686.egg/pymc/Container.py", line 548, in conservative_update
if not hasattr(obj, k):
TypeError: hasattr(): attribute name must be string
On the other hand , if in the function (which returns a model), if I do
m = pm.MCMC([fittable_params.values(), rv])
it is running fine, but the function should return a model so that the user can do whatever he wants with the model in other parts of code.

If the linked solutions don't work for you then as a last resort you can just delete the non-string attributes from the model, since they don't seem to be used anyway.
for key in m.__dict__.keys():
if not isinstance(key, basestring):
del m.__dict__[key]

Related

IllegalArgumentException on any functions with GeoDataFrame

I'm trying to do anything with my GeoDataFrame that I'm importing from the Census website, but when I try to dissolve or overlay with other data frames I get:
pygeos.GEOSException: IllegalArgumentException: Argument must be Polygonal or LinearRing
It won't every overlay itself which is weird. I've exploded it to get rid of the multi polygon and buffered the three invalid polygons, but I'm lost. New to geopandas but I can general feel my way around these things. Any help would be appreciated.
Is my installed package the issue?
Download this file
>>> import geopandas as gpd
>>> SHAPE_URL = 'https://www2.census.gov/geo/tiger/GENZ2018/shp/cb_2018_us_cd116_20m.zip'
>>> cd = gpd.read_file(SHAPE_URL)
>>> cd.dissolve()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/joefedorowicz/Development/virtualenvs/briefcase/lib/python3.9/site-packages/geopandas/geodataframe.py", line 1538, in dissolve
g = self.groupby(group_keys=False, **groupby_kwargs)[self.geometry.name].agg(
File "/Users/joefedorowicz/Development/virtualenvs/briefcase/lib/python3.9/site-packages/pandas/core/groupby/generic.py", line 259, in aggregate
return self._python_agg_general(func, *args, **kwargs)
File "/Users/joefedorowicz/Development/virtualenvs/briefcase/lib/python3.9/site-packages/pandas/core/groupby/groupby.py", line 1173, in _python_agg_general
result, counts = self.grouper.agg_series(obj, f)
File "/Users/joefedorowicz/Development/virtualenvs/briefcase/lib/python3.9/site-packages/pandas/core/groupby/ops.py", line 691, in agg_series
return self._aggregate_series_pure_python(obj, func)
File "/Users/joefedorowicz/Development/virtualenvs/briefcase/lib/python3.9/site-packages/pandas/core/groupby/ops.py", line 741, in _aggregate_series_pure_python
res = func(group)
File "/Users/joefedorowicz/Development/virtualenvs/briefcase/lib/python3.9/site-packages/pandas/core/groupby/groupby.py", line 1160, in <lambda>
f = lambda x: func(x, *args, **kwargs)
File "/Users/joefedorowicz/Development/virtualenvs/briefcase/lib/python3.9/site-packages/geopandas/geodataframe.py", line 1535, in merge_geometries
merged_geom = block.unary_union
File "/Users/joefedorowicz/Development/virtualenvs/briefcase/lib/python3.9/site-packages/geopandas/base.py", line 728, in unary_union
return self.geometry.values.unary_union()
File "/Users/joefedorowicz/Development/virtualenvs/briefcase/lib/python3.9/site-packages/geopandas/array.py", line 652, in unary_union
return vectorized.unary_union(self.data)
File "/Users/joefedorowicz/Development/virtualenvs/briefcase/lib/python3.9/site-packages/geopandas/_vectorized.py", line 892, in unary_union
return _pygeos_to_shapely(pygeos.union_all(data))
File "/Users/joefedorowicz/Development/virtualenvs/briefcase/lib/python3.9/site-packages/pygeos/decorators.py", line 80, in wrapped
return func(*args, **kwargs)
File "/Users/joefedorowicz/Development/virtualenvs/briefcase/lib/python3.9/site-packages/pygeos/set_operations.py", line 388, in union_all
result = lib.unary_union(collections, **kwargs)
pygeos.GEOSException: IllegalArgumentException: Argument must be Polygonal or LinearRing

Sentiment anaysis using Harvard IV-4 dictionary

I was trying to compute the sentiment using Harvard IV-4dictionary.
I installed the "pysentiment" successfully.
I run the following:
import pysentiment as ps
hiv4 = ps.HIV4()
tokens = hiv4.tokenize(text)
score = hiv4.get_score(tokens)
and I got the following error:
Traceback (most recent call last):
File "C:/Users/df/Desk Top/Finalazed/punctuation.py", line 274, in <module>
hiv4 = ps.HIV4()
File "C:\Users\df\AppData\Local\Programs\Python\Python37\lib\site-packages\pysentiment\base.py", line 55, in __init__
self._tokenizer = Tokenizer()
File "C:\Users\df\AppData\Local\Programs\Python\Python37\lib\site-packages\pysentiment\utils.py", line 36, in __init__
self._stopset = self.get_stopset()
File "C:\Users\df\AppData\Local\Programs\Python\Python37\lib\site-packages\pysentiment\utils.py", line 52, in get_stopset
fin = open('%s/%s'%(STATIC_PATH, f), 'rb')
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\df\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages\\pysentiment\\static/Currencies.txt'
Could any body tell why I am getting this? Thanks.
Do copy pysentiment folder in the given path. Actually pysentiment folder doesnt contain static sub folder. You can check it by diplaying hidden folder "local".

FileNotFoundError: No such file: 'someones_epi.nii.gzip'

I am trying to load an MRI, I keep getting the following error:
Traceback (most recent call last):
File "F:/Study/Projects/BTSaG/Programs/t3.py", line 2, in <module> epi_img = nib.load('someones_epi.nii.gzip')
File "C:\Users\AnkitaShinde\AppData\Local\Programs\Python\Python35-32\lib\site-packages\nibabel\loadsave.py", line 38, in load raise FileNotFoundError("No such file: '%s'" % filename)
FileNotFoundError: No such file: 'someones_epi.nii.gzip'
The code is used is as follows:
import nibabel as nib
epi_img = nib.load('someones_epi.nii.gzip')
epi_img_data = epi_img.get_data()
epi_img_data.shape(53, 61, 33)
import matplotlib.pyplot as plt
def show_slices(slices):
""" Function to display row of image slices """
fig, axes = plt.subplots(1, len(slices))
for i, slice in enumerate(slices):
axes[i].imshow(slice.T, cmap="gray", origin="lower")
slice_0 = epi_img_data[26, :, :]
slice_1 = epi_img_data[:, 30, :]
slice_2 = epi_img_data[:, :, 16]
show_slices([slice_0, slice_1, slice_2])
plt.suptitle("Center slices for EPI image")
I have also updated the loadsave.py file in nibabel but it didn't work. Please help.
Edit:
The earlier error was resolved. Now another error has been encountered.
Traceback (most recent call last):File "F:\Study\Projects\BTSaG\Programs\t3.py", line 2, in <module> epi_img = nib.load('someones_epi.nii.gzip')
File "C:\Users\AnkitaShinde\AppData\Local\Programs\Python\Python35-32\lib\site-packages\nibabel\loadsave.py", line 47, in load filename)
nibabel.filebasedimages.ImageFileError: Cannot work out file type of "someones_epi.nii.gzip"
This is an old question, however I may have the solution for it.
I just figured out that nibabel.save() does not allow me to have dot . or dash - in the folder names. These can exist in filenames however. In your case, the current path is:
C:\Users\AnkitaShinde\AppData\Local\Programs\Python\Python35-32\Lib\site-packages\nibabel\someones_epi.nii.gzip
I would change it to:
C:\Users\AnkitaShinde\AppData\Local\Programs\Python\Python35_32\Lib\site_packages\nibabel\someones_epi.nii.gzip
This is just to give an example. Of course, I don't mean that you actually change the names of these package folders as it might cause other errors.
The actual solution would be to move the file someones_epi.nii.gzip to the user structure, something like:
C:\Users\AnkitaShinde\Desktop\nibabel\someones_epi.nii.gzip

Accessing portal_registry via plone.app.theming

I'm trying to use a parameter expression in the plone.app.theming theming-controlpanel that gets a value from the portal_registry to use within the rules.xml file of the theme.
The goal is that if a boolean is set in the registry, the theme can allow/disallow certain content.
So my parameter expression (in theming-controlpanel) is
enable_ad_tags = python:context.portal_registry['lw.portal.enableadtags']
There is a corresponding boolean field in the portal_registry.
The rules.xml file has this rule:
<!-- Global Ad Tags -->
<drop css:theme="#globalAdTags" if="not($enable_ad_tags)" />
The problem is that on my local machine i get this error in the console all the time:
c2014-08-08 09:49:19 ERROR plone.transformchain Unexpected error whilst trying to apply transform chain
Traceback (most recent call last):
File "/Users/aaronwilliams/.buildout/eggs/plone.transformchain-1.0.3-py2.7.egg/plone/transformchain/transformer.py", line 48, in __call__
newResult = handler.transformIterable(result, encoding)
File "/Users/aaronwilliams/.buildout/eggs/plone.app.theming-1.1.1-py2.7.egg/plone/app/theming/transform.py", line 179, in transformIterable
params = prepareThemeParameters(findContext(self.request), self.request, parameterExpressions, cache)
File "/Users/aaronwilliams/.buildout/eggs/plone.app.theming-1.1.1-py2.7.egg/plone/app/theming/utils.py", line 630, in prepareThemeParameters
params[name] = quote_param(expression(expressionContext))
File "/Users/aaronwilliams/.buildout/eggs/Zope2-2.13.20-py2.7.egg/Products/PageTemplates/ZRPythonExpr.py", line 48, in __call__
return eval(self._code, vars, {})
File "PythonExpr", line 1, in <expression>
File "/Users/aaronwilliams/.buildout/eggs/AccessControl-3.0.6-py2.7-macosx-10.8-x86_64.egg/AccessControl/ImplPython.py", line 675, in guarded_getattr
v = getattr(inst, name)
AttributeError: 'DirectoryResource' object has no attribute 'portal_registry'
Is there a problem with the pattern I am trying to use here?
Is there a better/safer way to achieve this?
Using portal instead of context works:
enable_ad_tags = python:portal.portal_registry['lw.portal.enableadtags']
IMHO context should also work, or context does not behave like it does, or the naming is wrong.

gdata.docs.client.DocsClient

I have the following code, reads oauth2 token form file, then try's to perform a doc's list query to find a specific spreadsheet that I want to copy, however no matter what I try the code either errors out or returns with an object containing no document data.
I am using gdata.docs.client.DocsClient which as far as I can tell is version 3 of the API
def CreateClient():
"""Create a Documents List Client."""
client = gdata.docs.client.DocsClient(source=config.APP_NAME)
client.http_client.debug = config.DEBUG
# Authenticate the user with CLientLogin, OAuth, or AuthSub.
if os.path.exists(config.CONFIG_FILE):
f = open(config.CONFIG_FILE)
tok = pickle.load(f)
f.close()
client.auth_token = tok.auth_token
return client
1st query attempt
def get_doc():
new_api_query = gdata.docs.client.DocsQuery(title='RichSheet', title_exact=True, show_collections=True)
d = client.GetResources(q = new_api_query)
this fails with the following stack trace
Traceback (most recent call last):
File "/Users/richard/PycharmProjects/reportone/make_my_report.py", line 83, in <module>
get_doc()
File "/Users/richard/PycharmProjects/reportone/make_my_report.py", line 57, in get_doc
d = client.GetResources(q = new_api_query)
File "/Users/richard/PycharmProjects/reportone/gdata/docs/client.py", line 151, in get_resources
**kwargs)
File "/Users/richard/PycharmProjects/reportone/gdata/client.py", line 640, in get_feed
**kwargs)
File "/Users/richard/PycharmProjects/reportone/gdata/docs/client.py", line 66, in request
return super(DocsClient, self).request(method=method, uri=uri, **kwargs)
File "/Users/richard/PycharmProjects/reportone/gdata/client.py", line 267, in request
uri=uri, auth_token=auth_token, http_request=http_request, **kwargs)
File "/Users/richard/PycharmProjects/reportone/atom/client.py", line 115, in request
self.auth_token.modify_request(http_request)
File "/Users/richard/PycharmProjects/reportone/gdata/gauth.py", line 1047, in modify_request
token_secret=self.token_secret, verifier=self.verifier)
File "/Users/richard/PycharmProjects/reportone/gdata/gauth.py", line 668, in generate_hmac_signature
next, token, verifier=verifier)
File "/Users/richard/PycharmProjects/reportone/gdata/gauth.py", line 629, in build_oauth_base_string
urllib.quote(params[key], safe='~')))
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 1266, in quote
if not s.rstrip(safe):
AttributeError: 'bool' object has no attribute 'rstrip'
Process finished with exit code 1
then my second attempt
def get_doc():
other = gdata.docs.service.DocumentQuery(text_query='RichSheet')
d = client.GetResources(q = other)
this returns an ResourceFeed object, but has no content. I have been through the source code for these function but thing are not any obvious.
Have i missed something ? or should i go back to version 2 of the api ?

Resources