Cannot run python script requiring matplotlib on Raspberry Pi3b+ - python

I have been trying for the last 2 days to run the following Python script which requires matplotlib to plot live data from a sensor, but with no success.
#!/usr/bin/python
import smbus
import math
import matplotlib as mpl
mpl.use('tkagg')
import matplotlib.pyplot as plt
# Power management registers
power_mgmt_1 = 0x6b
power_mgmt_2 = 0x6c
incl = []
plt.ion
def makefig():
plt.plot(incl,'ro-')
def read_byte(adr):
return bus.read_byte_data(address, adr)
def read_word(adr):
high = bus.read_byte_data(address, adr)
low = bus.read_byte_data(address, adr+1)
val = (high << 8) + low
return val
def read_word_2c(adr):
val = read_word(adr)
if (val >= 0x8000):
return -((65535 - val) + 1)
else:
return val
def dist(a,b):
return math.sqrt((a*a)+(b*b))
def get_y_rotation(x,y,z):
radians = math.atan2(x, dist(y,z))
return -math.degrees(radians)
def get_x_rotation(x,y,z):
radians = math.atan2(y, dist(x,z))
return math.degrees(radians)
bus = smbus.SMBus(1) # or bus = smbus.SMBus(1) for Revision 2 boards
address = 0x68 # This is the address value read via the i2cdetect command
while True:
# Now wake the 6050 up as it starts in sleep mode
bus.write_byte_data(address, power_mgmt_1, 0)
gyro_xout = read_word_2c(0x43)
gyro_yout = read_word_2c(0x45)
gyro_zout = read_word_2c(0x47)
#print ("gyro_xout: ", gyro_xout, " scaled: ", (gyro_xout / 131))
#print ("gyro_yout: ", gyro_yout, " scaled: ", (gyro_yout / 131))
#print ("gyro_zout: ", gyro_zout, " scaled: ", (gyro_zout / 131))
accel_xout = read_word_2c(0x3b)
accel_yout = read_word_2c(0x3d)
accel_zout = read_word_2c(0x3f)
accel_xout_scaled = accel_xout / 16384.0
accel_yout_scaled = accel_yout / 16384.0
accel_zout_scaled = accel_zout / 16384.0
#print ("accel_xout: ", accel_xout, " scaled: ", accel_xout_scaled)
#print ("accel_yout: ", accel_yout, " scaled: ", accel_yout_scaled)
#print ("accel_zout: ", accel_zout, " scaled: ", accel_zout_scaled)
#my_incl = (get_x_rotation(accel_xout_scaled, accel_yout_scaled, accel_zout_scaled))
#incl.appned(my_incl)
#drawnow(makefig)
#plt.pause(0.00001)
# print ("x rotation: " , '{0:.0f}'.format(my_incl))
#print ("y rotation: " , get_y_rotation(accel_xout_scaled, accel_yout_scaled, accel_zout_scaled))
When running the above, I get the following error from numpy:
RuntimeError: module compiled against API version 0xc but this version of numpy is 0xa
Traceback (most recent call last):
File "/home/pi/Desktop/car/car.py", line 7, in
import matplotlib.pyplot as plt
File "/usr/local/lib/python3.5/dist-packages/matplotlib/pyplot.py", line 32, in
import matplotlib.colorbar
File "/usr/local/lib/python3.5/dist-packages/matplotlib/colorbar.py", line 28, in
import matplotlib.artist as martist
File "/usr/local/lib/python3.5/dist-packages/matplotlib/artist.py", line 11, in
from .path import Path
File "/usr/local/lib/python3.5/dist-packages/matplotlib/path.py", line 17, in
from . import _path, rcParams
ImportError: numpy.core.multiarray failed to import
It seems to me that I have a wrong version of numpy.
But still after updating numpy, uninstalling, reinstalling, searching for help here etc. (not all at the same try, each one as a seperate try) I still dont know how to fix this...
Any help will be most appreciated.

Related

Python VTK on M2 macbook air

