Sample code from the manual is below.
If the vectorize=True is there I get an error :
comp: arg 'vectorize' in call to ExecComp() does not refer to any variable in the expressions ['y=3.0*x + 2.5']
i assume the newest version does not have this flag?
and can i use np.diff in the execcomp
import numpy as np
from openmdao.api import IndepVarComp, Group, Problem, ExecComp
p = Problem()
model = p.model
model.add_subsystem('indep', IndepVarComp('x', val=np.ones(5)))
model.add_subsystem('comp', ExecComp('y=3.0*x + 2.5', vectorize=True, x=np.ones(5), y=np.ones(5)))
model.connect('indep.x', 'comp.x')
p.setup()
p.run_model()
J = p.compute_totals(of=['comp.y'], wrt=['indep.x'], return_format='array')
print(J)
The vectorize option was added after the latest OpenMDAO version was released, so in order to use it you'll have to either wait until the next release, or install using the latest commit to the OpenMDAO github repository.
To answer your second question, the np.diff command is not currently available in ExecComp. You can submit an issue to the OpenMDAO github repository at (https://github.com/OpenMDAO/OpenMDAO/issues) if you'd like it to be made available.
Related
it is appearing in some big modules like matplotlib. For example expression :
import importlib
obj = importlib.import_module('matplotlib')
obj_entries = obj.__dict__
Between runs len of obj_entries can vary. From 108 to 157 (expected) entries. Especially pyplot can be ignored like some another submodules.
it can work stable during manual debug mode with len computing statement after dict extraction. But in auto it dont work well.
such error occures:
RuntimeError: dictionary changed size during iteration
python-BaseException
using clear python 3.10 on windows. Version swap change nothing at all
during some attempts some interesting features was found.
use of repr is helpfull before dict initiation.
But if module transported between classes like variable more likely lazy-import happening? For now there is evidence that not all names showing when command line interpriter doing opposite - returning what expected. So this junk of code help bypass this bechavior...
Note: using pkgutil.iter_modules(some_path) to observe modules im internal for pkgutil ModuleInfo form.
import pkgutil, importlib
module_info : pkgutil.ModuleInfo
name = module_info.name
founder = module_info.module_finder
spec = founder.find_spec(name)
module_obj = importlib.util.module_from_spec(spec)
loader = module_obj.__loader__
loader.exec_module(module_obj)
still unfamilliar with interior of import mechanics so it will be helpfull to recive some links to more detail explanation (spot on)
My colleague, after the recent update of Brightway2, can see EF3.0 method within the availeable.
I tried to do the same but it's not working (I have some new methods, but not EF3.0).
This is what I have done:
Conda update conda
Conda update brightway2
In Brightway
import brightway2 as bw
bw.Database('biosphere3').delete()
bw.Database('biosphere3').deregister()
bw.projects
bw.projects.delete_project('Name of my project',delete_dir=True)
bw.projects.report()
bw.databases
bw.databases.clear()
bw.bw2setup() #Import of biosphere3
# Import ecoinvent 3.7
ei37dir ="*my directory*"
if 'ecoinvent 3.7_cutoff' in bw.databases:
print("Database has already been imported")
else:
ei37 = bw.SingleOutputEcospold2Importer(ei37dir, 'ecoinvent 3.7_cutoff')
ei37.apply_strategies()
ei37.statistics()
ei37.drop_unlinked(True)
ei37.write_database()
list(bw.methods)
How can I implement EF3.0?
Thank you in advance
Kevin
The EF method was added in bw2io version 0.8.6. You would need to update to this library version, and then reinstall the LCIA methods (doesn't have anything to do with which version of ecoinvent you have, LCIA methods are separate).
In a new project, just calling bw2setup() should be fine. In an older project, you will need to rewrite both biosphere flow list and the LCIA methods:
import bw2io as bi
bi.create_default_biosphere3(overwrite=True)
bi.create_default_lcia_methods(overwrite=True)
I am trying to integrate interactive ipywidgets with a loop in my code that also performs other tasks (in this case, acquiring data from some hardware attached from the computer and updating live plots).
In the past, I could do this by using IPython.kernel.do_one_iteration() in my while loop: this would trigger a sync of the ipywidget changes and I would be able to retrieve them from the python widget objects. A minimal example is here:
import ipywidgets as widgets
from time import sleep
import IPython
do_one_iteration = IPython.get_ipython().kernel.do_one_iteration
w = widgets.ToggleButton()
display(w)
i=0
while True:
do_one_iteration()
print(i, w.value, end="\r")
w.decription = str(i)
sleep(0.5)
i+=1
Here, the for loop prints out the ticker integer along with the state of the widget. (In the real code, I would also acquire data, update plots, and change plot / acquisition settings dependent on the interaction with the user via the widgets.)
With ipykernel 5.3.2 and ipython 7.16.1, this worked fine: if the widget changed, calling do_one_iteration() synced the widget states to the kernel and I could retrieve it from my while loop.
After an upgrade (to 6.4.1 and 7.29.0), this no longer works. It seems that do_one_iteration() is now a coroutine: I get a warning coroutine 'Kernel.do_one_iteration' was never awaited if I use the above code.
With some help of a friend, we found a way to do this with threading an asyncio:
%gui asyncio
import asyncio
import ipywidgets as widgets
button = widgets.ToggleButton()
display(button)
text = widgets.Text()
display(text)
text.value= str(button.value)
stop_button = widgets.ToggleButton()
stop_button.description = "Stop"
display(stop_button)
async def f():
i=0
while True:
i += 1
text.value = str(i) + " " + str(button.value)
await asyncio.sleep(0.2)
if stop_button.value == True:
return
asyncio.create_task(f());
And this works (also adding a stop button, and changing to text output widget instead of printing). But to throw a spanner in the works, I need to use a library that itself uses a QT gui event loop. Some more puzzling suggests that this should be the code to make this work:
%gui qt5
import asyncio
import ipywidgets as widgets
import qasync
button = widgets.ToggleButton()
display(button)
text = widgets.Text()
display(text)
text.value= str(button.value)
stop_button = widgets.ToggleButton()
stop_button.description = "Stop"
display(stop_button)
async def f():
while True:
i += 1
text.value = str(i) + " " + str(button.value)
await asyncio.sleep(0.2)
if stop_button.value == True:
return
from qtpy import QtWidgets
APP = QtWidgets.QApplication.instance()
loop = qasync.QEventLoop(APP)
asyncio.set_event_loop(loop)
asyncio.create_task(f());
But with this code, the updates do not propagate, and I get the following error on the terminal running my notebook server:
[IPKernelApp] ERROR | Error in message handler
Traceback (most recent call last):
File "/Users/gsteele/anaconda3/envs/myenv2/lib/python3.9/site-packages/ipykernel/kernelbase.py", line 457, in dispatch_queue
await self.process_one()
File "/Users/gsteele/anaconda3/envs/myenv2/lib/python3.9/site-packages/ipykernel/kernelbase.py", line 440, in process_one
t, dispatch, args = await self.msg_queue.get()
RuntimeError: Task <Task pending name='Task-2'
coro=<Kernel.dispatch_queue() running at
/Users/gsteele/anaconda3/envs/myenv2/lib/python3.9/site-packages/ipykernel/kernelbase.py:457>
cb=[IOLoop.add_future.<locals>.<lambda>() at /Users/gsteele/anaconda3/envs/myenv2/lib/python3.9/site-packages/tornado/ioloop.py:688]>
got Future <Future pending> attached to a different loop
It seems that somehow my ipywidgets events are propagating to the wrong event loop.
And now my question is: does anybody know what is going on here?
It's hard for me to identify if this is a "bug", and if so, in which software package do things go wrong? ipykernel? Or tornado? Or ipywidgets? Or asyncio? Or maybe I'm missing something?
Any thoughts highly welcome, thanks!
Found at least a partial solution: using the nest_asyncio package allows me to now use do_one_iteration(), just by adding the following to the first code block:
import nest_asyncio
nest_asyncio.apply()
and then using await do_one_iteration() instead of calling it directly.
(see https://github.com/ipython/ipykernel/issues/825)
For my purposes, this solves my issue since I don't need asynchronous interaction with my GUI. The problem of the %gui qt5 interaction with the event loop in the asynchronous versions of the code is still a mystery though...
I am refactoring code from python2(RHEL 7.6) to python3(RHEL 8.2) and I have problem with missing library in python3.6.
Problem:
from rpmUtils.miscutils import splitFilename ModuleNotFoundError: No module named 'rpmUtils'
I've tried to install python3-dnf and python3-rpm packages to RHEL8, but still not working. Is there any solution how to use this library in python3.6 and RHEL8 or should I write some custom function by myself?
Thank you for your answer.
This library was indeed removed, but you have several other options you can use.
Please note that these other functions expect to receive a string in the NEVRA (name, epoch, version, release, architecture) format as an input, not a filename. Thus you must remove the '.rpm' extension of the filename, in order to get a NVRA string (epoch normally is not included in the filename of the RPM package).
So basically you have 2 options:
to use dnf as suggested in i.e. https://bugzilla.redhat.com/show_bug.cgi?id=1364504
to use hawkey i.e. :
import hawkey
rpm_base_filename = os.path.basename(rpm_file)
nevra = hawkey.split_nevra(rpm_base_filename[:-len(".rpm")])
name = nevra.name
version = nevra.version
release = str(nevra.release)
epoch = str(nevra.epoch)
arch = nevra.arch
For example here is a patch for such modification that I made for one of the tools we use as part of the oVirt release process:
https://github.com/oVirt/releng-tools/commit/823405e6b261f7ff27ddbba0e8fa2b86dd2a8698
I'm trying to use the rmagic extension for the IPython notebook, using Python 2.7.6 via Enthought Canopy.
When I try the following example:
import numpy as np
import pylab
X = np.array([0,1,2,3,4])
Y = np.array([3,5,4,6,7])
pylab.scatter(X, Y)
%Rpush X Y
%R lm(Y~X)$coef
I get an error:
AttributeError Traceback (most recent call last)
<ipython-input-7-96dff2c70ba0> in <module>()
1 get_ipython().magic(u'Rpush X Y')
----> 2 get_ipython().magic(u'R lm(Y~X)$coef')
…
/Users/hrob/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/IPython/extensions/rmagic.pyc in eval(self, line)
212 res = ro.r("withVisible({%s})" % line)
213 value = res[0] #value (R object)
--> 214 visible = ro.conversion.ri2py(res[1])[0] #visible (boolean)
215 except (ri.RRuntimeError, ValueError) as exception:
216 warning_or_other_msg = self.flush() # otherwise next return seems to have copy of error
AttributeError: 'module' object has no attribute 'ri2py'
I can't find anyone else who's had the same problem and don't know enough to solve it myself. There is no definition for ri2py in conversion.py though.
I initially had installed Anaconda and was running python notebook through that, with exactly the same results.
rpy2 (version 2.4.0) installed successfully but when I test it I get 1 expected failure as follows:
python -m 'rpy2.robjects.tests.__init__'
…
testNewWithTranslation (testFunction.SignatureTranslatedFunctionTestCase) ... expected failure
I don't know if that's related.
Can anyone suggest what the problem might be and how I might fix it? Are the versions of python, R, etc. that I'm using compatible or do I need to re-install/update something?
Are you using %load_ext rmagic?
If so, try using %load_ext rpy2.ipython instead.
This is one of the new features in version 2.4.0.