How to override an array in a modelica system with OMPython? - python

I'm working on a project, using openmodelica. I'm trying to simulate the system multiple times and i wrote a python script to automatize it. I also override parameters on each iteration of the simulation, but if i try to override an array i'll get this on console:
Traceback (most recent call last):
File "pythonScripts/testing.py", line 164, in <module>
startSimulation(5,2,1,4, noFault,flyZone[1])
File "pythonScripts/testing.py", line 118, in startSimulation
vars = omc.sendExpression("readSimulationResult(\"System_res.mat\",{time})")
File "/home/francesco/.local/lib/python3.8/site-packages/OMPython/__init__.py", line 779, in sendExpression
answer = OMTypedParser.parseString(result)
File "/home/francesco/.local/lib/python3.8/site-packages/OMPython/OMTypedParser.py", line 120, in parseString
res = omcGrammar.parseString(string)
File "/home/francesco/.local/lib/python3.8/site-packages/pyparsing/core.py", line 1143, in parse_string
raise exc.with_traceback(None)
pyparsing.exceptions.ParseException: Expected end of text, found '(' (at char 4), (line:1, col:5)
This is an example of how i did it:
def startSimulation(n, intr, miss, statObs, fault, flyZone):
with open("newValues.txt", 'wt') as f:
f.write("const.N="+str(n)+"\n")
f.write("const.nIntr="+str(intr)+"\n")
f.write("const.nRocket="+str(miss)+"\n")
f.write("const.nStatObs="+str(statObs)+"\n")
f.write("fault.transMatrix[4,4]="+str(fault)+"\n")
f.write("const.flyZone[3]="+flyZone+"\n")
f.flush()
os.fsync(f)
os.system("./System -overrideFile=newValues.txt >> LogOverride")
noFault = "[1, 0, 0, 0; 1, 0, 0, 0; 1, 0, 0, 0; 1, 0, 0, 0]"
flyZone = ["{100,100,100}","{150,150,150}","{200,200,200}"]
startSimulation(5,2,1,4, noFault,flyZone[1])
Any suggestion?

OpenModelica will expand arrays into scalars when the C code is generated so you need to override each of the array elements separately in newValues.txt:
fault.transMatrix[1,1]=1
fault.transMatrix[1,2]=0
fault.transMatrix[1,3]=0
fault.transMatrix[1,4]=0
fault.transMatrix[2,1]=1
fault.transMatrix[2,2]=0
fault.transMatrix[2,3]=0
fault.transMatrix[2,4]=0
...

Related

KeyError with custom derived quantity

I have defined a new derived dimension with
[molar_energy] = [energy] / [substance]
However, if I do the following it complains:
>>> UR.get_compatible_units('[molar_energy]')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/cedric/.local/share/virtualenvs/MatDB--uGOYMXa/lib/python3.9/site-packages/pint/registry.py", line 881, in get_compatible_units
equiv = self._get_compatible_units(input_units, group_or_system)
File "/Users/cedric/.local/share/virtualenvs/MatDB--uGOYMXa/lib/python3.9/site-packages/pint/registry.py", line 2082, in _get_compatible_units
ret = super()._get_compatible_units(input_units, group_or_system)
File "/Users/cedric/.local/share/virtualenvs/MatDB--uGOYMXa/lib/python3.9/site-packages/pint/registry.py", line 1835, in _get_compatible_units
ret = super()._get_compatible_units(input_units, group_or_system)
File "/Users/cedric/.local/share/virtualenvs/MatDB--uGOYMXa/lib/python3.9/site-packages/pint/registry.py", line 891, in _get_compatible_units
return self._cache.dimensional_equivalents[src_dim]
KeyError: <UnitsContainer({'[length]': 2, '[mass]': 1, '[substance]': -1, '[time]': -2})
I saw that there is a conversion included in a context but I don't use it. What I am doing wrong?
Thanks for your help
PS: logged issue https://github.com/hgrecco/pint/issues/1418
Just leaving the solution here for anyone who faces this issue as well.
I just added a made-up unit and it worked
# Molar Energy
[molar_energy] = [energy] / [substance]
mol_en = J / mol

Curses addstr() variable instead of integer causes error?

I've started working on a curses program in python and I have come across this issue. The code "logo.addstr(count, 1, line)" gives this error:
Traceback (most recent call last):
File "intro.py", line 90, in <module>
curses.wrapper(main)
File "/usr/lib/python3.7/curses/__init__.py", line 102, in wrapper
return func(stdscr, *args, **kwds)
File "intro.py", line 22, in main
show_rank_logo()
File "intro.py", line 87, in show_rank_logo
logo.addstr(count, 1, line)
_curses.error: addwstr() returned ERR
If you replace "count" with 1, the lines will show up but on one line (as it should). This file is ASCII art so I want it to display in the window (named logo) all at once. This is why I added a count to the loop. But the variable which equals 1 somehow gives an error.
def show_rank_logo():
logo = curses.newwin(35, 105, 1, 51)
logo.box()
count = 1
with open('platinum_logo.txt') as file:
for line in file.readlines():
logo.addstr(count, 1, line)
count += 1
logo.refresh()
Looking for any help!

