I am trying to make an radar chart to look at the characteristics of the clusters formed by KMeans. The chart was plotting, but when I changed the variables I want to plot, it throws a run time error with incomplete radarchart. I am using the following code:
def _scale_data(data, ranges):
(x1, x2) = ranges[0]
d = data[0]
return [(d - y1) / (y2 - y1) * (x2 - x1) + x1 for d, (y1, y2) in zip(data, ranges)]
class RadarChart():
def __init__(self, fig, location, sizes, variables, ranges, n_ordinate_levels = 6):
angles = np.arange(0, 360, 360./len(variables))
ix, iy = location[:] ; size_x, size_y = sizes[:]
axes = [fig.add_axes([ix, iy, size_x, size_y], polar = True,
label = "axes{}".format(i)) for i in range(len(variables))]
_, text = axes[0].set_thetagrids(angles, labels = variables)
for txt, angle in zip(text, angles):
if angle > -1 and angle < 181:
txt.set_rotation(angle - 90)
else:
txt.set_rotation(angle - 270)
for ax in axes[1:]:
ax.patch.set_visible(False)
ax.xaxis.set_visible(False)
ax.grid("off")
for i, ax in enumerate(axes):
grid = np.linspace(*ranges[i],num = n_ordinate_levels)
grid_label = [""]+["{:.0f}".format(x) for x in grid[1:-1]]
ax.set_rgrids(grid, labels = grid_label, angle = angles[i])
ax.set_ylim(*ranges[i])
self.angle = np.deg2rad(np.r_[angles, angles[0]])
self.ranges = ranges
self.ax = axes[0]
def plot(self, data, *args, **kw):
sdata = _scale_data(data, self.ranges)
self.ax.plot(self.angle, np.r_[sdata, sdata[0]], *args, **kw)
def fill(self, data, *args, **kw):
sdata = _scale_data(data, self.ranges)
self.ax.fill(self.angle, np.r_[sdata, sdata[0]], *args, **kw)
def legend(self, *args, **kw):
self.ax.legend(*args, **kw)
def title(self, title, *args, **kw):
self.ax.text(0.9, 1, title, transform = self.ax.transAxes, *args, **kw)
#Plotting
fig = plt.figure(figsize=(14,16))
attributes = ['total_disabled', 'average_payment_amount', 'avg_days_btwn_payments', 'days_since_1st_transaction','days_since_last_transaction','amount_pending']
ranges = [[0.01, 1000], [0.01, 10000], [0.01, 50], [0.01, 1000], [0.01, 500], [0.01, 10000]]
index = [0, 1, 2, 3, 4, 5,6,7]
n_groups = n_clusters ; i_cols = 3
i_rows = n_groups//i_cols
size_x, size_y = (1/i_cols), (1/i_rows)
for ind in range(n_clusters):
ix = ind%3 ; iy = i_rows - ind//3
pos_x = ix*(size_x + 0.05) ; pos_y = iy*(size_y + 0.05)
location = [pos_x, pos_y] ; sizes = [size_x, size_y]
#______________________________________________________
data = np.array(clustered_df.loc[index[ind], attributes])
radar = RadarChart(fig, location, sizes, attributes, ranges)
radar.plot(data, color = 'b', linewidth=2.0)
radar.fill(data, alpha = 0.2, color = 'b')
radar.title(title = 'cluster nÂș{}'.format(index[ind]), color = 'r')
ind += 1
And it gives the following error:
C:\Users\arindam\Anaconda3\lib\site-packages\pandas\core\indexing.py:1020: FutureWarning:
Passing list-likes to .loc or [] with any missing label will raise
KeyError in the future, you can use .reindex() as an alternative.
See the documentation here:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#deprecate-loc-reindex-listlike
C:\Users\arindam\Anaconda3\lib\site-packages\matplotlib\projections\polar.py:65: RuntimeWarning:
invalid value encountered in less
I hope someone can help me out with this. Thanks in advance.
Related
I am trying to implement a custom dataset loader. Firstly I resize the images and labels with the same ratio between (0.98, 1,1) then I randomly crop both images and labels with same parameters so that I can feed them into NN. However, I am getting an error from PyTorch functional. Here is my code:
class RandomCrop(object):
def __init__(self, size, padding=None, pad_if_needed=True, fill=0, padding_mode='constant'):
self.size = size
self.padding = padding
self.pad_if_needed = pad_if_needed
self.fill = fill
self.padding_mode = padding_mode
#staticmethod
def get_params(img, output_size):
w, h = img.size
th, tw = output_size
if w == tw and h == th:
return 0, 0, h, w
i = random.randint(0, h - th)
j = random.randint(0, w - tw)
return i, j, th, tw
def __call__(self, data):
img,mask = data["image"],data["mask"]
# pad the width if needed
if self.pad_if_needed and img.size[0] < self.size[1]:
img = F.pad(img, (self.size[1] - img.size[0], 0), self.fill, self.padding_mode)
mask = F.pad(mask, (self.size[1] - mask.size[0], 0), self.fill, self.padding_mode)
# pad the height if needed
if self.pad_if_needed and img.size[1] < self.size[0]:
img = F.pad(img, (0, self.size[0] - img.size[1]), self.fill, self.padding_mode)
mask = F.pad(mask, (0, self.size[0] - mask.size[1]), self.fill, self.padding_mode)
i, j, h, w = self.get_params(img, self.size)
crop_image = transforms.functional.crop(img, i, j, h, w)
crop_mask = transforms.functional.crop(mask, i, j, h, w)
return{"image": crop_image, "mask": crop_mask }
Here is the error:
AttributeError: 'Image' object has no attribute 'dim'
Mistakenly I imported nn.functional.pad instead of the transforms.functional.pad. After changing it everything went smoothly
This question already has answers here:
How to clear memory completely of all matplotlib plots
(5 answers)
Closed 3 years ago.
I will first describe the script and later will publish the code and a way to reproduce the problem, in my machine might not be the case for every machine.
So I have a script that build objects, clouds, with specific properties and export the data to files that is the input to a software called SHDOM, this tool analyze radiation properties and can be further read in the following link.
The script is its a bit long, sorry in advance:
import numpy as np
from itertools import product
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from mpl_toolkits.mplot3d import Axes3D
import gc
def writeDomainFile(type, file_name, temp_vec,
lwc, r_effective, dx, dy,
height_vec):
if type == 2:
assert list(lwc.shape) == list(r_effective.shape), "when the file type is 2 the shapes of lwc and r_effective shold be the same"
x_lwc, y_lwc, z_lwc = lwc.shape
x_r_effetive, y_r_effetive, z_r_effetive = r_effective.shape
fp = open(file_name, 'w')
# write the file format
fp.write("{:}\n".format(type))
# write the number of x, y, z points
fp.write("{:} {:} {:}\n".format(x_lwc, y_lwc, z_lwc))
# write the spacing resolution in x and y
fp.write("{:} {:}\n".format(dx, dy))
# write the height vector
fp.write(" ".join(map(str,height_vec)) + "\n")
# write the temprature vector
fp.write(" ".join(map(str,temp_vec)) + "\n")
indices = product(range(x_lwc), range(y_lwc), range(z_lwc))
print_indices = product(range(1, x_lwc + 1), range(1, y_lwc + 1), range(1, z_lwc + 1))
if type == 1: # only lwc
for triplet, print_triplets in zip(indices, print_indices):
# t = tuple(1 + list(triplet))
if not lwc[triplet]:
fp.write("{:} {:} {:} {:}\n".format(*print_triplets, 0))
else:
fp.write("{:} {:} {:} {:6.4f}\n".format(*print_triplets, lwc[triplet]))
elif type == 2:
for triplet, print_triplets in zip(indices, print_indices):
# t = tuple(map(lambda x: x + 1, list(triplet)))
if not lwc[triplet]:
fp.write("{:} {:} {:} {:} {:}\n".format(*print_triplets, 0, 0))
else:
fp.write("{:} {:} {:} {:6.4f} {:4.2f}\n".format(*print_triplets, lwc[triplet], r_effective[triplet]))
fp.close()
return
def lapseRateTemp(base_temp, position):
temp = np.zeros(position.shape)
temp[0] = base_temp
temp[1:] = base_temp - 6.5 * position[1:]
return np.round(temp, 4)
def createCubicCloudDomain(cloud_tick, x_size, y_size,
dx, dy, dz, r_effective_option, lwc_option,
cloud_x_size, cloud_y_size):
# const
temp0 = 300 # kelvin
N_x = x_size / dx # number of x points
N_y = y_size / dy # number of y points
cld_base = 1.0 # the cloud always start from 1[km] above ground
x_center = N_x / 2
y_center = N_y / 2
prog_x = (cloud_x_size / 2) / dx
prog_y = (cloud_y_size / 2) / dy
cloud_x_west = int(x_center - prog_x)
cloud_x_east = int(x_center + prog_x)
cloud_y_south = int(y_center - prog_y)
cloud_y_north = int(y_center + prog_y)
cloud_x_vec = np.arange(cloud_x_west, cloud_x_east, 1)
cloud_y_vec = np.arange(cloud_y_south, cloud_y_north, 1)
for tick in cloud_tick: # cloud_tick might be a vector
cld_top = cld_base + tick
N_z = tick / dz # number of z points
cloud_z_vec = np.round(np.arange(cld_base, cld_top, dz), 4)
# temprature
temp_base = temp0 - 9.8 * cld_base
temp_vec = lapseRateTemp(temp_base, cloud_z_vec - cld_base,)
temp_cloud = np.tile(temp_vec,(int(temp_vec.shape[0]), int(temp_vec.shape[0]), 1))
temp_domain = np.zeros((int(N_x), int(N_y), int(N_z)))
temp_domain[cloud_x_west:cloud_x_east, cloud_y_south: cloud_y_north, :] = temp_cloud
plotTemperatureGradient(temp_domain, 'test.png')
# del temp_cloud
# del temp_domain
# gc.collect()
for r in r_effective_option:
for l in lwc_option:
r_effective_cloud = np.full((cloud_x_vec.shape[0],
cloud_y_vec.shape[0],
cloud_z_vec.shape[0]),
r)
lwc_cloud = np.full((cloud_x_vec.shape[0],
cloud_y_vec.shape[0],
cloud_z_vec.shape[0]),
l)
r_effective_domain = np.zeros((int(N_x), int(N_y), int(N_z)))
lwc_domain = np.zeros((int(N_x), int(N_y), int(N_z)))
# the positions to enter the cloud data
lwc_domain[cloud_x_west:cloud_x_east, cloud_y_south: cloud_y_north, :] = lwc_cloud
r_effective_domain[cloud_x_west:cloud_x_east, cloud_y_south: cloud_y_north, :] = r_effective_cloud
writeDomainFile(2, "test.txt", temp_vec, lwc_domain, r_effective_domain, dx, dy, cloud_z_vec)
plotGeneratedCloud(lwc_domain, r_effective_domain)
return
def plotTemperatureGradient(temp_mat, file_name):
xs, ys, zs = temp_mat.shape
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y, Z = np.mgrid[:xs, :ys, :zs]
faltten_data = temp_mat.ravel().astype(np.float16)
color_map = np.zeros((faltten_data.shape[0], 4))
# map scalars to colors
minima = np.min(faltten_data[np.nonzero(faltten_data)])
maxima = np.max(faltten_data[np.nonzero(faltten_data)])
norm = matplotlib.colors.Normalize(vmin=minima, vmax=maxima, clip=True)
mapper = cm.ScalarMappable(norm=norm, cmap='jet')
rgba = mapper.to_rgba(faltten_data)
color_map[:,0:3] = rgba[:, 0:3]
color_map[:,3] = np.where(faltten_data > 0, 0.07, 0)
p = ax.scatter(X, Y, Z, c=color_map.astype(np.float16))
ax.set_xlabel('X position [Arb.]')
ax.set_ylabel('Y position [Arb.]')
ax.set_zlabel('Z position [Arb.]')
fig.colorbar(p)
# plt.title(title)
plt.savefig(file_name)
return
def plotGeneratedCloud(lwc, r_effective):
light_blue = np.array([0, 1, 0.7])
matrixPlotter(lwc, 'lwc.png',
'Liquid water content of the cloud',
light_blue)
# gc.collect()
light_pink = np.array([0.9, 0.6, 0.9])
matrixPlotter(r_effective, 'r_effective.png',
'Effective radius of the cloud',
light_pink)
return
def matrixPlotter(mat, file_name, title, c=np.array([0.2, 0.6, 0])):
xs, ys, zs = mat.shape
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y, Z = np.mgrid[:xs, :ys, :zs]
faltten_data = mat.ravel().astype(np.float16)
color_map = np.zeros((faltten_data.shape[0], 4))
color_map[:,0:3] = c
color_map[:,3] = np.where(faltten_data > 0, 0.07, 0)
ax.scatter(X, Y, Z, c=color_map.astype(np.float16))
ax.set_xlabel('X position [Arb.]')
ax.set_ylabel('Y position [Arb.]')
ax.set_zlabel('Z position [Arb.]')
plt.title(title)
plt.savefig(file_name)
return
# def main():
# return
if __name__ == '__main__':
# main()
createCubicCloudDomain([0.5], 2.02, 2.02, 0.01, 0.01, 0.01, [0.5], [1], 0.5, 0.5)
print("Done")
So the problem occur when:
I try to export all 3 plots, calling the following blocks:
plotGeneratedCloud(lwc_domain, r_effective_domain) or
temp_cloud = np.tile(temp_vec,(int(temp_vec.shape[0]), int(temp_vec.shape[0]), 1))
temp_domain = np.zeros((int(N_x), int(N_y), int(N_z)))
temp_domain[cloud_x_west:cloud_x_east, cloud_y_south: cloud_y_north, :] = temp_cloud
plotTemperatureGradient(temp_domain, 'test.png')
When I try to create more then 1 object (cloud), so calling the function with:
createCubicCloudDomain([0.5, 0.6], 2.02, 2.02, 0.01, 0.01, 0.01, [0.5, 0.4], [1, 0.3], 0.5, 0.5)
increasing the domain size like:
createCubicCloudDomain([0.5], 4.02, 4.02, 0.01, 0.01, 0.01, [0.5], [1], 0.5, 0.5)
The type of error I'm getting is the following:
File
"C:\Users\davidsr\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\backends\backend_agg.py",
line 396, in draw
self.figure.draw(self.renderer) File "C:\Users\davidsr\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\artist.py",
line 38, in draw_wrapper
return draw(artist, renderer, *args, **kwargs) File "C:\Users\davidsr\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\figure.py",
line 1735, in draw
mimage._draw_list_compositing_images( File "C:\Users\davidsr\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\image.py",
line 137, in _draw_list_compositing_images
a.draw(renderer) File "C:\Users\davidsr\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\artist.py",
line 38, in draw_wrapper
return draw(artist, renderer, *args, **kwargs) File "C:\Users\davidsr\AppData\Local\Programs\Python\Python38-32\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py",
line 291, in draw
sorted(self.collections, File "C:\Users\davidsr\AppData\Local\Programs\Python\Python38-32\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py",
line 292, in
key=lambda col: col.do_3d_projection(renderer), File "C:\Users\davidsr\AppData\Local\Programs\Python\Python38-32\lib\site-packages\mpl_toolkits\mplot3d\art3d.py",
line 538, in do_3d_projection
vxs, vys, vzs, vis = proj3d.proj_transform_clip(xs, ys, zs, renderer.M) File
"C:\Users\davidsr\AppData\Local\Programs\Python\Python38-32\lib\site-packages\mpl_toolkits\mplot3d\proj3d.py",
line 214, in proj_transform_clip
vec = _vec_pad_ones(xs, ys, zs) File "C:\Users\davidsr\AppData\Local\Programs\Python\Python38-32\lib\site-packages\mpl_toolkits\mplot3d\proj3d.py",
line 189, in _vec_pad_ones
return np.array([xs, ys, zs, np.ones_like(xs)]) MemoryError: Unable to allocate array with shape (4, 2040200) and data type float64
I understand the problem is memory issues, so I thought that deleting the arrays once finish with them might solve the problem, so i used del function or even using the garbage collector solution used in the following question: How can I explicitly free memory in Python?
Would appreciate some help
The figure object persists in memory if you don't .close() it first, and it includes all the data it's plotting.
Try putting a plt.close(fig) before the return statement in matrixPlotter. Then your gc.collect() statements should be able to catch it if it's not collected by matplotlib (and I don't think it is).
i have 2 panels when i extract values of variables
what i need to do is to show all value from 3 panels in the same panel ..
the panel is for showing all information about files in the 3 panels
i try to add in this panels of value of variables from 3 panels to showing in this panel but i get error like :
Traceback (most recent call last):
File "C:\Users\majdoulina\Anaconda3\lib\site-packages\matplotlib\cbook\__init__.py", line 215, in process
func(*args, **kwargs)
File "D:\DATA\app6.py", line 450, in on_press
self.GrandParent.right.bottom.bottom.top.Update(x1,y1,list_var3,lon,lat)
TypeError: Update() missing 1 required positional argument: 'list_var4'
what i need to do is to show value of variable from 3 panels in this panel this is part of code wher i have error :
class MiddlePanelTop(wx.Panel):
def __init__(self, parent):
super().__init__(parent, name="MiddleTop", style = wx.SUNKEN_BORDER,size = (500,200))
self.SetBackgroundColour('black')
def Update(self,zoom_axes):
#Load axis values of the selected rectangle
#zoom_axes=parent.zoom_axes
#duplicate the plot from the main panel
self.figure = Figure(figsize =(5,4))
self.canvas = FigureCanvas(self, -1, self.figure)
self.axes = self.figure.add_subplot(111)
self.figure.subplots_adjust(left=0.009,right=0.99,bottom=0.09,top=0.99)
#Apply axis of drawn rectangle to the plot
self.axes.axis(zoom_axes)
path=file_names
nc = netCDF4.Dataset(file_names)
fic1='D:/DATA/latlon_+000.0_globe.nc'
fic2='D:/DATA/landsea_+000.0.h5'
hdf=h5py.File(fic2,'r')
landsea=hdf['dataset'][:]
var = nc.variables.keys()
list_var3 = [nc.variables['VIS006'],nc.variables['VIS008'],nc.variables['IR_120'],nc.variables['IR_108'],nc.variables['IR_087'],
nc.variables['IR_134'],nc.variables['IR_039'],nc.variables['WV_073'],nc.variables['WV_062'],nc.variables['IR_097']]
print("update2")
data_list = ['VIS006','VIS008','IR_120','IR_108','IR_087','IR_134','IR_039','WV_073','WV_062','IR_097']
list_var3 = [nc.variables[f] for f in data_list]
nc1 = netCDF4.Dataset(fic1,'r')
lons = nc1.variables['lon'][:]
lats = nc1.variables['lat'][:]
self.lons = lons[:]
self.lats = lats[:]
print("Option chosen update")
global index
print("index=",index)
self.list_var3 = list_var3[index][:]
self.axes.imshow(self.list_var3,cmap=plt.cm.gist_yarg)
self.clevs=np.arange(0,3,1)
self.axes.contour(landsea,self.clevs,extend="max",colors='y')
self.axes.get_xaxis().set_visible(False)
self.axes.get_yaxis().set_visible(False)
self.canvas.mpl_connect('button_press_event', self.on_press)
global x1,y1
self.rect = patches.Rectangle((x1, y1), 40, 40,edgecolor='g', alpha=1, fill=None, label='Label')
self.axes.add_patch(self.rect)
self.figure.add_axes(self.axes)
'self.figure.show()'
self.axes.plot()
#add_artist(t)
def on_press(self, click):
global x1, y1
x1, y1 = click.xdata, click.ydata
list_var3 = self.list_var3[int(y1),int(x1)]
lon = self.lons[int(y1),int(x1)]
lat = self.lats[int(y1),int(x1)]
self.GrandParent.right.bottom.bottom.top.Update(x1,y1,list_var3,lon,lat)
zx1 = x1 - 20
zy1 = y1 - 20
zx2 = x1 + 20
zy2 = y1 + 20
self.rect.set_x(x1 - 20) #Move the rectangle and centre it on the X click point
self.rect.set_y(y1 - 20) #Move the rectangle and centre it on the Y click point
x1=x1-20
y1=y1-20
self.axes.plot()
self.canvas.draw()
self.zoom_axes=[zx1,zx2,zy1,zy2]
global zoom
global zoom2
zoom2=self.zoom_axes
self.GrandParent.right.bottom.top.left.Update(self.zoom_axes)
'self.GrandParent.middle.top.Update(zoom)'
self.GrandParent.middle.bottom.Update(zoom)
self.GrandParent.right.top.Update(zoom)
self.GrandParent.right.bottom.top.right.Update(self.zoom_axes)
self.GrandParent.right.bottom.top.left.Update(self.zoom_axes)
self.GrandParent.right.bottom.top.middle.Update(self.zoom_axes)
class MiddlePanelBottom(wx.Panel):
def __init__(self, parent):
super().__init__(parent, name="MiddleBottom", style = wx.SUNKEN_BORDER,size = (300,200))
self.SetBackgroundColour('black')
def Update(self,zoom_axes):
#Load axis values of the selected rectangle
#zoom_axes=parent.zoom_axes
#duplicate the plot from the main panel
self.figure = Figure(figsize =(5,4))
self.canvas = FigureCanvas(self, -1, self.figure)
self.axes = self.figure.add_subplot(111)
self.figure.subplots_adjust(left=0.009,right=0.99,bottom=0.1,top=0.98)
#Apply axis of drawn rectangle to the plot
self.axes.axis(zoom_axes)
path=file_names
nc = netCDF4.Dataset(file_names)
fic1='D:/DATA/latlon_+000.0_globe.nc'
var = nc.variables.keys()
list_var4 = [nc.variables['VIS006'],nc.variables['VIS008'],nc.variables['IR_120'],nc.variables['IR_108'],nc.variables['IR_087'],
nc.variables['IR_134'],nc.variables['IR_039'],nc.variables['WV_073'],nc.variables['WV_062'],nc.variables['IR_097']]
print("update3")
data_list = ['VIS006','VIS008','IR_120','IR_108','IR_087','IR_134','IR_039','WV_073','WV_062','IR_097']
list_var4 = [nc.variables[f] for f in data_list][:]
nc1 = netCDF4.Dataset(fic1,'r')
lons = nc1.variables['lon'][:]
lats = nc1.variables['lat'][:]
self.lons = lons[:]
self.lats = lats[:]
print("Option chosen update")
global index
print("index=",index)
self.list_var4 = list_var4[index][:]
self.axes.imshow(self.list_var4,origin ='lower')
self.axes.get_xaxis().set_visible(False)
self.axes.get_yaxis().set_visible(False)
self.canvas.mpl_connect('button_press_event', self.on_press)
global x1,y1
self.rect = patches.Rectangle((x1, y1), 40, 40,edgecolor='g', alpha=1, fill=None, label='Label')
self.axes.add_patch(self.rect)
self.axes.plot()
def on_press(self, click):
global x1, y1
x1, y1 = click.xdata, click.ydata
list_var4 = self.list_var4[int(y1),int(x1)]
lon = self.lons[int(y1),int(x1)]
lat = self.lats[int(y1),int(x1)]
self.GrandParent.right.bottom.bottom.top.Update(list_var4)
zx1 = x1 - 20
zy1 = y1 - 20
zx2 = x1 + 20
zy2 = y1 + 20
self.rect.set_x(x1 - 20 ) #Move the rectangle and centre it on the X click point
self.rect.set_y(y1 - 20 ) #Move the rectangle and centre it on the Y click point
x1=x1-20
y1=y1-20
self.axes.plot()
self.canvas.draw()
self.zoom_axes=[zx1,zx2,zy1,zy2]
global zoom
global zoom2
zoom=self.zoom_axes
self.GrandParent.right.bottom.top.left.Update(self.zoom_axes)
self.GrandParent.middle.top.Update(zoom)
'self.GrandParent.middle.bottom.Update(zoom)'
self.GrandParent.right.top.Update(zoom)
self.GrandParent.right.bottom.top.right.Update(self.zoom_axes)
self.GrandParent.right.bottom.top.left.Update(self.zoom_axes)
self.GrandParent.right.bottom.top.middle.Update(self.zoom_axes)
class RightPanelBottomBottomTop(wx.Panel):
def __init__(self,parent):
super().__init__(parent,style = wx.SUNKEN_BORDER)
self.text_ctrl = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE|wx.BORDER_SUNKEN|wx.TE_READONLY|wx.TE_RICH2, size=(700,30))
self.text_ctrl.SetBackgroundColour('cyan')
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.text_ctrl,0)
self.SetSizer(sizer)
def Update(self,x1,y1,list_var3,lon,lat,list_var4):
update_str = "X :"+str(int(x1)) + " " +"Y :"+str(int(y1)) + " "+ "var3 :"+str(int(list_var3))+" "+"Lon : "+str(int(lon))+" "+"Lat :"+str(int(lat))+ "var4 :"+str(int(list_var4))
self.text_ctrl.SetValue(update_str)
panel where i showing information is : class RightPanelBottomBottomTop
thank you
I suspect that you have more than one problem with that code.
The error tells you exactly what the problem is i.e.
missing 1 required positional argument: 'list_var4'
You call class RightPanelBottomBottomTop's Update function with 2 different sets of parameters
self.GrandParent.right.bottom.bottom.top.Update(list_var4)
and
self.GrandParent.right.bottom.bottom.top.Update(x1,y1,list_var3,lon,lat)
Neither of those is correct!
It is defined as:
def Update(self,x1,y1,list_var3,lon,lat,list_var4):
I find solution myself but i still have some problem with value i visualize like
i can show name for variables from 2 panel just the first and x y lat lon and name of variable for other panels but still can't show value from var2 and var3 just for var1 !
Please see the following code:
class PickCursor(object):
def __init__(self, collection, alpha_other=0.3, tolerance=5):
self.collection = collection
self.alpha_other = alpha_other
self.pts= collection.get_offsets()
self.num_pts = len(self.pts)
# Need to set a tolerance to make it take effect
self.collection.set_picker(tolerance)
# Ensure that we have separate colors for each object
self.fc = collection.get_facecolors()
if len(self.fc) == 0:
raise ValueError('Collection must have a facecolor')
elif len(self.fc) == 1:
self.fc = np.tile(self.fc, (self.num_pts, 1))
# self.fc is a 2d array every row follows [r, g, b, a]
self.ind = None
self.point_selected = None
self.canvas = ax.figure.canvas
self.canvas.mpl_connect('pick_event', self.onselect)
def onselect(self, event):
self.ind = event.ind[0]
self.point_selected = self.pts[self.ind]
# Change alpha of other points
self.fc[:, -1] = self.alpha_other
self.fc[self.ind, -1] = 1
self.collection.set_facecolors(self.fc)
self.canvas.draw_idle()
fig, ax = plt.subplots(1, 1, figsize=(8, 8))
x = np.arange(0, 10)
y = np.arange(0, 10)
scat = ax.scatter(x, y, s=15)
PickCursor(scat)
The above code works! Basically, it will make points unselected transparent. However, if I wrap the code into a function like this:
def func():
fig, ax = plt.subplots(1, 1, figsize=(8, 8))
x = np.arange(0, 10)
y = np.arange(0, 10)
scat = ax.scatter(x, y, s=15)
PickCursor(scat)
func() ## this line does not work!!!
Anyone please shred some light on this? Thanks!
Your class is being garbage collected because you don't retain a reference to it.
def func():
# ...
return PickCursor(scat)
pc = func()
I have created my k means algorithm for 2 dimensions. I want to modify it for 8 dimensions i.e. the datapoints can take 8-dimensional values and finally return 8-dimensional centroid values.
The code is following :
import random
import math
# Input varibles
#k = 3
#Threshold = 1
DATA = [[2, 1, 1, 2, 1, 1, 1, 5], [ 6, 8, 1, 3, 4, 3, 7, 1],[4, 1, 3, 2, 1, 3, 1, 1],[3, 1, 1, 2, 1, 2, 1, 1],[3 ,1 ,1 ,1, 1, 2, 1, 1],[6, 1, 1, 1, 1, 7, 1, 1],[6, 10, 2, 8, 10, 7, 3, 3]]
BIG_NUMBER = math.pow(10, 10)
data = []
centroids = []
class DataPoint:
def __init__(self, x, y):
self.x = x
self.y = y
def set_x(self, x):
self.x = x
def get_x(self):
return self.x
def set_y(self, y):
self.y = y
def get_y(self):
return self.y
def set_cluster(self, clusterNumber):
self.clusterNumber = clusterNumber
def get_cluster(self):
return self.clusterNumber
class Centroid:
def __init__(self, x, y):
self.x = x
self.y = y
def set_x(self, x):
self.x = x
def get_x(self):
return self.x
def set_y(self, y):
self.y = y
def get_y(self):
return self.y
# Initializing The Centroids
def initialize_centroids(k,DATA):
#find data range in x and y
max_x = max(x for x,y in DATA)
max_y = max(y for x,y in DATA)
min_x = min(x for x,y in DATA)
min_y = min(y for x,y in DATA)
#chosse random x and y between this data range
#assign to centroids
for j in range(k):
#x = random.choice(DATA)
random_x = random.uniform(min_x,max_x)
random_y = random.uniform(min_y,max_y)
centroids.append(Centroid(random_x, random_y))
#print("(", centroids[j].get_x(), ",", centroids[j].get_y(), ")")
return centroids
# Assigning Datapoints to nearest Centroids
def initialize_datapoints(k,DATA):
for i in range(len(DATA)):
newpoint = DataPoint(DATA[i][0], DATA[i][1])
bestMinimum = BIG_NUMBER
data.append(newpoint)
for j in range(k):
distance = get_distance(newpoint.get_x(), newpoint.get_y(), centroids[j].get_x(), centroids[j].get_y())
if(distance < bestMinimum):
bestMinimum = distance
newpoint.set_cluster(j)
return
# Calculating Euclidean distance
def get_distance(dataPointX, dataPointY, centroidX, centroidY):
return math.sqrt(math.pow((centroidY - dataPointY), 2) + math.pow((centroidX - dataPointX), 2))
# Updating Centroid and Clusters till the threshold is met
def update_centroids_n_clusters(k,DATA,Threshold):
dist = 0.0
#print ("a")
for j in range(k):
prev_x = centroids[j].get_x()
prev_y = centroids[j].get_y()
totalX = 0
totalY = 0
totalInCluster = 0
for z in range(len(data)):
if (data[z].get_cluster() == j):
totalX += data[z].get_x()
totalY += data[z].get_y()
totalInCluster += 1
if (totalInCluster > 0):
s_x = (totalX / totalInCluster)
s_y = (totalY / totalInCluster)
centroids[j].set_x(s_x)
centroids[j].set_y(s_y)
x1 = centroids[j].get_x()
y1 = centroids[j].get_y()
x2 = prev_x
y2 = prev_y
dist += get_distance(x1,y1,x2,y2)
conv_val = (1/k)*dist
if(conv_val >= Threshold):
for i in range(len(DATA)):
bestMinimum = BIG_NUMBER
currentCluster = 0
for j in range(k):
distance = get_distance(data[i].get_x(), data[i].get_y(), centroids[j].get_x(), centroids[j].get_y())
if (distance < bestMinimum):
bestMinimum = distance
currentCluster = j
data[i].set_cluster(currentCluster)
update_centroids_n_clusters(k, DATA, Threshold)
return
# Performing K_Means
def Kmeans(k, DATA, Threshold):
initialize_centroids(k,DATA)
initialize_datapoints(k, DATA)
update_centroids_n_clusters(k, DATA, Threshold)
for i in range(k):
p = 0
print()
print("Centroid ", i, " is at")
print("(",centroids[i].get_x(), ",", centroids[i].get_y(), ")")
print("Cluster ", i, " includes:")
for j in range(len(DATA)):
if (data[j].get_cluster() == i):
#print("(", data[j].get_x(), ", ", data[j].get_y(), ")")
p += 1
print(p,"points")
return
Kmeans(3,DATA,0.1)
How should I modify my class Centroid and class DataPoint in this code? Thanks!!
Note: The code is in Python 3
Use arrays instead of x and y.
You want e.g. your distance function to be
def distance(array1, array2):
return (array1 - array2)**2
(assuming you use numpy)