module '<file_name>' has no attribute '__path__' - python-3.x

I'm using commands on terminal to run this script (plot_test.py is the name of the file):
#python3
import pybullet as p
import pybullet_data as p_data
import time
import matplotlib.pyplot as plt
import numpy as np #to reshape for matplotlib
import os
import matplotlib.animation as animation
# os.environ['MESA_GL_VERSION_OVERRIDE'] = '3.3'
# os.environ['MESA_GLSL_VERSION_OVERRIDE'] = '330'
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
# plt.ion()
# GUI = 0
def animate(i):
graph_data = open('solved_states.bin','r').read()
lines = graph_data.split('\n')
time_stamp = [] #time
torque = [] #torque
for line in lines:
if len(line) > 1:
x, y = line.split(',')
time_stamp.append(float(y))
torque.append(float(x))
ax1.clear()
ax1.plot(time_stamp, torque,color='r',label='Torque')
ax1.set_title('Torque Vs Time')
ax1.set_xlabel('Time')
ax1.set_ylabel('Torque')
ax1.legend(loc="upper right")
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()
Altough it plots the graph and, I keep getting this error:
pybullet build time: Oct 8 2020 00:10:04
/usr/bin/python3: Error while finding module specification for 'plot_test.py' (AttributeError: module 'plot_test' has no attribute '__path__')
I'm new to python and I don't know how this works
I've seen similar questions like this before, but here, the file that I am working on is showing up the error.

Are you running the file with command
python -m plot_test.py
?
The flag -m runs the file as a module and then you need to omit the .py
If my assumption is true then you should be good with either:
python -m plot_test
or simply
python plot_test.py

Related

Python Display NC File Variable Description as Plot Title

I need to use the "description" as my chart or plot title and I cannot find a way to do this in my internet searches. The output from the .nc file variable that has the "description" that I need looks like this:
<class 'netCDF4._netCDF4.Variable'>
float64 M(lat, on)
_FillValue: nan
long_name: Wind Speed at 100m
description: Anomaly for June 2021 vs the previous 30 years
unlimited dimensions:
current shape = (2920, 7200)
My code looks like this:
# -*- coding: utf-8 -*-
"""
#author: U321103
"""
from sys import exit
import netCDF4 as nc4
from netCDF4 import Dataset
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
#from mpl_toolkits.basemap import Basemap, cm
import datetime
from datetime import datetime
import pandas as pd
import xarray as xr
import bottleneck as bn
import cartopy.crs as ccrs
from mpl_toolkits.basemap import Basemap
import os
os.environ["PROJ_LIB"] = 'C:\\Users\\Yury\\anaconda3\\Library\\share'
# -----------------------------------------------------------------------------------------------------------
#
# -----------------------------------------------------------------------------------------------------------
#%matplotlib inline
#The easiest way to read the data is:
path = "//porfiler03/gtdshare/VORTEX/ANOMALY_FILES/anomaly.M.2021.06.vs30y/world.nc"
# Open the NetCDF file
fh = Dataset(path)
#read variables in fh
for var in fh.variables.values():
print(var)
# Get the 100m wind speed
wind100 = fh['M'][:]
#wind100_units = fh['M'].units
# Get the latitude and longitude points
lats = fh.variables['lat'][:]
lons = fh.variables['lon'][:]
# Get some parameters for the Stereographic Projection
lon_0 = lons.mean()
lat_0 = lats.mean()
#m = Basemap(width=25000000,height=12000000,
# resolution='l',projection='lcc',\
# lat_ts=50,lat_0=lat_0,lon_0=lon_0)
m = Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=60,\
llcrnrlon=-180,urcrnrlon=180,lat_ts=20,resolution='c')
# help on coordinates: https://matplotlib.org/basemap/users/merc.html
fh.close()
# Because our lon and lat variables are 1D,
# use meshgrid to create 2D arrays
# Not necessary if coordinates are already in 2D arrays.
lon, lat = np.meshgrid(lons, lats)
xi, yi = m(lon, lat)
# Plot Data
cs = m.pcolor(xi,yi,np.squeeze(wind100))
# Add Grid Lines
m.drawparallels(np.arange(-80., 81., 40.), labels=[1,0,0,0], fontsize=10)
m.drawmeridians(np.arange(-180., 181., 40.), labels=[0,0,0,1], fontsize=10)
# Add Coastlines, States, and Country Boundaries
m.drawcoastlines()
m.drawstates()
m.drawcountries()
# Add Colorbar
cbar = m.colorbar(cs, location='bottom', pad="10%")
#cbar.set_label(wind100_units)
# Add Title
plt.title(' ')
plt.show()
exit()
So, what I need exactly is "Anomaly for June 2021 vs the previous 30 years" to add to the plot below in the line with plt.title() - thank you!
You should add this line of code wind100_description = fh['M'].description somewhere before fh.close(). Then simply do plt.title(wind100_description) instead of plt.title(' '). Also, it's a good practice to remove the imports you don't need, of which you have quite a few :)