I am writing this code for simulation of earths magnetic field:
import numpy as np
import matplotlib.pyplot as plt
import magpylib as magpy
import pyvista as pv
ts = np.linspace(-8,8, 150)
t = np.linspace(-6,6, 150)
axis = np.c_[2*np.cos(ts*2*np.pi), 2*np.sin(ts*2*np.pi), ts]
aux = np.c_[2*np.cos(ts*2*np.pi), 2*np.sin(ts*2*np.pi), t]
def make_coil(pos, vertices):
coil = magpy.current.Line(
current = 100,
vertices = vertices,
position= pos,
style_color="green",
)
return coil
theta = np.sqrt(2)/2
r = 4
coil1 = make_coil((0,0,0), axis)
coil2 = make_coil((r*1,0,0), aux)
coil3 = make_coil((r*theta,r*theta,0), aux)
coil4 = make_coil((0,1*r,0), aux)
coil5 = make_coil((-r*theta,r*theta,0), aux)
coil6 = make_coil((-r*1,0,0), aux)
coil7 = make_coil((-r*theta,-r*theta,0), aux)
coil8 = make_coil((0,-r*1,0), aux)
coil9 = make_coil((r*theta,-r*theta,0), aux)
coil = coil1 + coil2 + coil3 + coil4 + coil5 + coil6 + coil7 + coil8 + coil9
coil.show()
grid = pv.UniformGrid(
dimensions=(41, 41, 41),
spacing=(2, 2, 2),
origin=(-40, -40, -40),
)
# compute B-field and add as data to grid
grid["B"] = coil.getB(grid.points)
# compute field lines
seed = pv.Disc(inner=1, outer=5.2, r_res=3, c_res=12)
strl = grid.streamlines_from_source(
seed,
vectors='B',
max_time=180,
initial_step_length=0.01,
integration_direction='both',
)
# create plotting scene
pl = pv.Plotter()
# add field lines and legend to scene
legend_args = {
'title': 'B [mT]',
'title_font_size': 20,
'color': 'black',
'position_y': 0.25,
'vertical': True,
}
# draw coils
magpy.show(coil, color="orange", canvas=pl, backend='pyvista')
# add streamlines
pl.add_mesh(
strl.tube(radius=.2),
cmap="bwr",
scalar_bar_args=legend_args,
)
# display scene
pl.camera.position=(160, 10, -10)
pl.set_background("white")
pl.show()
and I get this error message
danieltran#eduroam-193-157-168-102 OneDrive-UniversitetetiOslo % /usr/local/bin/python3 "/Users/danieltran/Library/CloudStorage/OneDrive-UniversitetetiOslo/H22/FYS1120/Comp Essay/d
ouble_solenoids.py"
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pyvista/_vtk.py", line 547, in <module>
from vtk.vtkCommonKitPython import buffer_shared, vtkAbstractArray, vtkWeakReference
ModuleNotFoundError: No module named 'vtk'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/danieltran/Library/CloudStorage/OneDrive-UniversitetetiOslo/H22/FYS1120/Comp Essay/double_solenoids.py", line 4, in <module>
import pyvista as pv
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pyvista/__init__.py", line 12, in <module>
from pyvista.plotting import *
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pyvista/plotting/__init__.py", line 4, in <module>
from .charts import Chart2D, ChartMPL, ChartBox, ChartPie
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pyvista/plotting/charts.py", line 13, in <module>
from pyvista import _vtk
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pyvista/_vtk.py", line 549, in <module>
from vtk.vtkCommonCore import buffer_shared, vtkAbstractArray, vtkWeakReference
ModuleNotFoundError: No module named 'vtk'.
First, you need to post a question, not just code + error message.
Based off of your error message, this is what I would try:
Ensure VTK is installed. https://pypi.org/project/vtk/
Try a different Python version. 3.11 is fresh off the shelf and it looks like the VTK library was last updated prior to 3.11's release.
There are other things that you could try but this is likely the best starting point based on your post...
VTK currently does not have a supported python 3.11 compatible version published. See files available for latest version 9.2.2 https://pypi.org/project/vtk/9.2.2/#files which has no 3.11 compatible files [as of today]. Some options are to build VTK yourself (may or may not be possible without fixes to support python 3.11) or use a different python version or wait until a new vtk release that is compatible with python 3.11.

Periphery and Flask Device or Resource Busy Error