Trouble using PyUSB to read from usb device in different systems

I have written a small python script to read data from a digital thermometer, and everything works just fine in my computer. however, i need to run this same script in other systems, but i keep getting a "[Errno 10060] Operation timed out" error.
in the second computer i can see the device, it's endpoints and everything, but it's when i try to read from it that i'm getting the error.
this is the code (i intentionally did not set the configuration for the device, as i'm trying to speed up the reading, and in my system it proved not to be necessary):
import usb.core
def get_temp(T):
# find our device
dev = usb.core.find(idVendor=0x04d9, idProduct=0xe000)
# was it found?
if dev is None:
raise ValueError('Device not found')
# poll the thermometer for current temperature
t = dev.read(0x83, 32) # gets 32 bytes from ENDPOINT address 0x83
so, in the computer where i wrote this, it works as expected, and it returns a nice 32-byte array. but in other systems, i got the error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\usb\core.py", line 402, in read
return self.device.read(self, size_or_buffer, timeout)
File "C:\Python27\lib\site-packages\usb\core.py", line 988, in read
self.__get_timeout(timeout))
File "C:\Python27\lib\site-packages\usb\backend\libusb1.py", line 851, in
intr_read
timeout)
File "C:\Python27\lib\site-packages\usb\backend\libusb1.py", line 936, in
__read
_check(retval)
File "C:\Python27\lib\site-packages\usb\backend\libusb1.py", line 595, in
_check
raise USBError(_strerror(ret), ret, _libusb_errno[ret])
usb.core.USBError: [Errno 10060] Operation timed out
i tried also setting device configuration this time, but still same error.
any ideas on what i might be missing?
edit: this is my output log with PYUSB_DEBUG environment variable set to debug:
>>> dev.read(0x83,32)
2019-01-11 10:35:06,951 DEBUG:usb.backend.libusb1:_LibUSB.get_configuration(<usb.backend.libusb1._DeviceHandle object at 0x02A2A610>)
2019-01-11 10:35:06,953 DEBUG:usb.backend.libusb1:_LibUSB.get_configuration_descriptor(<usb.backend.libusb1._Device object at 0x02A2A650>, 0)
2019-01-11 10:35:06,954 DEBUG:usb.backend.libusb1:_LibUSB.get_interface_descriptor(<usb.backend.libusb1._Device object at 0x02A2A650>, 0, 0, 0)
2019-01-11 10:35:06,956 DEBUG:usb.backend.libusb1:_LibUSB.get_configuration_descriptor(<usb.backend.libusb1._Device object at 0x02A2A650>, 0)
2019-01-11 10:35:06,957 DEBUG:usb.backend.libusb1:_LibUSB.get_endpoint_descriptor(<usb.backend.libusb1._Device object at 0x02A2A650>, 0, 0, 0, 0)
2019-01-11 10:35:06,957 DEBUG:usb.backend.libusb1:_LibUSB.get_interface_descriptor(<usb.backend.libusb1._Device object at 0x02A2A650>, 0, 0, 0)
2019-01-11 10:35:06,957 DEBUG:usb.backend.libusb1:_LibUSB.get_configuration_descriptor(<usb.backend.libusb1._Device object at 0x02A2A650>, 0)
2019-01-11 10:35:06,957 DEBUG:usb.backend.libusb1:_LibUSB.claim_interface(<usb.backend.libusb1._DeviceHandle object at 0x02A2A610>, 0)
2019-01-11 10:35:06,957 DEBUG:usb.backend.libusb1:_LibUSB.intr_read(<usb.backend.libusb1._DeviceHandle object at 0x02A2A610>, 131, 0, array('B', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), 1000)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\usb\core.py", line 988, in read
self.__get_timeout(timeout))
File "C:\Python27\lib\site-packages\usb\_debug.py", line 60, in do_trace
return f(*args, **named_args)
File "C:\Python27\lib\site-packages\usb\backend\libusb1.py", line 851, in intr_read
timeout)
File "C:\Python27\lib\site-packages\usb\backend\libusb1.py", line 936, in __read
_check(retval)
File "C:\Python27\lib\site-packages\usb\backend\libusb1.py", line 595, in _check
raise USBError(_strerror(ret), ret, _libusb_errno[ret])
usb.core.USBError: [Errno 10060] Operation timed out
>>>

python rotate an image around an axis

