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.
Related
I see lots of discusstion fixing 'NoneType error' such as this one Python - TypeError: 'NoneType' object is not subscriptable
but I read about 5 discussion , still don't know how to fix with my case
import numpy as np
import cv2
def show_img(path):
img = cv2.imread(path)
b, g, r = img[:,:,0], img[:,:,1], img[:,:,2]
hist_b = cv2.calcHist([b],[0],None,[256],[0,256])
hist_g = cv2.calcHist([g],[0],None,[256],[0,256])
hist_r = cv2.calcHist([r],[0],None,[256],[0,256])
plt.plot(hist_r, color='r', label="r")
plt.plot(hist_g, color='g', label="g")
plt.plot(hist_b, color='b', label="b")
plt.legend()
plt.show()
img2 = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h, s, v = img2[:,:,0], img2[:,:,1], img2[:,:,2]
hist_h = cv2.calcHist([h],[0],None,[256],[0,256])
hist_s = cv2.calcHist([s],[0],None,[256],[0,256])
hist_v = cv2.calcHist([v],[0],None,[256],[0,256])
plt.plot(hist_h, color='r', label="h")
plt.plot(hist_s, color='g', label="s")
plt.plot(hist_v, color='b', label="v")
plt.legend()
plt.show()
return hist_r,hist_g, hist_b, hist_h, hist_s, hist_v
aaa = "/home/student_DC/desktop/optimization_11_10/original_duplicate.png "
r,g,b,h,s,v = show_img(aaa)
error:
Traceback (most recent call last):
File "/home/student_DC/desktop/optimization_11_10/3_color.py", line 31, in <module>
r,g,b,h,s,v = show_img(aaa)
File "/home/student_DC/desktop/optimization_11_10/3_color.py", line 7, in show_img
b, g, r = img[:,:,0], img[:,:,1], img[:,:,2]
TypeError: 'NoneType' object is not subscriptable
File system paths can be sensitive to minor naming errors. In your case, there is an extra space at the end of the file name. At the shell level, this would have been stripped out, but the operating system API assumes you really did want that space there.
Fix, the space, but also consider adding error handling code. After importing sys,
if img is None:
print(f"Error in image file '{path}', file=sys.stderr)
exit(2)
If you got path from the user, you would want to .strip() before use, to avoid minor mistakes.
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
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.
I'm writing a roguelike with libtcodpy. It works, but when I run this listing: http://kooneiform.wordpress.com/2009/03/29/241/ at the bottom of the page is a full listing and a few others I've tried, I get errors such as this:
FYI I'm on Windows and do have the libtcodpy.py, SDL.dll, libtcod-mingw.dll files and they do work when following the tutorial that is most popular for libtcodpy.
For the listing above I receive this specific error:
$ python roguelike_practice2.py
Traceback (most recent call last):
File "roguelike_practice2.py", line 165, in <module>
draw()
File "roguelike_practice2.py", line 98, in draw
libtcod.console_set_foreground_color(0, libtcod.white)
AttributeError: 'module' object has no attribute 'console_set_foreground_color'
I also on that same program encounter the exact same issue with console_set_background_color, console_print_left. None work. All with the same error.
For other listings such as this one:
#!/usr/bin/python
###imports###
import os
import libtcodpy as libtcod
###utility functions###
def get_key(key):
if key.vk == libtcod.KEY_CHAR:
return chr(key.c)
else:
return key.vk
###global constants and variables###
window_width = 46
window_height = 20
first = True
fov_px = 9
fov_py = 10
fov_recompute = True
fov_map = None
fov_colors = {
'dark wall' : libtcod.Color(0, 0, 100),
'light wall' : libtcod.Color(130, 110, 50),
'dark ground' : libtcod.Color(50, 50, 150),
'light ground' : libtcod.Color(200, 180, 50)
}
fov_init = False
fov_radius = 4
do = {
'up' : (0, -1),
'down' : (0, 1),
'right' : (1, 0),
'left' : (-1, 0)
}
keys = {
'i' : do['up'],
'k' : do['down'],
'j' : do['left'],
'l' : do['right'],
libtcod.KEY_UP : do['up'],
libtcod.KEY_KP8 : do['up']
}
smap = ['##############################################',
'####################### #################',
'##################### # ###############',
'###################### ### ###########',
'################## ##### ####',
'################ ######## ###### ####',
'############### #################### ####',
'################ ###### ##',
'######## ####### ###### # # # ##',
'######## ###### ### ##',
'######## ##',
'#### ###### ### # # # ##',
'#### ### ########## #### ##',
'#### ### ########## ###########=##########',
'#### ################## ##### #####',
'#### ### #### ##### #####',
'#### # #### #####',
'######## # #### ##### #####',
'######## ##### ####################',
'##############################################',
]
###drawing###
def draw():
global fov_px, fov_py, fov_map, first
global fov_init, fov_recompute, smap
if first:
wh = window_height
ww = window_width
first = False
libtcod.console_clear(0)
libtcod.console_set_fore(0, ww, wh, libtcod.white)
libtcod.console_print_left(0, 1, 1, libtcod.BKGND_NONE,
"IJKL : move around")
libtcod.console_set_fore(0, ww, wh, libtcod.black)
libtcod.console_put_char(0, fov_px, fov_py, '#',
libtcod.BKGND_NONE)
for y in range(window_height):
for x in range(window_width):
if smap[y][x] == '=':
libtcod.console_put_char(0, x, y,
libtcod.CHAR_DHLINE,
libtcod.BKGND_NONE)
if not fov_init:
fov_init = True
fov_map = libtcod.map_new(window_width, window_height)
for y in range(window_height):
for x in range(window_width):
if smap[y][x] == ' ':
libtcod.map_set_properties(fov_map, x, y, True, True)
elif smap[y][x] == '=':
libtcod.map_set_properties(fov_map, x, y, True, False)
if fov_recompute:
fov_recompute = False
libtcod.map_compute_fov(fov_map, fov_px, fov_py, fov_radius, True)
for y in range(window_height):
for x in range(window_width):
affect, cell = 'dark', 'ground'
if libtcod.map_is_in_fov(fov_map, x, y):
affect = 'light'
if (smap[y][x] == '#'):
cell = 'wall'
color = fov_colors['%s %s' % (affect, cell)]
libtcod.console_set_back(0, x, y, color, libtcod.BKGND_SET)
###game state updates###
def update(key):
global fov_py, fov_px, fov_recompute, smap
key = get_key(key)
if key in keys:
dx, dy = keys[key]
if smap[fov_py+dy][fov_px+dx] == ' ':
libtcod.console_put_char(0, fov_px, fov_py, ' ',
libtcod.BKGND_NONE)
fov_px = fov_px + dx
fov_py = fov_py + dy
libtcod.console_put_char(0, fov_px, fov_py, '#',
libtcod.BKGND_NONE)
fov_recompute = True
###initialization and main loop###
font = os.path.join('fonts', 'arial12x12.png')
libtcod.console_set_custom_font(font, libtcod.FONT_LAYOUT_TCOD | libtcod.FONT_TYPE_GREYSCALE)
libtcod.console_init_root(window_width, window_height, 'Python Tutorial', False)
while not libtcod.console_is_window_closed():
draw()
libtcod.console_flush()
key = libtcod.console_wait_for_keypress(True)
update(key)
if key.vk == libtcod.KEY_ESCAPE:
break
I receive the following errors, again I have all the needed files in the folder and am on Windows.
Error for listing 2:
Traceback (most recent call last):
File "roguelike_practice1.py", line 167, in <module>
draw()
File "roguelike_practice1.py", line 100, in draw
libtcod.console_set_fore(0, ww, wh, libtcod.white)
File "c:\Users\cshenkan\CloudStation\Programming\Libtcod\Project 2\libtcodpy.p
y", line 764, in console_set_fore
_lib.TCOD_console_set_fore(con, x, y, col)
File "c:\Python27\lib\ctypes\__init__.py", line 378, in __getattr__
func = self.__getitem__(name)
File "c:\Python27\lib\ctypes\__init__.py", line 383, in __getitem__
func = self._FuncPtr((name_or_ordinal, self))
AttributeError: function 'TCOD_console_set_fore' not found
I run into this TCOD_console_set_fore error a bunch. But say I comment that out, I get the same error but with another function such as TCOD_console_set_back, and others.
Not sure why I'm getting these errors. Using Python 2.7.9 32 bit, and libtcod 1.5.1 I believe. Running Windows 7 64 bit. Keep in mind I can get other programs to run that don't require any of those set_foreground and variation functions, or the print_left function or whatever other functions aren't working. But I'm sure it one or two issues affecting all the functions that wont work. \
If anyone has any ideas, I've spent a ton of time looking online to no avail for info. And the forum for libtcod takes days for administrator approval to join - lame.
Anyway thanks in advance! Ask me any questions or if you need clarification.
TCOD 1.5.1 renamed some functions, so that is why your two listings are crashing.
Version 1.5.1 renamed console_set_foreground_color to console_set_default_foreground,console_set_background_color to console_set_default_background, console_set_fore and console_set_back to console_set_char_foreground and console_set_char_background respectively, and console_wait_for_keypress has been replaced with sys_wait_for_event.
Also, console_print_left has been replaced by console_print_ex, which has an extra 'alignment' parameter between background and the string to print.
It appears that those functions were deprecated in 1.5.1. I can find them in 1.5.0, but neither in 1.5.1 nor 1.5.2. I think you would have to use console_print_ex or console_print_rect_ex instead.
Otherwise you could off course switch back to 1.5.0.
I have some troubles with plotting the figure. I have a file with some results computed by application I wrote in c++ and I would like to plot the figure for the computed data.
The problem is that I don't know the 'max' and 'min' limit on axis X and axis Y ...
I tried:
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
def plot_it(ox, oy, x_label, y_label, filename) :
fig = plt.figure()
axis = fig.add_subplot(111)
plt.xlabel(x_label)
plt.ylabel(y_label)
plt.ylim(min(oy),max(oy))
plt.xlim(min(ox),max(ox))
axis.plot(ox, oy, color = 'red')
plt.savefig(filename)
plt.clf()
plt.close()
filename = input("Filename (file with data)\n>")
res = []
try :
with open(filename, 'r') as file :
for line in file :
line = line.rstrip('\n')
res.append(line.split(" "))
except IOError :
print("IO error")
if len(res) != 0 :
ox = []
oy = []
x_label = str(input("OX label\n>"))
y_label = str(input("OY label\n>"))
for i in range(0,len(res)) :
ox.append(res[i][0])
oy.append(res[i][1])
plot_it(ox, oy, x_label, y_label, 'fig_' + str(filename[:len(filename)-4]) + '.png')
Where my file is here: http://pastie.org/private/4rl64ule9ymljmp6g5bfzg (just copy it and save as file.txt)
I got those errors:
Traceback (most recent call last): File "E:/plotter.py", line 43, in
plot_it(ox, oy, x_label, y_label, 'fig_' + str(filename[:len(filename)-4]) + '.png') File "E:/plotter.py", line
14, in plot_it
plt.ylim(min(oy),max(oy)) File "C:\Python27\lib\site-packages\matplotlib\pyplot.py", line 1252, in
ylim
ret = ax.set_ylim(*args, **kwargs) File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 2642, in
set_ylim
bottom, top = mtransforms.nonsingular(bottom, top, increasing=False) File
"C:\Python27\lib\site-packages\matplotlib\transforms.py", line 2282,
in nonsingular
if (not np.isfinite(vmin)) or (not np.isfinite(vmax)): NotImplementedError: Not implemented for this type
Add:
plt.ylim(min(oy),max(oy))
plt.xlim(min(ox),max(ox))
to the second block of code you give, this will set your x and limits to the min/max of your data.