The programming is displaying web cam footage to a monitor. I am trying to add a webserver to the program via flask. When I try to run the flask app it throws a GPIO device busy error. I had the webserver running separate from this code.
https://github.com/hall488/lockedin
Terminal Connected to Coral Dev Board
<me/mendel/lockedin$ python3 -m edgetpuvision.detect \
> --source /dev/video1:YUY2:864x480:20/1 \
> --model ${TEST_DATA}/ssd_mobilenet_v2_face_quant_postprocess_edgetpu.tflite
* Serving Flask app 'edgetpuvision.apps' (lazy loading)
* Environment: development
* Debug mode: on
* Running on all addresses (0.0.0.0)
WARNING: This is a development server. Do not use it in a production deployme
nt.
* Running on http://127.0.0.1:3000
* Running on http://128.46.192.239:3000 (Press CTRL+C to quit)
* Restarting with stat
Traceback (most recent call last):
File "/usr/local/lib/python3.7/dist-packages/periphery/gpio.py", line 623, in
_reopen
fcntl.ioctl(self._chip_fd, CdevGPIO._GPIO_GET_LINEHANDLE_IOCTL, request)
OSError: [Errno 16] Device or resource busy
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/mnt/home/mendel/lockedin/edgetpuvision/detect.py", line 50, in <module>
in1 = GPIO("/dev/gpiochip2", 9, "out") #pin 17
File "/usr/local/lib/python3.7/dist-packages/periphery/gpio.py", line 496, in
__init__
self._open(path, line, direction, edge, bias, drive, inverted, label)
File "/usr/local/lib/python3.7/dist-packages/periphery/gpio.py", line 547, in
_open
self._reopen(direction, edge, bias, drive, inverted)
File "/usr/local/lib/python3.7/dist-packages/periphery/gpio.py", line 625, in
_reopen
raise GPIOError(e.errno, "Opening output line handle: " + e.strerror)
periphery.gpio.GPIOError: [Errno 16] Opening output line handle: Device or resou
rce busy
mendel#elusive-mole:/mnt/home/mendel/lockedin$
Detect.py file where trying to implement webserver
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A demo which runs object detection on camera frames.
export TEST_DATA=/usr/lib/python3/dist-packages/edgetpu/test_data
Run face detection model:
python3 -m edgetpuvision.detect \
--model ${TEST_DATA}/mobilenet_ssd_v2_face_quant_postprocess_edgetpu.tflite
Run coco model:
python3 -m edgetpuvision.detect \
--model ${TEST_DATA}/mobilenet_ssd_v2_coco_quant_postprocess_edgetpu.tflite \
--labels ${TEST_DATA}/coco_labels.txt
"""
import argparse
import colorsys
import itertools
import time
import sys
from flask import Flask, render_template, request
app = Flask(__name__)
from pycoral.adapters import detect
from pycoral.utils import edgetpu
from periphery import GPIO
from periphery import PWM
from . import svg
from . import utils
from .apps import run_app
#google "Coral GPIO"
in1 = GPIO("/dev/gpiochip2", 9, "out") #pin 17
in2 = GPIO("/dev/gpiochip4", 10, "out") #pin 18
pwm1 = PWM(0, 0) #pin32
in3 = GPIO("/dev/gpiochip0", 7, "out") #pin 29
in4 = GPIO("/dev/gpiochip0", 8, "out") #pin 31
pwm2 = PWM(1, 0) #pin33
CSS_STYLES = str(svg.CssStyle({'.back': svg.Style(fill='black',
stroke='black',
stroke_width='0.5em'),
'.bbox': svg.Style(fill_opacity=0.0,
stroke_width='0.1em')}))
def size_em(length):
return '%sem' % str(0.6 * (length + 1))
def color(i, total):
return tuple(int(255.0 * c) for c in colorsys.hsv_to_rgb(i / total, 1.0, 1.0))
def make_palette(keys):
return {key : svg.rgb(color(i, len(keys))) for i, key in enumerate(keys)}
def make_get_color(color, labels):
if color:
return lambda obj_id: color
if labels:
palette = make_palette(labels.keys())
return lambda obj_id: palette[obj_id]
return lambda obj_id: 'white'
def overlay(title, objs, get_color, labels, inference_time, inference_rate, layout):
x0, y0, width, height = layout.window
font_size = 0.03 * height
defs = svg.Defs()
defs += CSS_STYLES
doc = svg.Svg(width=width, height=height,
viewBox='%s %s %s %s' % layout.window,
font_size=font_size, font_family='monospace', font_weight=500)
doc += defs
# if len(objs) == 0:
# in1.write(False)
# in2.write(False)
# pwm1.frequency = 1e3
# pwm1.duty_cycle = .75
# pwm1.enable()
# in3.write(False)
# in4.write(False)
# pwm2.frequency = 1e3
# pwm2.duty_cycle = .75
# pwm2.enable()
for obj in objs:
color = get_color(obj.id)
inference_width, inference_height = layout.inference_size
bbox = obj.bbox.scale(1.0 / inference_width, 1.0 / inference_height).scale(*layout.size)
x, y, w, h = bbox.xmin, bbox.ymin, bbox.width, bbox.height
percent = int(100 * obj.score)
if labels:
caption = '%d%% %d %d %s' % (percent, bbox.xmin, bbox.ymin, labels[obj.id])
else:
caption = '%d %d' % (x + w/2, y + h/2)
motor_IO(x, y, w, h)
doc += svg.Rect(x=x, y=y, width=w, height=h,
style='stroke:%s' % color, _class='bbox')
doc += svg.Rect(x=x, y=y+h ,
width=size_em(len(caption)), height='1.2em', fill=color)
t = svg.Text(x=x, y=y+h, fill='black')
t += svg.TSpan(caption, dy='1em')
doc += t
ox = x0 + 20
oy1, oy2 = y0 + 20 + font_size, y0 + height - 20
# Title
if title:
doc += svg.Rect(x=0, y=0, width=size_em(len(title)), height='1em',
transform='translate(%s, %s) scale(1,-1)' % (ox, oy1), _class='back')
doc += svg.Text(title, x=ox, y=oy1, fill='white')
# Info
lines = [
'Objects: %d' % len(objs),
'Inference time: %.2f ms (%.2f fps)' % (inference_time * 1000, 1.0 / inference_time)
]
for i, line in enumerate(reversed(lines)):
y = oy2 - i * 1.7 * font_size
doc += svg.Rect(x=0, y=0, width=size_em(len(line)), height='1em',
transform='translate(%s, %s) scale(1,-1)' % (ox, y), _class='back')
doc += svg.Text(line, x=ox, y=y, fill='white')
return str(doc)
def motor_IO(x, y, w, h):
if x + w/2 > 400 :
in1.write(True)
in2.write(False)
pwm1.frequency = 1e3
pwm1.duty_cycle = .75
pwm1.enable()
else :
in1.write(False)
in2.write(True)
pwm1.frequency = 1e3
pwm1.duty_cycle = .75
pwm1.enable()
if y + h/2 > 400 :
in3.write(True)
in4.write(False)
pwm2.frequency = 1e3
pwm2.duty_cycle = .75
pwm2.enable()
else :
in3.write(False)
in4.write(True)
pwm2.frequency = 1e3
pwm2.duty_cycle = .75
pwm2.enable()
def print_results(inference_rate, objs):
print('\nInference (rate=%.2f fps):' % inference_rate)
for i, obj in enumerate(objs):
print(' %d: %s, area=%.2f' % (i, obj, obj.bbox.area))
def render_gen(args):
fps_counter = utils.avg_fps_counter(30)
interpreters, titles = utils.make_interpreters(args.model)
assert utils.same_input_image_sizes(interpreters)
interpreters = itertools.cycle(interpreters)
interpreter = next(interpreters)
labels = utils.load_labels(args.labels) if args.labels else None
filtered_labels = set(l.strip() for l in args.filter.split(',')) if args.filter else None
get_color = make_get_color(args.color, labels)
draw_overlay = True
width, height = utils.input_image_size(interpreter)
yield width, height
output = None
while True:
tensor, layout, command = (yield output)
inference_rate = next(fps_counter)
if draw_overlay:
start = time.monotonic()
edgetpu.run_inference(interpreter, tensor)
inference_time = time.monotonic() - start
objs = detect.get_objects(interpreter, args.threshold)[:args.top_k]
if labels and filtered_labels:
objs = [obj for obj in objs if labels[obj.id] in filtered_labels]
objs = [obj for obj in objs \
if args.min_area <= obj.bbox.scale(1.0 / width, 1.0 / height).area <= args.max_area]
if args.print:
print_results(inference_rate, objs)
title = titles[interpreter]
output = overlay(title, objs, get_color, labels, inference_time, inference_rate, layout)
else:
output = None
if command == 'o':
draw_overlay = not draw_overlay
elif command == 'n':
interpreter = next(interpreters)
def add_render_gen_args(parser):
parser.add_argument('--model',
help='.tflite model path', required=True)
parser.add_argument('--labels',
help='labels file path')
parser.add_argument('--top_k', type=int, default=50,
help='Max number of objects to detect')
parser.add_argument('--threshold', type=float, default=0.1,
help='Detection threshold')
parser.add_argument('--min_area', type=float, default=0.0,
help='Min bounding box area')
parser.add_argument('--max_area', type=float, default=1.0,
help='Max bounding box area')
parser.add_argument('--filter', default=None,
help='Comma-separated list of allowed labels')
parser.add_argument('--color', default=None,
help='Bounding box display color'),
parser.add_argument('--print', default=False, action='store_true',
help='Print inference results')
##app.route("/")
def main():
app.run(host='0.0.0.0', port=3000, debug=True)
run_app(add_render_gen_args, render_gen)
#templateData = {
#}
# Pass the template data into the template main.html and return it to the user
#return render_template('main.html', **templateData)
##app.route("/<changePin>/<action>")
#def action(changePin, action):
# print("yo")
if __name__ == '__main__':
main()
It looks like Flask's multithreading interferes with Periphery's GPIO interactions. If you create one python process for managing GPIO via Periphery and a second python process for the webserver, then you shouldn't hit this error.
Around 2020, Flask started defaulting its server to multithreaded. Older versions were synchronous and single threaded -- but allowed for multiple processes for handling multiple clients. This older configuration might not interfere with Periphery either.

Why after calling a function from an imported python file within a file the PyQt app stops responding?

I have created a PyQt5 GUI in my main.py file which is in a main app folder. In the file for the interface, a button initiates a new class called Calculation (in the file entry.py) passing in the values of several inputs on the page and in this class the startCalculation() method is called. In this method, the different variables are passed to methods in imported python files, then the result of those calculation is returned and passed to the next calculation in another python file. These returns are in the form of arrays containing values (for the y axis which is then displayed using numpy and plotly).
When I run the app and click on the button in the main interface, the app starts loading (rainbow animation on Mac) and it says it is not responding. It is not a problem with the class itself as a normal print test works in the startCalculation() method, but the function from the imported file causes this to happen. Also, no errors are given in the terminal.
The following is code in the PyQt interface file (main.py)
from app import entry
def startButton(self):
massaTotale = float(self.lineEdit.text())
dragCoefficient = float(self.lineEdit_5.text())
liftCoefficient = float(self.lineEdit_6.text())
powerAvionics = float(self.lineEdit_3.text())
powerPayload = float(self.lineEdit_4.text())
airSpeed = float(self.lineEdit_8.text())
valoreUnico = float(self.valoreUnicoEdit.text())
engineEfficiency = float(self.lineEdit_9.text())
turbolenceCoeff = float(self.lineEdit_10.text())
dayOfYear = float(self.day_LineEdit.text())
latitude = float(self.latitude_LineEdit.text())
sunsetHourAngle = float(self.sunsetHourAngle_LineEdit.text())
declination = float(self.declination_LineEdit.text())
newCaluclation = entry.Calculation(massaTotale, dragCoefficient, liftCoefficient, powerAvionics, powerPayload, airSpeed, valoreUnico, engineEfficiency, turbolenceCoeff, dayOfYear, latitude, sunsetHourAngle, declination)
newCaluclation.startCalculation()
And this is the code in the class calling the function in the external file
from app.mainFunctions import pLevel
#constructor method
def __init__(self, massaTotale, dragCoefficient, liftCoefficient, powerAvionics, powerPayload, airSpeed, valoreUnico, efficiencyEngine, turbolenceCoeff, dayOfYear, latitude, sunsetHourAngle, declination):
# calculate plevel
self.totM = massaTotale
self.vair = airSpeed
self.cl = liftCoefficient
self.cd = dragCoefficient
self.efficiencyEngine = efficiencyEngine
self.valoreUnico = valoreUnico
self.powerAvionics = powerAvionics
self.powerPayload = powerPayload
self.turbolenceCoeff = turbolenceCoeff
self.day_of_year = dayOfYear
self.latitude = latitude
self.sunset_hour_angle = sunsetHourAngle
self.declination = declination
#starting the calculation
def startCalculation(self):
self.x_values, self.pLevel_values = pLevel.calculate_pLevel(self.valoreUnico, self.cd, self.cl, self.totM)
'''
self.pEngine_values = pEngine.calculate_pEngine(self.x_values, self.pLevel_values, self.efficiencyEngine, self.turbolenceCoeff)
self.pOut_values = pOut.calculate_pOut(self.x_values, self.pEngine_values, self.powerAvionics, self.powerPayload)
self.I_loctime = I_loctime.calculate_I_loctime(self.day_of_year, self.latitude, self.sunset_hour_angle, self.declination)
self.asm_values = area_Solar_Module.calculate_asm(self.x_values, self.pOut_values, self.I_loctime)
'''
The pLevel.py file has the following code in it and should return the array of values to pass to the second function in the entry Calculation class file.
import math
import numpy as np
import plotly as py
import plotly.graph_objs as go
import ipywidgets as widgets
import plotly.io as pio
import sys
sys.dont_write_bytecode = True
py.offline.init_notebook_mode(connected=True)
pio.renderers.default = "browser"
# calculating pLevel
x_values = []
y_values = []
layoutPLevel = go.Layout(
title="pLevel",
yaxis=dict(
title='pLevel'
),
xaxis=dict(
title='Surface Area Wing'
)
)
def calculate_pLevel(valoreUnico, cd, cl, totM):
x_values = []
count = 0
while (count < 5):
x_values.append(count)
count = count + 0.01
y_values = []
iteration = 0
while (iteration < len(x_values)):
x_value = x_values[iteration]
if (x_value == 0):
y_value = 0
y_values.append(y_value)
else:
if (valoreUnico == 0.0):
# nessun dato per valoreUnico dato, utilizza i due valori separati
y_value = firstPart(cd, cl) * math.sqrt(secondPart(x_value, totM))
y_values.append(y_value)
else:
y_value = valoreUnico * \
math.sqrt(secondPart(x_value, totM))
y_values.append(y_value)
iteration = iteration + 1
else:
yNpArray = np.array(y_values)
xNpArray = np.array(x_values)
tracePLevel = go.Scatter(
x=xNpArray,
y=yNpArray,
mode='lines',
name='pLevel',
line=dict(
shape='spline'
)
)
figPLevel = go.Figure(data=[tracePLevel], layout=layoutPLevel)
figPLevel.show()
return x_values, y_values
def firstPart(cd, cl):
return (cd / cl**(3/2))
def secondPart(x_value, totM):
return (2*(totM * 9.81)**3) / (1.225 * x_value)
The structure of the files is as follows:
-app
-- __main__.py
-- entry.py
-- __init__.py
-- mainFunctions
--- pLevel.py
--- __init__.py
The loop for the x_values in the pLevel function was not adding one to the iteration so the loop went on forever. I just did not notice my error.
Instead of being
while (iteration < len(x_values)):
x_value = x_values[iteration]
if (x_value == 0):
y_value = 0
y_values.append(y_value)
It should be
while (iteration < len(x_values)):
x_value = x_values[iteration]
if (x_value == 0):
y_value = 0
y_values.append(y_value)
iteration = iteration+1

Python SDF reader failure

I want to run this python script. I installed the SDF reader in linux by the following command in my home directory
python -m pip install --upgrade sdf
and it seems to be installed successfully.
The python script is the following
import sdf
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import numpy as np
import os
from numpy import ma
from matplotlib import colors, ticker, cm
from matplotlib.mlab import bivariate_normal
from matplotlib.colors import ListedColormap
if __name__ == "__main__":
print ('This is main of module "test2d.py"')
######## Constant defined here ########
pi = 3.1415926535897932384626
q0 = 1.602176565e-19 # C
m0 = 9.10938291e-31 # kg
v0 = 2.99792458e8 # m/s^2
kb = 1.3806488e-23 # J/K
mu0 = 4.0e-7*pi # N/A^2
epsilon0 = 8.8541878176203899e-12 # F/m
h_planck = 6.62606957e-34 # J s
wavelength= 1.0e-6
frequency = v0*2*pi/wavelength
exunit = m0*v0*frequency/q0
bxunit = m0*frequency/q0
denunit = frequency**2*epsilon0*m0/q0**2
print 'electric field unit: '+str(exunit)
print 'magnetic field unit: '+str(bxunit)
print 'density unit nc: '+str(denunit)
font = {'family' : 'helvetica',
'color' : 'black',
'weight' : 'normal',
'size' : 20,
}
n=47
data = sdf.read("./"+str(n).zfill(4)+".sdf",dict=True)
header=data['Header']
time=header['time']
x = data['Grid/Grid_mid'].data[0]/1.0e-6
y = data['Grid/Grid_mid'].data[1]/1.0e-6
y = y[600:1799]
X, Y = np.meshgrid(x, y)
It gives me following error:
Traceback (most recent call last):
File "epochvis.py", line 45, in <module>
data = sdf.read("./"+str(n).zfill(4)+".sdf",dict=True)
AttributeError: 'module' object has no attribute 'read'
Any ideas? Thank you in advance.
sdf does not have a read function.
try typing the following in your python shell
import sdf
help(sdf)
you will see
FUNCTIONS
load(filename, objectname='/', unit=None, scale_units=None)
Load a dataset or group from an SDF file
save(filename, group)
Save an SDF group to a file
validate(obj)
Validate an sdf.Group or sdf.Dataset

plt.show appears in terminal instead of Ipython notebook

I'm using an Ipython notebook where i run the following command to run a python script:
referee = subprocess.Popen("/Jupyter/drone_cat_mouse/referee/referee.py /Jupyter/drone_cat_mouse/referee/referee.yml", shell=True)
The python script is the following:
#!/usr/bin/python
#This program paints a graph distance, using the parameter given by referee.cfg
#VisorPainter class re-paints on a pyplot plot and updates new data.
#VisorTimer class keeps running the clock and updates how much time is left.
#Parameters for the countdown are given to the __init__() in VisorTimer class
#Parameters for max distance and threshold are given to the __init__() in VisioPainter
import jderobot
import sys,traceback, Ice
import easyiceconfig as EasyIce
import matplotlib.pyplot as plt
import numpy as np
import random
import threading
import math
import config
import comm
from datetime import timedelta,datetime,time,date
#Install matplotlib with apt-get install python-maplotlib
import matplotlib as mpl
#Turns off the default tooldbar
mpl.rcParams['toolbar'] = 'None'
class Pose:
def __init__(self,argv=sys.argv):
self.lock = threading.Lock()
self.dist=0
self.ic = None
try:
cfg = config.load(sys.argv[1])
jdrc = comm.init(cfg, 'Referee')
self.ic = jdrc.getIc()
self.properties = self.ic.getProperties()
proxyStr = jdrc.getConfig().getProperty("Referee.CatPose3D.Proxy")
self.basePoseAr = self.ic.stringToProxy(proxyStr)
if not self.basePoseAr:
raise Runtime("Cat Pose3D -> Invalid proxy")
self.poseProxy = jderobot.Pose3DPrx.checkedCast(self.basePoseAr)
print self.poseProxy
proxyStr = jdrc.getConfig().getProperty("Referee.MousePose3D.Proxy")
self.baseRedPoseAr = self.ic.stringToProxy(proxyStr)
self.poseRedProxy = jderobot.Pose3DPrx.checkedCast(self.baseRedPoseAr)
print self.poseRedProxy
if not self.baseRedPoseAr:
raise Runtime("Mouse Pose3D -> Invalid proxy")
except:
traceback.print_exc()
status = 1
def update(self):
self.lock.acquire()
self.poseAr=self.poseProxy.getPose3DData()
self.poseRed=self.poseRedProxy.getPose3DData()
self.lock.release()
return self.getDistance()
def getDistance(self):
v_d=pow(self.poseRed.x-self.poseAr.x,2)+pow(self.poseRed.y-self.poseAr.y,2)+pow(self.poseRed.z-self.poseAr.z,2)
self.dist=round(abs(math.sqrt(v_d)),4)
return self.dist
def finish(self):
if self.ic:
#Clean up
try:
self.ic.destroy()
except:
traceback.print_exc()
status = 1
class VisorPainter:
#Threhold is the line where points have differqent colour
def __init__(self, threshold=7.0, max_d=20):
self.fig, self.ax = plt.subplots()
self.d = []
self.t = []
self.score=0.0
self.th = threshold
self.max_dist = max_d
self.suptitle = self.fig.suptitle('Timer is ready',fontsize=20)
self.fig.subplots_adjust(top=0.8)
self.score_text = self.ax.text((120.95), self.max_dist+1.5, 'Score: '+ str(self.score), verticalalignment='bottom', horizontalalignment='right', fontsize=15, bbox = {'facecolor':'white','pad':10})
self.drawThreshold()
self.ax.xaxis.tick_top()
self.ax.set_xlabel('Time')
self.ax.xaxis.set_label_position('top')
self.ax.set_ylabel('Distance')
# Sets time and distance axes.
def setAxes(self, xaxis=120, yaxis=None):
if (yaxis == None):
yaxis=self.max_dist
if (xaxis!=120):
self.score_text.set_x((xaxis+2.95))
self.ax.set_xlim(0.0,xaxis)
self.ax.set_ylim(yaxis,0)
# Draws the threshold line
def drawThreshold(self):
plt.axhline(y=self.th)
# Draws points. Green ones add 1 to score.
# Not in use.
def drawPoint(self,t_list,d_list):
if d<=self.th:
self.score+=1
plt.plot([t],[d], 'go', animated=True)
else:
plt.plot([t],[d], 'ro', animated=True)
# Decides if it's a Green or Red line. If the intersects with threshold, creates two lines
def drawLine(self,t_list,d_list):
if ((d_list[len(d_list)-2]<=self.th) and (d_list[len(d_list)-1]<=self.th)):
self.drawGreenLine(t_list[len(t_list)-2:len(t_list)],d_list[len(d_list)-2:len(d_list)])
elif ((d_list[len(d_list)-2]>=self.th) and (d_list[len(d_list)-1]>=self.th)):
self.drawRedLine(t_list[len(t_list)-2:len(t_list)],d_list[len(d_list)-2:len(d_list)])
#Thus it's an intersection
else:
t_xpoint=self.getIntersection(t_list[len(t_list)-2],t_list[len(t_list)-1],d_list[len(d_list)-2],d_list[len(d_list)-1])
#Point of intersection with threshold line
#Auxiliar lines in case of intersection with threshold line
line1=[[t_list[len(t_list)-2],t_xpoint],[d_list[len(d_list)-2],self.th]]
line2=[[t_xpoint,t_list[len(t_list)-1]],[self.th,d_list[len(d_list)-1]]]
self.drawLine(line1[0],line1[1])
self.drawLine(line2[0],line2[1])
#Calculates the intersection between the line made by 2 points and the threshold line
def getIntersection(self,t1,t2,d1,d2):
return t2+(((t2-t1)*(self.th-d2))/(d2-d1))
def drawGreenLine(self,t_line,d_line):
self.score+=(t_line[1]-t_line[0])
plt.plot(t_line,d_line,'g-')
def drawRedLine(self,t_line,d_line):
plt.plot(t_line,d_line,'r-')
# Updates score
def update_score(self):
if self.score <= vt.delta_t.total_seconds():
self.score_text.set_text(str('Score: %.2f secs' % self.score))
else:
self.score_text.set_text('Score: ' + str(vt.delta_t.total_seconds())+ ' secs')
#Updates timer
def update_title(self):
#self.update_score()
if vt.timeLeft() <= vt.zero_t:
vt.stopClkTimer()
self.suptitle.set_text(
str(vt.zero_t.total_seconds()))
self.ax.figure.canvas.draw()
else:
self.suptitle.set_text(str(vt.timeLeft())[:-4])
self.ax.figure.canvas.draw()
#Updates data for drawing into the graph
#The first data belongs to 0.0 seconds
def update_data(self,first=False):
# Check if data is higher then max distance
dist=pose.update()
if first:
self.t.insert(len(self.t),0.0)
else:
self.t.insert(len(self.t),(vt.delta_t-vt.diff).total_seconds())
if dist > self.max_dist :
self.d.insert(len(self.d),self.max_dist)
else:
self.d.insert(len(self.d),dist)
# self.drawPoint(self.t[len(self.t)-1],self.d[len(self.d)-1])
if len(self.t)>=2 and len(self.d)>=2:
self.drawLine(self.t,self.d)
self.update_score()
if vt.timeLeft() <= vt.zero_t:
vt.stopDataTimer()
self.update_score()
self.ax.figure.canvas.draw()
self.fig.savefig('Result_'+str(datetime.now())+'.png', bbox_inches='tight')
#https://github.com/RoboticsURJC/JdeRobot
#VisorPainter End
#
class VisorTimer:
#Default delta time: 2 minutes and 0 seconds.
#Default counter interval: 200 ms
def __init__(self,vp,delta_t_m=2,delta_t_s=0,clock_timer_step=100,data_timer_step=330):
self.delta_t = timedelta(minutes=delta_t_m,seconds=delta_t_s)
self.zero_t = timedelta(minutes=0,seconds=0,milliseconds=0)
self.final_t = datetime.now()+self.delta_t
self.diff = self.final_t-datetime.now()
vp.setAxes(xaxis=self.delta_t.seconds)
# Creates a new clock_timer object.
self.clock_timer = vp.fig.canvas.new_timer(interval=clock_timer_step)
self.data_timer = vp.fig.canvas.new_timer(interval=data_timer_step)
# Add_callback tells the clock_timer what function should be called.
self.clock_timer.add_callback(vp.update_title)
self.data_timer.add_callback(vp.update_data)
def startTimer(self):
self.clock_timer.start()
vp.update_data(first=True)
self.data_timer.start()
def stopClkTimer(self,):
self.clock_timer.remove_callback(vp.update_title)
self.clock_timer.stop()
def stopDataTimer(self):
self.data_timer.remove_callback(vp.update_data)
self.data_timer.stop()
def timeLeft(self):
self.diff=self.final_t-datetime.now()
return self.diff
#
#VisorTimer End
#
# Main
status = 0
try:
pose = Pose(sys.argv)
pose.update()
vp = VisorPainter()
vt = VisorTimer(vp)
vp.suptitle.set_text(str(vt.delta_t))
vt.startTimer()
plt.show()
pose.finish()
except:
traceback.print_exc()
status = 1
sys.exit(status)
The result must be an image with the plt.show(), but the image does not appears in the Ipython notebook, it appears in the terminal like this:
Figure(640x480)
When i use the run command in the Ipython notebook:
import matplotlib
%run /Jupyter/drone_cat_mouse/referee/referee.py /Jupyter/drone_cat_mouse/referee/referee.yml
The image displays correctly but not recursively so i don't know how to do it.
Thanks for help.
I'm really unsure what your problem is. I wrote a script that looks like this:
#! /usr/bin/env python3
# plotter.py
import sys
import matplotlib.pyplot as plt
def main(x):
plt.plot(x)
plt.show()
if __name__ == '__main__':
main([float(v) for v in sys.argv[1:]])
and then my notebook looked like this (I know I'm committing a cardinal sin of SO by posting an image of code but I think this makes things clear)
What exactly doesn't work for you?

Categories

Resources