Change in JModelica transfer_optimization_problem method? - python

I believe that there has been a change in the JModelica transfer_optimization_problem method that is not documented. If there is a new way of doing this, I'd like to know as I am new to JModelica. I am following the manual for JModelica 2.2 and I noticed that
from pyjmi import transfer_optimization_problem
does not exist, but this does:
from pyjmi.casadi_interface import transfer_optimization_problem
But this line returns an error:
op = transfer_optimization_problem("VDP_Opt", "VDP_Opt.mop")
The error:
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-27-e1ed8260993b> in <module>()
----> 1 op = transfer_optimization_problem("VDP_Opt", "VDP_Opt.mop")
/home/paperspace/JModelica/Python/pyjmi/casadi_interface.py in transfer_optimization_problem(class_name, file_name, compiler_options, compiler_log_level, accept_model)
147
148 """
--> 149 op = OptimizationProblem()
150 _transfer_optimization_problem(op, class_name=class_name, file_name=file_name,
151 compiler_options=compiler_options,
/home/paperspace/JModelica/Python/pyjmi/common/core.py in __init__(self)
44
45 def __init__(self):
---> 46 raise Exception("This is an abstract class it can not be instantiated.")
47
48 def optimize(self):
Exception: This is an abstract class it can not be instantiated.

Related

"TypeError: <class 'numpy.typing._dtype_like._SupportsDType'> is not a generic class" when importing the plotly.express library

I want to create a simple plotly chart from a .csv file that I fetched from an API.
I import the library, pass the dataframe, and get the error:
TypeError: <class 'numpy.typing._dtype_like._SupportsDType'> is not a generic class
code:
import plotly.express as px
df=pd.read_csv('file.csv')
What might be the problem, and what does this error mean?
Full error traceback:
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9952/1054373791.py in <module>
1 from dash import Dash, dcc, html, Input, Output
----> 2 import plotly.express as px
3 import pandas as pd
~\anaconda3\lib\site-packages\plotly\express\__init__.py in <module>
13 )
14
---> 15 from ._imshow import imshow
16 from ._chart_types import ( # noqa: F401
17 scatter,
~\anaconda3\lib\site-packages\plotly\express\_imshow.py in <module>
9
10 try:
---> 11 import xarray
12
13 xarray_imported = True
~\anaconda3\lib\site-packages\xarray\__init__.py in <module>
----> 1 from . import testing, tutorial
2 from .backends.api import (
3 load_dataarray,
4 load_dataset,
5 open_dataarray,
~\anaconda3\lib\site-packages\xarray\testing.py in <module>
7 import pandas as pd
8
----> 9 from xarray.core import duck_array_ops, formatting, utils
10 from xarray.core.dataarray import DataArray
11 from xarray.core.dataset import Dataset
~\anaconda3\lib\site-packages\xarray\core\duck_array_ops.py in <module>
24 from numpy import where as _where
25
---> 26 from . import dask_array_compat, dask_array_ops, dtypes, npcompat, nputils
27 from .nputils import nanfirst, nanlast
28 from .pycompat import cupy_array_type, dask_array_type, is_duck_dask_array
~\anaconda3\lib\site-packages\xarray\core\npcompat.py in <module>
70 List[Any],
71 # anything with a dtype attribute
---> 72 _SupportsDType[np.dtype],
73 ]
74 except ImportError:
~\anaconda3\lib\typing.py in inner(*args, **kwds)
273 except TypeError:
274 pass # All real errors (not unhashable args) are raised below.
--> 275 return func(*args, **kwds)
276 return inner
277
~\anaconda3\lib\typing.py in __class_getitem__(cls, params)
997 else:
998 # Subscripting a regular Generic subclass.
--> 999 _check_generic(cls, params, len(cls.__parameters__))
1000 return _GenericAlias(cls, params)
1001
~\anaconda3\lib\typing.py in _check_generic(cls, parameters, elen)
207 """
208 if not elen:
--> 209 raise TypeError(f"{cls} is not a generic class")
210 alen = len(parameters)
211 if alen != elen:
TypeError: <class 'numpy.typing._dtype_like._SupportsDType'> is not a generic class
I got the same error, it is dependency issue, plotly.express (5.9.0) is not working with numpy==1.20, if you upgrade numpy==1.21.6 it will solve your error.
pip install numpy==1.21.6
I was having same issue when I updated xarray. I tried updating numpy but conda environment was restricting it. Updating the whole conda environment helped me resolve this error.
conda update --all
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_4960/3694415272.py in <module>
----> 1 plotly.express.__version__
~\anaconda3\lib\site-packages\_plotly_utils\importers.py in __getattr__(import_name)
37 return getattr(class_module, class_name)
38
---> 39 raise AttributeError(
40 "module {__name__!r} has no attribute {name!r}".format(
41 name=import_name, __name__=parent_name
AttributeError: module 'plotly' has no attribute 'express'

allennlp.common.JsonDict, TypeError: FileLock.acquire: `poll_intervall` is not present

would you please tell me why when i use the following script:
from allennlp.common import JsonDict
i get the following error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-7-58adc5745662> in <module>()
----> 1 from allennlp.common import JsonDict
10 frames
/usr/local/lib/python3.7/dist-packages/overrides/signature.py in ensure_all_kwargs_defined_in_sub(super_sig, sub_sig, super_type_hints, sub_type_hints, check_first_parameter, method_name)
134 name, True, sub_has_var_kwargs, sub_sig, super_param
135 ):
--> 136 raise TypeError(f"{method_name}: `{name}` is not present.")
137 elif name in sub_sig.parameters and super_param.kind != Parameter.VAR_KEYWORD:
138 sub_index = list(sub_sig.parameters.keys()).index(name)
TypeError: FileLock.acquire: `poll_intervall` is not present.

Unable to export a python chainladder triangle to excel sheet

I am exploring the chainladder package. I tried to export a triangle structure into an excel sheet. But it throws an error. Has anyone ever faced this kind of problem. I am using chainladder==0.7.9 with pandas==0.24.2. Here is my simple code by reading their documentation https://chainladder-python.readthedocs.io/en/latest/tutorials/index.html
import pandas as pd
import numpy as np
import chainladder as cl
raa = cl.load_sample('raa')
cl.load_template('triangle', triangle=raa.latest_diagonal).to_excel('raa_example.xlsx')
I get the following error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
e:\pyworkspace37\chainladderdemo\venv\lib\site-packages\chainladder\utils\exhibits.py in load_template(template, env, **kwargs)
24 try:
---> 25 return load_yaml(template, env, **kwargs)
26 except:
e:\pyworkspace37\chainladderdemo\venv\lib\site-packages\xlcompose\templates.py in load_yaml(template, env, str_only, **kwargs)
108 else:
--> 109 return _make_xlc(yaml.load(template, Loader=yaml.SafeLoader), **kwargs)
110
e:\pyworkspace37\chainladderdemo\venv\lib\site-packages\xlcompose\templates.py in _make_xlc(template, **kwargs)
51 return core.Tabs(*[('Sheet1', item) for item in tabs])
---> 52 key = list(template.keys())[0]
53 if key in ['Row', 'Column']:
AttributeError: 'str' object has no attribute 'keys'
During handling of the above exception, another exception occurred:
AttributeError Traceback (most recent call last)
<ipython-input-17-270670213d97> in <module>
----> 1 cl.load_template('triangle', triangle=raa.latest_diagonal).to_excel('raa_example.xlsx')
2 #,type(raa.latest_diagonal)
3 type(raa_model.ultimate_)
e:\pyworkspace37\chainladderdemo\venv\lib\site-packages\chainladder\utils\exhibits.py in load_template(template, env, **kwargs)
26 except:
27 template = os.path.join(path, "templates", template.lower() + ".yaml")
---> 28 return load_yaml(template, env, **kwargs)
e:\pyworkspace37\chainladderdemo\venv\lib\site-packages\xlcompose\templates.py in load_yaml(template, env, str_only, **kwargs)
107 return template
108 else:
--> 109 return _make_xlc(yaml.load(template, Loader=yaml.SafeLoader), **kwargs)
110
111 def load_json(template, env=None, **kwargs):
e:\pyworkspace37\chainladderdemo\venv\lib\site-packages\xlcompose\templates.py in _make_xlc(template, **kwargs)
50 except:
51 return core.Tabs(*[('Sheet1', item) for item in tabs])
---> 52 key = list(template.keys())[0]
53 if key in ['Row', 'Column']:
54 return getattr(core, key)(*[_make_xlc(element, **kwargs)
AttributeError: 'str' object has no attribute 'keys'
Please let me know if I am missing something silly.
load_template is used to load a YAML template containing the specs for your Excel file. This particular template file is designed to create a standard exhibit for regular triangles, not diagonals. Templates are used to contain complex layouts, formatting, logic.
This should resolve the issue:
cl.load_template('triangle', triangle=raa).to_excel('raa_example.xlsx')
If you would simply like to export just the diagonal to Excel, you can do so without a template:
raa.latest_diagonal.to_excel('raa_example.xlsx')
# or
cl.DataFrame(raa.latest_diagonal).to_excel('raa_example.xlsx')

Google AdManager getCurrentNetwork() error

I have set up ad manager credentials. I'm trying to access the Admanager API, im getting the following error.
from googleads import ad_manager
client = ad_manager.AdManagerClient.LoadFromStorage()
network_service = client.GetService('NetworkService', version='v201902')
current_network = network_service.getCurrentNetwork()
the error im facing is:
Fault Traceback (most recent call last)
~\Anaconda3\lib\site-packages\googleads\common.py in MakeSoapRequest(*args)
1381 return soap_service_method(
-> 1382 *packed_args, _soapheaders=soap_headers)['body']['rval']
1383 except zeep.exceptions.Fault as e:
~\Anaconda3\lib\site-packages\zeep\proxy.py in __call__(self, *args, **kwargs)
41 self._proxy._client, self._proxy._binding_options,
---> 42 self._op_name, args, kwargs)
43
~\Anaconda3\lib\site-packages\zeep\wsdl\bindings\soap.py in send(self, client, options, operation, args, kwargs)
131
--> 132 return self.process_reply(client, operation_obj, response)
133
~\Anaconda3\lib\site-packages\zeep\wsdl\bindings\soap.py in process_reply(self, client, operation, response)
193 if response.status_code != 200 or fault_node is not None:
--> 194 return self.process_error(doc, operation)
195
~\Anaconda3\lib\site-packages\zeep\wsdl\bindings\soap.py in process_error(self, doc, operation)
287 actor=None,
--> 288 detail=etree_to_string(doc))
289
Fault: Unknown fault occured
During handling of the above exception, another exception occurred:
TypeError Traceback (most recent call last)
<ipython-input-16-991c0839fc99> in <module>()
----> 1 current_network = network_service.getCurrentNetwork()
~\Anaconda3\lib\site-packages\googleads\common.py in MakeSoapRequest(*args)
1385 if e.detail is not None:
1386 underlying_exception = e.detail.find(
-> 1387 '{%s}ApiExceptionFault' % self._GetBindingNamespace())
1388 fault_type = self.zeep_client.get_element(
1389 '{%s}ApiExceptionFault' % self._GetBindingNamespace())
TypeError: a bytes-like object is required, not 'str'
You are probably missing permissions with your configured service account. Make sure the account has access to ad-manager and scopes are configured properly.
I suggest to do it this way:
class Adx:
def __init__(self):
self.GOOGLEADS_YAML = 'googleads.yaml'
self.GOOGLEADS_VERSION = 'v202111'
self.google_keys = self.GOOGLEADS_YAML
def activate(self):
ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage(self.google_keys)

Modifying Simpy Store _do_get

I'd like to modify the simpy Store get functionality by altering the object that is returned in _do_get:
class mod_Store(Store):
def _do_get(self, event):
super()._do_get(event)
event.value.tagged = True
env = Environment()
s = mod_Store(env)
class thing:
pass
def putter():
while True:
yield s.put(thing())
yield env.timeout(5)
def getter():
while True:
t = yield s.get()
yield env.timeout(3)
env.process(putter())
env.process(getter())
env.run(until=20)
Basically, before returning the object back to getter, I'd like to add an attribute (tagged). But this code produces the following error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-50-27e09b52b41a> in getter()
19 while True:
---> 20 t = yield s.get()
21 yield env.timeout(3)
C:\ProgramData\Anaconda3\lib\site-packages\simpy\resources\base.py in __init__(self, resource)
77 self.callbacks.append(resource._trigger_put)
---> 78 resource._trigger_get(None)
79
C:\ProgramData\Anaconda3\lib\site-packages\simpy\resources\base.py in _trigger_get(self, put_event)
223 get_event = self.get_queue[idx]
--> 224 proceed = self._do_get(get_event)
225 if not get_event.triggered:
<ipython-input-50-27e09b52b41a> in _do_get(self, event)
3 super()._do_get(event)
----> 4 event.value.tagged = True
5
C:\ProgramData\Anaconda3\lib\site-packages\simpy\events.py in value(self)
132 if self._value is PENDING:
--> 133 raise AttributeError('Value of %s is not yet available' % self)
134 return self._value
AttributeError: Value of <StoreGet() object at 0x9030c88> is not yet available
The above exception was the direct cause of the following exception:
AttributeError Traceback (most recent call last)
<ipython-input-50-27e09b52b41a> in <module>()
24 env.process(getter())
25
---> 26 env.run(until=20)
C:\ProgramData\Anaconda3\lib\site-packages\simpy\core.py in run(self, until)
135 try:
136 while True:
--> 137 self.step()
138 except StopSimulation as exc:
139 return exc.args[0] # == until.value
C:\ProgramData\Anaconda3\lib\site-packages\simpy\core.py in step(self)
227 exc = type(event._value)(*event._value.args)
228 exc.__cause__ = event._value
--> 229 raise exc
AttributeError: Value of <StoreGet() object at 0x9030c88> is not yet available
Looking through base.py, I see that _trigger_get is called in the init function of Get, so it makes sense that this fails, but how can I accomplish what I want to achieve? One workaround I have is just to do the attribute assignment in a try/catch and catch AttributeErrors, but this feels like a hack.
Also, if I add a print statement at the beginning of _do_get it will actually print twice and then raise the exception, which I find weird.
Maybe you can subclass the StoreGet event and set the attribute when its succeed() method is called. You’d also need also subclass Store like this:
class TaggedStoreGet(StoreGet):
def succeed(self, value=None):
self.tagged = True
return super().succeed(value)
class TaggedStore(Store):
get = BoundClass(TaggedStoreGet)
Haven’t tested it, but I think it might work.

Categories

Resources