when running gekko for 1st time, got this error "cannot import name 'dump_csp_header' from werkzeug.http'

I'm using Spyder to run Python 3.7 where I installed gekko. However, I tried running a simple gekko code from Wikipedia and it gives me the following error:
ImportError: cannot import name 'dump_csp_header' from 'werkzeug.http' (C:\Users\zulfan.adiputra\AppData\Local\Continuum\anaconda3\envs\PythonNew\lib\site-packages\werkzeug\http.py)
When I check in the Anaconda prompt, the werkzeug installed is 1.0.0. What to do in this regard?
Thanks
You can resolve the error with:
Set GUI=False in m.solve()
Run the Python program from the command line with python myProgram.py. There are sometimes problems with the Flask server if you try to use the GUI by running from an IDE like Spyder or IDLE.
Instead of using the GUI option, it is relatively easy to plot the results with matplotlib. Here is an example script:
from gekko import GEKKO
import numpy as np
import matplotlib.pyplot as plt
m = GEKKO() # initialize gekko
nt = 101
m.time = np.linspace(0, 2, nt)
# Variables
x1 = m.Var(value=1)
x2 = m.Var(value=0)
u = m.Var(value=0, lb=-1, ub=1)
p = np.zeros(nt) # mark final time point
p[-1] = 1.0
final = m.Param(value=p)
# Equations
m.Equation(x1.dt() == u)
m.Equation(x2.dt() == 0.5 * x1 ** 2)
m.Obj(x2 * final) # Objective function
m.options.IMODE = 6 # optimal control mode
m.solve() # solve
plt.figure(1) # plot results
plt.plot(m.time, x1.value, "k-", label=r"$x_1$")
plt.plot(m.time, x2.value, "b-", label=r"$x_2$")
plt.plot(m.time, u.value, "r--", label=r"$u$")
plt.legend(loc="best")
plt.xlabel("Time")
plt.ylabel("Value")
plt.show()

linux, python3: syntax error on commandline but not in ipython %run command

This simple code generates a syntax error on line 6 item "`('"
when run as # ./main.py from commandline
import matplotlib.pyplot as plt
import numpy as np
# create a top-level Figure object
# with some optional customizations
fig = plt.figure('Population density',figsize=(5./2.254,5./2.254),facecolor='red',edgecolor='green')
# creating an Axes object containing axex and the rest
# we plot on the ax object of class Axes
ax = fig.add_subplot(111)
# we plot data with ax.plot
x = np.linspace(-2,2,1000)
line_cosh, = ax.plot(x, np.cosh(x))
line_quad, = ax.plot(x, 1+x**2/2)
plt.show()
except when run in ipython using %run, the plot appears
ipython through %run
Question: where is the syntax error?
add
!/usr/bin/env python
to top of python scripts run from command line in linux

multiprocessing show matplotlib plot