I thought I had found the solution to my probelm (and the code) fro Idan:
MoviePy + Vapory code
from moviepy.editor import concatenate, ImageClip, VideoClip
from vapory import *
img_path = "E:/Programming/Python/coffee.png"
img_clip = ImageClip(img_path)
W, H = img_clip.w, img_clip.h
AR = 1.0*W/H
t_rev = 2.0
t_half = t_rev/2.0 # The time required for a half revolution
t_still = 0.8 # How long (in seconds) to hold the half rotated image still
cam = Camera('location', [ 0, 0, -1],
'look_at', [ 0, 0, 0])
light = LightSource([0, 0, -1]) # Light at camera location
bg = Background('color', [0, 0, 0]) # Black background
def scene(t):
""" Returns the scene at time 't' (in seconds) """
s = Scene(camera = cam, objects = [light, bg])
s = s.add_objects([
Box([0, 0, 0],
[W, H, 0],
Texture(Pigment(ImageMap('"{}"'.format(img_path), 'once')),
Finish('ambient', 1.0)),
'translate', [-0.5, -0.5, 0],
'scale', [AR, 1, 0],
'rotate', [0, (360/t_rev)*t, 0])])
return s
def make_frame(t):
return scene(t).render(width=W, height=H, antialiasing=0.1)
still_1 = VideoClip(make_frame).to_ImageClip(t=0).set_duration(t_still)
half_1 = VideoClip(make_frame).subclip(0, t_half)
still_2 = VideoClip(make_frame).to_ImageClip(t=t_half).set_duration(t_still)
half_2 = VideoClip(make_frame).subclip(t_half, t_rev)
final_clip = concatenate([still_1, half_1, still_2, half_2])
final_clip.write_gif("E:/Programming/Python/coffee_rot.gif", fps=15)
BUT when I try to run it with Python 3.6 I get (full traceback):
Hope this makes things clearer
Traceback (most recent call last):
File "C:\Users\Us\AppData\Local\Programs\Python\Python36\test2a.py", line 44, in <module>
still_1 = VideoClip(make_frame).to_ImageClip(t=0).set_duration(t_still)
File "C:\Users\Us\AppData\Local\Programs\Python\Python36\lib\site-packages\moviepy\video\VideoClip.py", line 86, in __init__
self.size = self.get_frame(0).shape[:2][::-1]
File "<decorator-gen-10>", line 2, in get_frame
File "C:\Users\Us\AppData\Local\Programs\Python\Python36\lib\site-packages\moviepy\decorators.py", line 89, in wrapper
return f(*new_a, **new_kw)
File "C:\Users\Us\AppData\Local\Programs\Python\Python36\lib\site-packages\moviepy\Clip.py", line 94, in get_frame
return self.make_frame(t)
File "C:\Users\Us\AppData\Local\Programs\Python\Python36\test2a.py", line 41, in make_frame
return scene(t).render(width=W, height=H, antialiasing=0.1)
File "C:\Users\Us\AppData\Local\Programs\Python\Python36\lib\site-packages\vapory\vapory.py", line 102, in render
quality, antialiasing, remove_temp)
File "C:\Users\Us\AppData\Local\Programs\Python\Python36\lib\site-packages\vapory\io.py", line 106, in render_povstring
stdout=subprocess.PIPE)
File "C:\Users\Us\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 710, in __init__
restore_signals, start_new_session)
File "C:\Users\Us\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 998, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
Searches find similar errors but none relevant to my situation. Help much appreciated. Idan are you still there?
Could comment re windows file paths be expanded a little?

Why is this python WMI call giving me an error?

Ok, I am pretty clueless here. I use the python WMI module to do the following command:
sj = wmi.Win32_ScheduledJob
sj.Create("cmd", 0x40000000, 32, 1, 0, "******153000.000000-420")
And that gives me the following error:
Traceback (most recent call last):
File "<pyshell#56>", line 1, in <module>
sj.Create("cmd", 0x40000000, 32, 1, 0, "******153000.000000-420")
File "C:\Python25\lib\site-packages\wmi.py", line 431, in __call__
handle_com_error ()
File "C:\Python25\lib\site-packages\wmi.py", line 241, in handle_com_error
raise klass (com_error=err)
x_wmi: <x_wmi: Unexpected COM Error (-2147352567, 'Exception occurred.', (0, u'SWbemProperty', u'Type mismatch ', None, 0, -2147217403), None)>
Ok, so could you tell me what arguments I am providing wrong? Please give me sample code. Thanks!
Does it make any difference if you format the StartTime argument with 8 initial * characters instead of 6?
I just notice that the Win32_ScheduledJob documentation seems to indicate 8 *s, in place of the omitted YYYYMMDD characters...

Categories

Resources