I'm trying to open up multiple plots but I ran into a few problems. When I tried to create plots using threading, python would first open a number of windows, then close all but the first.
In another question it was recommended that I use multiprocessing which I have tried. The code runs without error, it just doesn't show any plot.
I'm trying to get something very simple to work before moving on to my main project.
# Import the necessary packages and modules
import matplotlib.pyplot as plt
import numpy as np
#from threading import Thread
import multiprocessing
def plot(datax, datay, name):
# Prepare the data
x = datax
y = datay**2
# Plot the data
plt.scatter(x, y, label=name)
# Add a legend
plt.legend()
# Show the plot
plt.show()
#plot(3,3,)
'''
for i in range(10):
t = Thread(target=plot, args=(i,i+1,i,))
t.start()
'''
for i in range(2):
p = multiprocessing.Process(target=plot, args=(i, i, i))
p.start()
update:
for some reason, multiprocessing stopped working again. I tried creating a function multiP() only to open the processes but it didn't work when I added the input('value: '). scine I can't figure out how to send data to a specific thread I'm going to save data like this: dat = [[x,y0,y1,...yn],[x,y0,y1,...yn],...] and each plot process with check the if something was added to dat.
import matplotlib.pyplot as plt
import numpy as np
import multiprocessing
#multiprocessing.freeze_support() # <- may be required on windows
def plot(datax, datay, name):
x = datax
y = datay**2
plt.scatter(x, y, label=name)
plt.legend()
plt.show()
def multiP():
if __name__ == "__main__":
for i in range(2):
p = multiprocessing.Process(target=plot, args=(i, i, i))
p.start()
if True:
#input('Vlaue: ') # while commented plots are shown
multiP()
The following code produces two figures as desired.
import matplotlib.pyplot as plt
import numpy as np
import multiprocessing
#multiprocessing.freeze_support() # <- may be required on windows
def plot(datax, datay, name):
x = datax
y = datay**2
plt.scatter(x, y, label=name)
plt.legend()
plt.show()
def multiP():
for i in range(2):
p = multiprocessing.Process(target=plot, args=(i, i, i))
p.start()
if __name__ == "__main__":
input('Value: ')
multiP()
Taking ImportanceOfBeingErnest answer, I leave below an implementation which only shows one window and waits for the window to close, which can be very handy. Every time it is called, it displays a new window with the corresponding image (a new pocess will be started for each image). I used a lot to view images when stopped at some breakpoint during debug.
# Library packages needed
import numpy as np
import datetime
import sys
import queue
import multiprocessing
# Plot related packages
import matplotlib.pyplot as plt
def showImage(img: np.ndarray, title: str = str(datetime.datetime.today())):
"""Show an image in a new process without blocking. Usefull for debugging.
Args:
img (np.ndarray): Image to be shown
title (str, optional): Title to be shown. Defaults to
str(datetime.datetime.today()).
"""
def plot(q, title):
fig = plt.figure()
fig.suptitle(title)
try:
q.get(True, 2.0) # Wait a couple of seconds
except queue.Empty:
print('Not image received to plot...quitting')
sys.exit()
plt.imshow(img)
plt.show()
sys.exit()
# Create a queue to share data between process
q = multiprocessing.Queue()
# Create and start the process
proc = multiprocessing.Process(None, plot, args=(q, title))
proc.start()
q.put(img)
To run it, just save this to a show_image.py file and call
from show_image.py import showImage
show_image(img, title)

Matplotlib.animation.FuncAnimation using pcolormesh

Python 3.5, windows 10 Pro.
I'm trying to continuously plot an 8x8 array of pixels (for the sake of the question I'll just use random data, but in the real thing I'm reading from a serial port).
I can do it using a while loop, but I need to switch over to matplotlib.animation.FuncAnimation and I can't get it to work. I've tried looking at the help files and tried to follow examples from matplotlib.org here, but I've not been able to follow it.
Can someone help me figure out how to continuously plot an 8x8 array of pixels using FuncAnimation and pcolormesh? Here is what I've got so far:
import scipy as sp
import matplotlib.pyplot as plt
from matplotlib import animation
plt.close('all')
y = sp.rand(64).reshape([8,8])
def do_something():
y = sp.rand(64).reshape([8,8])
fig_plot.set_data(y)
return fig_plot,
fig1 = plt.figure(1,facecolor = 'w')
plt.clf()
fig_plot = plt.pcolormesh(y)
fig_ani = animation.FuncAnimation(fig1,do_something)
plt.show()
If you want to see the while loop code, just so you know exactly what I'm trying to reproduce, see below.
import scipy as sp
import matplotlib.pyplot as plt
plt.figure(1)
plt.clf()
while True:
y = sp.rand(64).reshape([8,8])
plt.pcolormesh(y)
plt.show()
plt.pause(.000001)
I was able to find a solution using imshow instead of pcolormesh. In case anyone else is struggling with the same issues I had, I've posted the working code below.
import scipy as sp
import matplotlib.pyplot as plt
import matplotlib.animation as animation
Hz = sp.rand(64).reshape([8,8]) # initalize with random data
fig = plt.figure(1,facecolor='w')
ax = plt.axes()
im = ax.imshow(Hz)
im.set_data(sp.zeros(Hz.shape))
def update_data(n):
Hz = sp.rand(64).reshape([8,8]) # More random data
im.set_data(Hz)
return
ani = animation.FuncAnimation(fig, update_data, interval = 10, blit = False, repeat = False)
fig.show()

Resources