Too many values to unpack with python - python

I have a little problem with Python.
I'm try to write an application for DCM standard who some slice and draw the final model.
This is my code:
from lar import *
from scipy import *
import scipy
import numpy as np
from time import time
from pngstack2array3d import pngstack2array3d
colors = 2
theColors = []
DEBUG = False
MAX_CHAINS = colors
# It is VERY important that the below parameter values
# correspond exactly to each other !!
# ------------------------------------------------------------
MAX_CHUNKS = 75
imageHeight, imageWidth = 250,250 # Dx, Dy
# configuration parameters
# ------------------------------------------------------------
beginImageStack = 430
endImage = beginImageStack
nx = ny = 50
imageDx = imageDy = 50
count = 0
# ------------------------------------------------------------
# Utility toolbox
# ------------------------------------------------------------
def ind(x,y): return x + (nx+1) * (y + (ny+1) )
def invertIndex(nx,ny):
nx,ny = nx+1,ny+1
def invertIndex0(offset):
a0, b0 = offset / nx, offset % nx
a1, b1 = a0 / ny, a0 % ny
return b0,b1
return invertIndex0
def invertPiece(nx,ny):
def invertIndex0(offset):
a0, b0 = offset / nx, offset % nx
a1, b1 = a0 / ny, a0 % ny
return b0,b1
return invertIndex0
# ------------------------------------------------------------
# computation of d-chain generators (d-cells)
# ------------------------------------------------------------
# cubic cell complex
# ------------------------------------------------------------
def the3Dcell(coords):
x,y= coords
return [ind(x,y),ind(x+1,y),ind(x,y+1),ind(x+1,y+1)]
# construction of vertex coordinates (nx * ny )
# ------------------------------------------------------------
V = [[x,y] for y in range(ny+1) for x in range(nx+1) ]
if __name__=="__main__" and DEBUG == True:
print "\nV =", V
# construction of CV relation (nx * ny)
# ------------------------------------------------------------
CV = [the3Dcell([x,y]) for y in range(ny) for x in range(nx)]
if __name__=="__main__" and DEBUG == True:
print "\nCV =", CV
#hpc = EXPLODE(1.2,1.2,1.2)(MKPOLS((V,CV[:500]+CV[-500:])))
#box = SKELETON(1)(BOX([1,2,3])(hpc))
#VIEW(STRUCT([box,hpc]))
# construction of FV relation (nx * ny )
# ------------------------------------------------------------
FV = []
v2coords = invertIndex(nx,ny)
for h in range(len(V)):
x,y= v2coords(h)
if (x < nx) and (y < ny): FV.append([h,ind(x+1,y),ind(x,y+1),ind(x+1,y+1)])
if __name__=="__main__" and DEBUG == True:
print "\nFV =",FV
#hpc = EXPLODE(1.2,1.2,1.2)(MKPOLS((V,FV[:500]+FV[-500:])))
#box = SKELETON(1)(BOX([1,2,3])(hpc))
#VIEW(STRUCT([box,hpc]))
# construction of EV relation (nx * ny )
# ------------------------------------------------------------
EV = []
v2coords = invertIndex(nx,ny)
for h in range(len(V)):
x,y = v2coords(h)
if x < nx: EV.append([h,ind(x+1,y)])
if y < ny: EV.append([h,ind(x,y+1)])
if __name__=="__main__" and DEBUG == True:
print "\nEV =",EV
#hpc = EXPLODE(1.2,1.2,1.2)(MKPOLS((V,EV[:500]+EV[-500:])))
#box = SKELETON(1)(BOX([1,2,3])(hpc))
#VIEW(STRUCT([box,hpc]))
# ------------------------------------------------------------
# computation of boundary operators (∂3 and ∂2s)
# ------------------------------------------------------------
"""
# computation of the 2D boundary complex of the image space
# ------------------------------------------------------------
Fx0V, Ex0V = [],[] # x == 0
Fx1V, Ex1V = [],[] # x == nx-1
Fy0V, Ey0V = [],[] # y == 0
Fy1V, Ey1V = [],[] # y == ny-1
v2coords = invertIndex(nx,ny)
for h in range(len(V)):
x,y = v2coords(h)
if (y == 0):
if x < nx: Ey0V.append([h,ind(x+1,y)])
if (x < nx):
Fy0V.append([h,ind(x+1,y),ind(x,y)])
elif (y == ny):
if x < nx: Ey1V.append([h,ind(x+1,y)])
if (x < nx):
Fy1V.append([h,ind(x+1,y),ind(x,y)])
if (x == 0):
if y < ny: Ex0V.append([h,ind(x,y+1)])
if (y < ny):
Fx0V.append([h,ind(x,y+1),ind(x,y)])
elif (x == nx):
if y < ny: Ex1V.append([h,ind(x,y+1)])
if (y < ny):
Fx1V.append([h,ind(x,y+1),ind(x,y)])
FbV = Fy0V+Fy1V+Fx0V+Fx1V
EbV = Ey0V+Ey1V+Ex0V+Ex1V
"""
"""
if __name__=="__main__" and DEBUG == True:
hpc = EXPLODE(1.2,1.2,1.2)(MKPOLS((V,FbV)))
VIEW(hpc)
hpc = EXPLODE(1.2,1.2,1.2)(MKPOLS((V,EbV)))
VIEW(hpc)
"""
# computation of the ∂2 operator on the boundary space
# ------------------------------------------------------------
print "start partial_2_b computation"
#partial_2_b = larBoundary(EbV,FbV)
print "end partial_2_b computation"
# computation of ∂3 operator on the image space
# ------------------------------------------------------------
print "start partial_3 computation"
partial_3 = larBoundary(FV,CV)
print "end partial_3 computation"
# ------------------------------------------------------------
# input from volume image (test: 250 x 250 x 250)
# ------------------------------------------------------------
out = []
Nx,Ny = imageHeight/imageDx, imageWidth/imageDx
segFaces = set(["Fy0V","Fy1V","Fx0V","Fx1V"])
for inputIteration in range(imageWidth/imageDx):
startImage = endImage
endImage = startImage + imageDy
xEnd, yEnd = 0,0
theImage,colors,theColors = pngstack2array3d('SLICES2/', startImage, endImage, colors)
print "\ntheColors =",theColors
theColors = theColors.reshape(1,2)
background = max(theColors[0])
foreground = min(theColors[0])
print "\n(background,foreground) =",(background,foreground)
if __name__=="__main__" and DEBUG == True:
print "\nstartImage, endImage =", (startImage, endImage)
for i in range(imageHeight/imageDx):
for j in range(imageWidth/imageDy):
xStart, yStart = i * imageDx, j * imageDy
xEnd, yEnd = xStart+imageDx, yStart+imageDy
image = theImage[:, xStart:xEnd, yStart:yEnd]
nx,ny = image.shape
if __name__=="__main__" and DEBUG == True:
print "\n\tsubimage count =",count
print "\txStart, yStart =", (xStart, yStart)
print "\txEnd, yEnd =", (xEnd, yEnd)
print "\timage.shape",image.shape
# ------------------------------------------------------------
# image elaboration (chunck: 50 x 50)
# ------------------------------------------------------------
"""
# Computation of (local) boundary to be removed by pieces
# ------------------------------------------------------------
if pieceCoords[0] == 0: boundaryPlanes += ["Fx0V"]
elif pieceCoords[0] == Nx-1: boundaryPlanes += ["Fx1V"]
if pieceCoords[1] == 0: boundaryPlanes += ["Fy0V"]
elif pieceCoords[1] == Ny-1: boundaryPlanes += ["Fy1V"]
"""
#if __name__=="__main__" and DEBUG == True:
#planesToRemove = list(segFaces.difference(boundaryPlanes))
#FVtoRemove = CAT(map(eval,planesToRemove))
count += 1
# compute a quotient complex of chains with constant field
# ------------------------------------------------------------
chains2D = [[] for k in range(colors)]
def addr(x,y): return x + (nx) * (y + (ny))
for x in range(nx):
for y in range(ny):
if (image[x,y] == background):
chains2D[1].append(addr(x,y))
else:
chains2D[0].append(addr(x,y))
#if __name__=="__main__" and DEBUG == True:
#print "\nchains3D =\n", chains3D
# compute the boundary complex of the quotient cell
# ------------------------------------------------------------
objectBoundaryChain = larBoundaryChain(partial_3,chains2D[1])
b2cells = csrChainToCellList(objectBoundaryChain)
sup_cell_boundary = MKPOLS((V,[FV[f] for f in b2cells]))
# remove the (local) boundary (shared with the piece boundary) from the quotient cell
# ------------------------------------------------------------
"""
cellIntersection = matrixProduct(csrCreate([FV[f] for f in b2cells]),csrCreate(FVtoRemove).T)
#print "\ncellIntersection =", cellIntersection
cooCellInt = cellIntersection.tocoo()
b2cells = [cooCellInt.row[k] for k,val in enumerate(cooCellInt.data) if val >= 4]
"""
# ------------------------------------------------------------
# visualize the generated model
# ------------------------------------------------------------
print "xStart, yStart =", xStart, yStart
if __name__=="__main__":
sup_cell_boundary = MKPOLS((V,[FV[f] for f in b2cells]))
if sup_cell_boundary != []:
out += [T([1,2])([xStart,yStart]) (STRUCT(sup_cell_boundary))]
if count == MAX_CHUNKS:
VIEW(STRUCT(out))
# ------------------------------------------------------------
# interrupt the cycle of image elaboration
# ------------------------------------------------------------
if count == MAX_CHUNKS: break
if count == MAX_CHUNKS: break
if count == MAX_CHUNKS: break
And this is the error take from the terminal :
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-4-2e498c6090a0> in <module>()
213
214 image = theImage[:, xStart:xEnd, yStart:yEnd]
--> 215 nx,ny = image.shape
216
217 if __name__=="__main__" and DEBUG == True:
ValueError: too many values to unpack
Someone can help me to solve this issue????

Based on the line:
image = theImage[:, xStart:xEnd, yStart:yEnd]
image is a 3d array, not a 2d array (it appears to be multiple slices of an image), with the 2nd and 3rd dimensions representing x and y respectively. Thus, if you want to get its dimensions you'll need to unpack it into three dimensions, something like:
nslice, nx, ny = image.shape

Related

Reconstruction function for scanlines in IDAT chunk

I'm trying to write png reader using python and zlib. I do not understand what to do after I've decompressed IDAT content. My code now (imagine that we have only one IDAT chunk):
...
def IDAT(self, chunk_size):
data = self.f.read(chunk_size)
raw_colors = zlib.decompress(data)
self.raw_color_values.extend(raw_colors)
self.f.read(4)
self.processIDAT()
def processIDAT(self):
Recon = []
i = 0
bytesPerPixel = self.bit_depth // 8
if self.color_type == 2:
bytesPerPixel = (self.bit_depth // 8) * 3
for y in range(self.file_height): # for each scanline
processRow = [0] * self.file_width
filter_type = self.raw_color_values[y * (self.file_width * bytesPerPixel + 1)]
i += 1
for x in range(self.file_width): # for each byte in scanline
color_index = self.raw_color_values[y * (self.file_width * bytesPerPixel + 1) + 1 + x]
i += 1
if filter_type == 0: # None
Recon_x = color_index
elif filter_type == 1: # Sub
# ??????
elif filter_type == 2: # Up
# ??????
elif filter_type == 3: # Average
# ??????
elif filter_type == 4: # Paeth
Recon_x = color_index + self.PaethPredictor() # what are params here?
else:
print('unknown filter type: ' + str(filter_type))
Recon.append(Recon_x & 0xff) # truncation to byte
return Recon
def PaethPredictor(self, a, b, c):
p = a + b - c
pa = abs(p - a)
pb = abs(p - b)
pc = abs(p - c)
if pa <= pb and pa <= pc:
Pr = a
elif pb <= pc:
Pr = b
else:
Pr = c
return Pr
According to official documentation I have to implement Recon function. What this function does? Are there any implementation references?
The formulas for Recon are right there in the document you linked:

converting code to be able to use Multiprocessing

I have a rather long question I hope I can get help with.
I have a code that runs a simulation by a "while true" loop and after that a "for" loop that saves data from the simulation and restart the sim after given time. This code works fine, but now Im trying to convert this into a multiprocess where I can get 4 simultaneous simulations and for loops. So I tried to put most of the code into a function and then called it but it does not seem to work. Sorry for the long code I appreciate any help!
The first working code without multiprocessing
for z in range(8):
for q in range(100):
time_re = time_re + 3000
tk.after(time_re,appender)
tk.after(time_re,restart)
ava(avaR1)
while True:
time_steps = range(0,iterations+1)
B = Beta.get()
G = Gamma.get()
D = Diff.get()
M = Mor.get()
steps_x_or_y = np.random.rand(n)
steps_x = steps_x_or_y < D/2
steps_y = (steps_x_or_y > D/2) & (steps_x_or_y < D)
nx = (x + np.sign(np.random.randn(n)) * steps_x) % l
ny = (y + np.sign(np.random.randn(n)) * steps_y) % l
for i in np.where( (S==1) & ( np.random.rand(n) < B ))[0]: # loop over infecting agents
S[(x==x[i]) & (y==y[i]) & (S==0)] = 1 # Susceptiples together with infecting agent becomes infected
S[ (S==1) & (np.random.rand(n) < G) ] = 2 # Recovery
S[ (S==1) & (np.random.rand(n) < M) ] = 3 # Death
nrInf1 = sum(S==1)
nrSus.append(sum(S==0))
nrInf.append(sum(S==1))
nrRec.append(sum(S==2))
nrRec1 = sum(S==2)
nrDea = sum(S == 3)
iterations += 1
tk.update()
tk.title('Infected:' + str(np.sum(S==1)))
x = nx # Update x
y = ny # Update y
The second code with me trying to change it to multiprocessing
def main1(i):
# Physical parameters of the system
x = np.floor(np.random.rand(n)*l) # x coordinates
y = np.floor(np.random.rand(n)*l) # y coordinates
S = np.zeros(n) # status array, 0: Susceptiple, 1: Infected, 2: recovered
I = np.argsort((x-l/2)**2 + (y-l/2)**2)
S[I[1:initial_infected]] = 1 # Infect agents that are close to center
nrRec1 = 0
nrDea = []
time_re = 0
particles = []
R = .5 # agent plot radius
nx = x # udpated x
ny = y # updated y
def restart():
global S
I = np.argsort((x-l/2)**2 + (y-l/2)**2)
S = np.zeros(n)
S[I[1:initial_infected]] = 1
rest = Button(tk, text='Restart',command= restart)
rest.place(relx=0.05, rely=.85, relheight= 0.12, relwidth= 0.15 )
def ava(k,o):
global b
k.append(sum(o)/3)
Beta.set(b) # Parameter slider for mortality rate
b += 0.03125
#bSaver.append(b)
def appender(o):
nrDea1.append(nrDea)
o.append(nrRec1)
for j in range(n): # Generate animated particles in Canvas
particles.append( canvas.create_oval( (x[j] )*res/l,
(y[j] )*res/l,
(x[j]+2*R )*res/l,
(y[j]+2*R )*res/l,
outline=ccolor[0], fill=ccolor[0]) )
if i == 1:
b=0
for z in range(3):
for q in range(3):
time_re = time_re + 1000
tk.after(time_re,appender(nrSRec1))
tk.after(time_re,restart)
tk.after(9000,ava(avaR1,nrSRec1))
elif i == 2:
b=0.25
for z in range(3):
for q in range(3):
time_re = time_re + 1000
tk.after(time_re,appender(nrSRec2))
tk.after(time_re,restart)
tk.after(9000,ava(avaR2,nrSRec2))
elif i == 3:
b=.50
for z in range(3):
for q in range(3):
time_re = time_re + 1000
tk.after(time_re,appender(nrSRec3))
tk.after(time_re,restart)
tk.after(9000,ava(avaR3,nrSRec3))
else:
b=.75
for z in range(3):
for q in range(3):
time_re = time_re + 1000
tk.after(time_re,appender(nrSRec4))
tk.after(time_re,restart)
tk.after(9000,ava(avaR4,nrSRec4))
while True:
B = Beta.get()
G = Gamma.get()
D = Diff.get()
steps_x_or_y = np.random.rand(n)
steps_x = steps_x_or_y < D/2
steps_y = (steps_x_or_y > D/2) & (steps_x_or_y < D)
nx = (x + np.sign(np.random.randn(n)) * steps_x) % l
ny = (y + np.sign(np.random.randn(n)) * steps_y) % l
for i in np.where( (S==1) & ( np.random.rand(n) < B ))[0]: # loop over infecting agents
S[(x==x[i]) & (y==y[i]) & (S==0)] = 1 # Susceptiples together with infecting agent becomes infected
S[ (S==1) & (np.random.rand(n) < G) ] = 2 # Recovery
nrDea= sum(S == 3)
nrRec1 = sum(S==2)
tk.update()
tk.title('Infected:' + str(np.sum(S==1)))
x = nx # Update x
y = ny # Update y
if __name__ == '__main__':
p1=mp.Process(target=main1, args=(1,))
p1.start()
p2=mp.Process(target=main1, args=(2,))
p2.start()
p3=mp.Process(target=main1, args=(3,))
p3.start()
p4=mp.Process(target=main1, args=(4,))
p4.start()
joinedList = avaR1+avaR2+avaR3+avaR4
print(joinedList)
Tk.mainloop(canvas)

I'm having a problem with determining the intersection of two lines in this python code

I tried a math formula from analytic geometry but I didn't get the desired results.
As you can see in the code, the user draw two lines and a green circle(point of intersection) appear.
I have tried to fix the problem for hours but I failed. Sometimes the point doesn't appear or appear but in the wrong position.
Source of the formula I used in the code
Docs of pygame the library I used
#!/usr/bin/env python
from pygame import *
from time import sleep
init();
win = display.set_mode((500,500));
lines = []
cords = []
preview = False
xi = -100
yi = -100
def drawlines(flines):
for fcords in flines:
draw.line(win,(0,0,0),fcords[0],fcords[1],4)
while True:
win.fill((255,255,255))
for ev in event.get():
if ev.type == QUIT:
quit();
exit();
elif ev.type == MOUSEBUTTONDOWN:
if ev.button == 1:
preview = True
a = mouse.get_pos()
cords.append(mouse.get_pos())
elif ev.type == MOUSEBUTTONUP:
if ev.button == 1:
cords.append(mouse.get_pos())
lines.append((cords))
cords = []
preview = False
######################################## THIS BROKEN PART #################################
if len(lines) == 2:
#line 1
points_line1 = lines[0]
point1_line1 = points_line1[0]
point2_line1 = points_line1[1]
line1_vector = (point2_line1[0]-point1_line1[0],point2_line1[1]-point1_line1[1])
a_line1 = line1_vector[1]
b_line1 = -line1_vector[0]
c_line1 = -((a_line1*point1_line1[0]) + (b_line1*point1_line1[1]))
#line2
points_line2 = lines[1]
point1_line2 = points_line2[0]
point2_line2 = points_line2[1]
line2_vector = (point2_line2[0]-point1_line2[0],point2_line2[1]-point1_line2[1])
a_line2 = line2_vector[1]
b_line2 = -line2_vector[0]
c_line2 = -((a_line2*point1_line2[0]) + (b_line2*point1_line2[1]))
if (a_line2 != 0 and b_line2 != 0):
if (a_line1 / a_line2) != ( b_line1/b_line2):
#intersection between line1 and line2
yi = ((((a_line1*c_line2) / a_line2) + c_line1) / -b_line1)
xi = (((-b_line1*yi)-c_line1) / a_line1)
###########################################################################################
elif preview:
draw.line(win,(0,0,0),a,mouse.get_pos(),4)
drawlines(lines)
draw.circle(win,(0,200,0),(int(xi),int(yi)),10)
display.flip()
It's hard to dig through your code. Especially c_line1 = -((a_line1*point1_line1[0]) + (b_line1*point1_line1[1])) seems to be odd, because it calculates the Dot product of vector and a point.
Therefore I don't know exactly what's wrong with your code, but I know how to intersect lines. See Problem with calculating line intersections and Collision and Intersection - Line and line.
Write functions that can add, subtract, scale vectors and rotate vectors by 90°. Write a function which calculates the Dot product:
def add(a, b):
return a[0]+b[0], a[1]+b[1]
def sub(a, b):
return a[0]-b[0], a[1]-b[1]
def rot90(v):
return -v[1], v[0]
def mul(v, s):
return v[0]*s, v[1]*s
def dot(a, b):
return a[0]*b[0] + a[1]*b[1]
Calculate the vector from the beginning of the lines to the end of the lines and the normal vectors to the lines. The normal vector is obtained by rotating the line vector by 90°:
#line 1
point1_line1, point2_line1 = lines[0]
line1_vector = sub(point2_line1, point1_line1)
line1_norml = rot90(line1_vector)
#line2
point1_line2, point2_line2 = lines[1]
line2_vector = sub(point2_line2, point1_line2)
line2_norml = rot90(line2_vector)
Calculate the intersection of the line segments. Make sure the lines are not parallel and that the intersection point is on the line segments:
# vector from start point of line 2 to start point of line 1
l2p1_l1p1 = sub(point1_line1, point1_line2)
# intersection
d = dot(line2_vector, line1_norml)
if d != 0: # prallel lines
t = dot(l2p1_l1p1, line1_norml) / d
u = dot(l2p1_l1p1, line2_norml) / d
if 0 <= t <= 1 and 0 <= u <= 1: # intersection on line segments
xi, yi = add(point1_line2, mul(line2_vector, t))
Minimal example:
from pygame import *
init()
win = display.set_mode((500,500))
lines = []
cords = []
preview = False
xi, yi = -100, -100
def drawlines(flines):
for fcords in flines:
draw.line(win,(0,0,0),fcords[0],fcords[1],4)
def add(a, b):
return a[0]+b[0], a[1]+b[1]
def sub(a, b):
return a[0]-b[0], a[1]-b[1]
def rot90(v):
return -v[1], v[0]
def mul(v, s):
return v[0]*s, v[1]*s
def dot(a, b):
return a[0]*b[0] + a[1]*b[1]
run = True
while run:
for ev in event.get():
if ev.type == QUIT:
run = False
elif ev.type == MOUSEBUTTONDOWN:
if ev.button == 1:
preview = True
a = ev.pos
cords.append(a)
elif ev.type == MOUSEBUTTONUP:
if ev.button == 1:
cords.append(ev.pos)
lines.append((cords))
cords = []
preview = False
intersections = []
for i, line1 in enumerate(lines):
for line2 in lines[i+1:]:
#line 1
point1_line1, point2_line1 = line1
line1_vector = sub(point2_line1, point1_line1)
line1_norml = rot90(line1_vector)
#line2
point1_line2, point2_line2 = line2
line2_vector = sub(point2_line2, point1_line2)
line2_norml = rot90(line2_vector)
# vector from start point of line 2 to start point of line 1
l2p1_l1p1 = sub(point1_line1, point1_line2)
# intersection
d = dot(line2_vector, line1_norml)
if d != 0: # prallel lines
t = dot(l2p1_l1p1, line1_norml) / d
u = dot(l2p1_l1p1, line2_norml) / d
if 0 <= t <= 1 and 0 <= u <= 1: # intersection on line segments
xi, yi = add(point1_line2, mul(line2_vector, t))
intersections.append((xi, yi))
win.fill((255,255,255))
if len(cords) % 2 == 1:
draw.line(win,(0,0,0), a, mouse.get_pos(), 4)
drawlines(lines)
for p in intersections:
draw.circle(win, (0,200,0), (round(p[0]), round(p[1])), 10)
display.flip()
quit()
exit()

Why doesn't update repaint a scene?

I am making a marching cubes project in python using PyQt5 and PyOpenGL. I am trying to hide the wireframe cube which marches across the screen, referenced as mainWindow.marchingCube to disappear after cycling through. I managed to get the disappearing cycle to occur, but the cube does not actually disappear. I called the QOpenGLWidget's update function, but the cube still did not disappear.
import sys
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QSlider,
QOpenGLWidget, QLabel, QPushButton
)
from PyQt5.QtCore import Qt
from OpenGL.GL import (
glLoadIdentity, glTranslatef, glRotatef,
glClear, glBegin, glEnd,
glColor3fv, glVertex3fv,
GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT,
GL_QUADS, GL_LINES
)
from OpenGL.GLU import gluPerspective
from numerics import sin, cos, tan, avg, rnd #Numerics is my custom math library.
import random, time
class mainWindow(QMainWindow): #Main class.
shapes = [] #this will hold instances of the following classes: cube
dataPoints = []
zoomLevel = -10
rotateDegreeV = -90
rotateDegreeH = 0
marchActive = False
limit = -1
meshPoints = []
class cube():
render = True
solid = False
color = (1, 1, 1)
def config(self, x, y, z, size = 0.1, solid = False, color = (1, 1, 1)):
self.solid = solid
self.color = color
self.size = size / 2
s = self.size
self.vertices = [
(-s + x, s + y, -s + z),
(s + x, s + y, -s + z),
(s + x, -s + y, -s + z),
(-s + x, -s + y, -s + z),
(-s + x, s + y, s + z),
(s + x, s + y, s + z),
(s + x, -s + y, s + z),
(-s + x, -s + y, s + z)
]
self.edges = [
(0,1), (0,3), (0,4), (2,1),
(2,3), (2,6), (7,3), (7,4),
(7,6), (5,1), (5,4), (5,6)
]
self.facets = [
(0, 1, 2, 3), (0, 1, 6, 5),
(0, 3, 7, 4), (6, 5, 1, 2),
(6, 7, 4, 5), (6, 7, 3, 2)
]
def show(self):
self.render = True
def hide(self):
self.render = False
class dataPoint():
location = (0, 0, 0)
value = 0
shape = None
def place(self, x, y, z):
self.location = (x, y, z)
def set(self, val):
self.value = val
def setShape(self, shape):
self.shape = shape
class meshPoint():
location = (0, 0, 0)
shape = None
def place(self, x, y, z):
self.location = (x, y, z)
def setShape(self, shape):
self.shape = shape
def keyPressEvent(self, event): #This is the keypress detector. I use this to determine input to edit grids.
try:
key = event.key()
#print(key)
if key == 87:
self.rotateV(5)
elif key == 65:
self.rotateH(5)
elif key == 83:
self.rotateV(-5)
elif key == 68:
self.rotateH(-5)
elif key == 67:
self.zoom(1)
elif key == 88:
self.zoom(-1)
elif key == 77:
self.marchStep()
except:
pass
def __init__(self):
super(mainWindow, self).__init__()
self.currentStep = 0
self.width = 700 #Variables used for the setting of the size of everything
self.height = 600
self.setGeometry(0, 0, self.width + 50, self.height) #Set the window size
self.initData(3, 3, 3)
def setupUI(self):
self.openGLWidget = QOpenGLWidget(self) #Create the GLWidget
self.openGLWidget.setGeometry(0, 0, self.width, self.height)
self.openGLWidget.initializeGL()
self.openGLWidget.resizeGL(self.width, self.height) #Resize GL's knowledge of the window to match the physical size?
self.openGLWidget.paintGL = self.paintGL #override the default function with my own?
self.filterSlider = QSlider(Qt.Vertical, self)
self.filterSlider.setGeometry(self.width + 10, int(self.height / 2) - 100, 30, 200)
self.filterSlider.valueChanged[int].connect(self.filter)
self.limitDisplay = QLabel(self)
self.limitDisplay.setGeometry(self.width, int(self.height / 2) - 130, 50, 30)
self.limitDisplay.setAlignment(Qt.AlignCenter)
self.limitDisplay.setText('-1')
self.marchButton = QPushButton(self)
self.marchButton.setGeometry(self.width, int(self.height / 2) - 160, 50, 30)
self.marchButton.setText('March!')
self.marchButton.clicked.connect(self.marchStep)
def marchStep(self):
if not self.marchActive:
marchAddr = len(self.shapes)
self.shapes.append(self.cube())
self.marchingCube = self.shapes[marchAddr]
self.marchActive = True
self.currentStep = 0
if self.currentStep == len(self.marchPoints):
self.currentStep = 0
#print('meshPoints: {}'.format(self.meshPoints))
for mp in self.meshPoints:
#print(mp.shape)
self.shapes.remove(mp.shape)
self.meshPoints.clear()
self.marchingCube.hide()
return
if self.currentStep == 0:
self.marchingCube.show()
p = self.marchPoints[self.currentStep]
x, y, z = p
self.marchingCube.config(x, y, z, size = 1)
points = []
for i in range(8):
point = self.getDataPointByLocation(self.marchingCube.vertices[i])
points.append(point)
self.openGLWidget.update()
#print('step: {} x: {} y: {} z: {}'.format(self.currentStep, x, y, z))
#for point in points:
# print(point.location, end = ' ')
#print()
for pair in self.marchingCube.edges:
pointA = points[pair[0]]
pointB = points[pair[1]]
#print('pointA.value: {} pointB.value: {} limit: {}'.formatpointA.value, pointB.value, self.limit)
if (pointA.value < self.limit and pointB.value > self.limit) or (pointA.value > self.limit and pointB.value < self.limit):
xA, yA, zA = pointA.location
xB, yB, zB = pointB.location
valA = (pointA.value + 1) / 2
valB = (pointB.value + 1) / 2
xC = float(avg([xA, xB]))
yC = float(avg([yA, yB]))
zC = float(avg([zA, zB]))
mp = self.meshPoint()
mp.place(xC, yC, zC)
mp.setShape(self.cube())
mp.shape.config(xC, yC, zC, size = 0.05, solid = True, color = (1, 0, 0))
self.shapes.append(mp.shape)
self.meshPoints.append(mp)
self.currentStep += 1
self.openGLWidget.update()
def zoom(self, value):
self.zoomLevel += value
self.openGLWidget.update()
def rotateV(self, value):
self.rotateDegreeV += value
self.openGLWidget.update()
def rotateH(self, value):
self.rotateDegreeH += value
self.openGLWidget.update()
def filter(self, value):
self.limit = rnd((value / 49.5) -1, -2)
for d in self.dataPoints:
if d.value < self.limit:
d.shape.hide()
else:
d.shape.show()
self.limitDisplay.setText(str(self.limit))
self.openGLWidget.update()
def getDataPointByLocation(self, coord):
x, y, z = coord
for dp in self.dataPoints:
if dp.location == (x, y, z):
return dp
return False
def paintGL(self):
glLoadIdentity()
gluPerspective(45, self.width / self.height, 0.1, 110.0) #set perspective?
glTranslatef(0, 0, self.zoomLevel) #I used -10 instead of -2 in the PyGame version.
glRotatef(self.rotateDegreeV, 1, 0, 0) #I used 2 instead of 1 in the PyGame version.
glRotatef(self.rotateDegreeH, 0, 0, 1)
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
if len(self.shapes) != 0:
glBegin(GL_LINES)
for s in self.shapes:
glColor3fv(s.color)
if s.render and not s.solid:
for e in s.edges:
for v in e:
glVertex3fv(s.vertices[v])
glEnd()
glBegin(GL_QUADS)
for s in self.shapes:
glColor3fv(s.color)
if s.render and s.solid:
for f in s.facets:
for v in f:
glVertex3fv(s.vertices[v])
glEnd()
def initData(self, sizeX, sizeY, sizeZ):
marchSizeX = sizeX - 1
marchSizeY = sizeY - 1
marchSizeZ = sizeZ - 1
xOff = -(sizeX / 2) + 0.5
yOff = -(sizeY / 2) + 0.5
zOff = -(sizeZ / 2) + 0.5
xMarchOff = -(marchSizeX / 2) + 0.5
yMarchOff = -(marchSizeY / 2) + 0.5
zMarchOff = -(marchSizeZ / 2) + 0.5
vals = []
self.marchPoints = []
for z in range(marchSizeZ):
for y in range(marchSizeY):
for x in range(marchSizeX):
self.marchPoints.append((x + xMarchOff, y + yMarchOff ,z + zMarchOff))
for z in range(sizeZ):
for y in range(sizeY):
for x in range(sizeX):
loc = len(self.dataPoints)
val = self.generate(x + xOff, y + yOff, z + zOff)
self.dataPoints.append(self.dataPoint())
self.dataPoints[loc].place(x + xOff, y + yOff, z + zOff)
self.dataPoints[loc].set(val)
loc2 = len(self.shapes)
self.shapes.append(self.cube())
self.shapes[loc2].config(x + xOff, y + yOff, z + zOff, solid = True, color = (0, (val + 1) / 2, (val + 1) / -2 + 1))
self.dataPoints[loc].setShape(self.shapes[loc2])
vals.append(val)
print(avg(vals))
def generate(self, xIn, yIn, zIn): #Function which produces semi-random values based on the supplied coordinates.
i = -(xIn * yIn * (10 + zIn))
j = xIn * yIn * (10 + zIn)
if i < j:
mixer = random.randint(i, j)
else:
mixer = random.randint(j, i + 1)
a = avg([sin(cos(xIn)), tan(tan(yIn)), cos(tan(zIn))])
out = mixer * a
while out > 10:
out -= 5
while out < -10:
out += 5
return float(out / 10)
app = QApplication([])
window = mainWindow()
window.setupUI()
window.show()
sys.exit(app.exec_())
Why doesn't the cube disappear? I have caught wind during my web searches on the subject that update does not always work as expected. Directly calling self.openGLWidget.paintGL() does not work either. What must I do to make the cube disappear?
EDIT:
If I make a call to rotate, rotate, or zoom, the screen refreshes and the meshpoints as well as the marching cube all disappear. I think I may end up making a workaround by calling one of those with a zero value.
To test, save the following code in a file named numerics.py in the same directory as the rest of the code.
from decimal import Decimal as dec
degrad = 'deg'
pi = 3.14159265358979323846
terms = dec(9) #number of terms used for the trig calculations
def version():
print('numerics.py version 1.0.0')
print('Packaged with the cubes project')
def mode(modeinput = ''): #switch between degrees and radians or check the current mode
global degrad
if modeinput == 'deg':
degrad = 'deg'
return 'deg'
if modeinput == 'rad':
degrad = 'rad'
return 'rad'
if modeinput == '':
return degrad
else:
return False
def accuracy(accinput = ''):
global terms
global pi
if accinput == '':
return terms
terms = dec(accinput)
PI = calculatePi(accinput)
print('Pi is: {}'.format(PI))
return terms
def calculatePi(placeIn = terms):
if placeIn > 15:
if input("Warning: You have chosen to calculate more than 20 digits of pi. This may take a LONG TIME and may be inacurate. Enter 'yes' if you wish to proceed. If you enter anything else, this function will revert to 10 digits.") == 'yes':
place = placeIn
else:
place = 10
else:
place = placeIn
print('Calculating Pi...\nPlease wait, as this may take a while.')
PI = dec(3)
addSub = True
for i in range(2, 2 * (int(place) ** 6) + 1, 2):
if addSub:
PI += dec(4) / (dec(i) * dec(i + 1) * dec(i + 2))
elif not addSub:
PI -= dec(4) / (dec(i) * dec(i + 1) * dec(i + 2))
addSub = not addSub
return rnd(PI, -(place), mode = 'cutoff')
def radToDeg(radin):
return (dec(radin) * dec(180 / pi))
def degToRad(degin):
return (dec(degin) * dec(pi / 180))
def avg(numsIn): #return the average of two numbers, specified as an integer or float
num1 = dec(0)
for i in numsIn:
num1 += dec(i)
return rnd(dec(num1 / dec(len(numsIn))))
def sin(anglein, dr = degrad): #return sine of the supplied angle using the predetermined mode or the supplied mode
if dr == 'deg':
while anglein > 180:
anglein -= 360
while anglein < -180:
anglein += 360
angle = degToRad(anglein)
if dr == 'rad':
while anglein > pi:
anglein -= (2 * pi)
while anglein < -pi:
anglein += (2 * pi)
angle = anglein
return rnd(rawsin(dec(angle)), -terms)
def arcsin(ratioin, dr = degrad): #return arcsine of the supplied ratio using the predetermined mode or the supplied mode
if ratioin > 1 or ratioin < -1: #if the input is illegal
return False
attempt = dec(0) #start at 0
target = rnd(dec(ratioin), -terms) #identify the target value
#print('target is: {}'.format(target))
for i in range(-1, int(terms) + 1): #for each place from 10s to terms decimal place (use -i, not i)
#print('Editing place {0}'.format(10 ** -i)) #debugging
for j in range(10): #for 10 steps
#print('current attempt: {}'.format(attempt), end = ' ')
if rnd(sin(attempt, dr), -terms) == target:
if attempt < 0:
final = (attempt * dec(-1))
else:
final = attempt
#print('attempt: {0} final: {1}'.format(attempt, final))
return final
if rnd(sin(attempt, dr), -terms) < target:
#add some
attempt += (dec(10) ** -i)
#print('attempt: {}'.format(attempt), end = ' ')
if rnd(sin(attempt, dr), -terms) > target:
#subtract some
attempt -= (dec(10) ** -i)
#print('attempt: {}'.format(attempt), end = ' ')
#print('')
if attempt < 0:
final = (attempt * dec(-1))
else:
final = attempt
#print('attempt: {0} final: {1}'.format(attempt, final))
return (final)
def cos(anglein, dr = degrad): #return cosine of the supplied angle
if dr == 'deg':
return rawsin(degToRad(90 - anglein))
else:
angle = anglein
return rnd(rawsin(90 - angle), -terms)
def arccos(ratioin, dr = degrad): #return arccosine of the supplied ratio
if ratioin > 1 or ratioin < -1:
return False
attempt = dec(0) #start at 0
target = rnd(dec(ratioin), -terms) #identify the target value
#print('target is: {}'.format(target))
for i in range(-1, int(terms) + 1): #for each place from 10s to terms decimal place (use -i, not i)
#print('Editing place {0}'.format(10 ** -i)) #debugging
for j in range(10): #for 10 steps
#print('current attempt: {}'.format(attempt), end = ' ')
if rnd(cos(attempt, dr), -terms) == target:
if attempt < 0:
final = (attempt * dec(-1))
else:
final = attempt
#print('attempt: {0} final: {1}'.format(attempt, final))
return final
if rnd(cos(attempt, dr), -terms) < target:
#add some
attempt += (dec(10) ** -i)
#print('attempt: {}'.format(attempt), end = ' ')
if rnd(cos(attempt, dr), -terms) > target:
#subtract some
attempt -= (dec(10) ** -i)
#print('attempt: {}'.format(attempt), end = ' ')
#print('')
if attempt < 0:
final = (attempt * dec(-1))
else:
final = attempt
#print('attempt: {0} final: {1}'.format(attempt, final))
return (final)
def tan(anglein, dr = degrad): #return tangent of the supplied angle
a = sin(anglein, dr)
b = cos(anglein, dr)
if (not a == 0) and (not b == 0):
return rnd((a / b), -terms)
else:
return False
def arctan(ratioin, dr = degrad): #return arctangent of the supplied ratio
if ratioin > 1 or ratioin < -1:
return False
attempt = dec(0) #start at 0
target = rnd(dec(ratioin), -terms) #identify the target value
#print('target is: {}'.format(target))
for i in range(-1, int(terms) + 1): #for each place from 10s to terms decimal place (use -i, not i)
#print('Editing place {0}'.format(10 ** -i)) #debugging
for j in range(10): #for 10 steps
#print('current attempt: {}'.format(attempt), end = ' ')
if rnd(tan(attempt, dr), -terms) == target:
if attempt < 0:
final = (attempt * dec(-1))
else:
final = attempt
#print('attempt: {0} final: {1}'.format(attempt, final))
return final
if rnd(tan(attempt, dr), -terms) < target:
#add some
attempt += (dec(10) ** -i)
#print('attempt: {}'.format(attempt), end = ' ')
if rnd(tan(attempt, dr), -terms) > target:
#subtract some
attempt -= (dec(10) ** -i)
#print('attempt: {}'.format(attempt), end = ' ')
#print('')
if attempt < 0:
final = (attempt * dec(-1))
else:
final = attempt
#print('attempt: {0} final: {1}'.format(attempt, final))
return (final)
def rawsin(anglein): #return the result of sine of the supplied angle, using radians
#This is the taylor series used.
#final = x - (x^3 / 3!) + (x^5 / 5!) - (x^7 / 7!) + (x^9 / 9!) - (x^11 / 11!)...
angle = dec(anglein)
final = angle
add = False
for i in range(3, int(terms) * 3, 2):
if add:
final += dec(angle ** i) / fact(i)
elif not add:
final -= dec(angle ** i) / fact(i)
add = not add
return final
def fact(intin): #return the factorial of the given integer, return False if not given an int
if intin == int(intin):
intout = 1
for i in range(1, intin + 1):
intout *= i
return intout
else:
return False
def rnd(numIn, decPlcIn = -terms, mode = 'fiveHigher'): #return the given number, rounded to the given decimal place.
#use 1 to indicate 10s, 0 to indicate 1s, -2 to indicate 100ths, etc.
num1 = dec(numIn)
decPlc = dec(decPlcIn)
if mode == 'fiveHigher':
return dec(str(dec(round(num1 * (dec(10) ** -decPlc))) * (dec(10) ** decPlc)).rstrip('0'))
elif mode == 'cutoff':
return dec(str(dec(int(num1 * (dec(10) ** -decPlc))) * (dec(10) ** decPlc)).rstrip('0'))
def root(numIn, rootVal):
num = dec(numIn)
rt = dec(dec(1) / rootVal)
num1 = num ** rt
return rnd(num1, -terms)
def quad(aIn, bIn, cIn): #Plugin for the quadratic formula. Provide a, b, and c.
a = dec(aIn)
b = dec(bIn)
c = dec(cIn)
try:
posResult = (-b + root((b ** dec(2)) - (dec(4) * a * c), 2)) / (dec(2) * a)
except:
posResult = False
try:
negResult = (-b - root((b ** dec(2)) - (dec(4) * a * c), 2)) / (dec(2) * a)
except:
negResult = False
return (posResult, negResult)
You are missing 1 call to self.openGLWidget.update(). There is a return statement in the instruction block of the if. The function is terminated at this point and the self.openGLWidget.update() instruction at the end of the code is never executed.
Add self.openGLWidget.update() right before return, to solve the issue:
class mainWindow(QMainWindow):
# [...]
def marchStep(self):
if not self.marchActive:
# [...]
self.currentStep = 0
if self.currentStep == len(self.marchPoints):
# [...]
self.meshPoints.clear()
self.marchingCube.hide()
self.openGLWidget.update() # <--------- ADD
return
if self.currentStep == 0:
self.marchingCube.show()
# [...]

How do I get my data in my heatmap?

I've programmed Conways Game of Life in Python and now I'm trying to display the simple data that it gives me as an output in a heat map.
This is my current code:
from Tkinter import *
import matplotlib.pyplot as plt
import time
import numpy as np
import random
size_x = 100
size_y = 10
# create the matrices
cell = [[0 for row in range(0, size_y)] for col in range(0, size_x)]
live = [[0 for row in range(0, size_y)] for col in range(0, size_x)]
temp = [[0 for row in range(0, size_y)] for col in range(0, size_x)]
# process and draw the next frame
def frame():
process()
draw()
root.after(100, frame)
# load the initial data
def load(initial=0.5):
for y in range(0, size_y):
for x in range(0, size_x):
if random.random()<initial: live[x][y] = 1
temp[x][y] = 0
# Applying rules
def process():
for y in range(0, size_y):
for x in range(0, size_x):
lives = live_neighbors(x,y)
if live[x][y] == 1:
if lives < 2 or lives > 3:
temp[x][y] = 0
else:
temp[x][y] = 1
if live[x][y] == 0:
if lives == 3:
temp[x][y] = 1
else:
temp[x][y] = 0
for y in range(0, size_y):
for x in range(0, size_x):
live[x][y] = temp[x][y]
# live = temp
# Count live neighbors
def live_neighbors(a,b):
lives = 0
if live[a][(b+1)%size_y] == 1: lives += 1
if live[a][(b-1)%size_y] == 1: lives += 1
if live[(a+1)%size_x][b] == 1: lives += 1
if live[(a+1)%size_x][(b+1)%size_y] == 1: lives += 1
if live[(a+1)%size_x][(b-1)%size_y] == 1: lives += 1
if live[(a-1)%size_x][b] == 1: lives += 1
if live[(a-1)%size_x][(b+1)%size_y] == 1: lives += 1
if live[(a-1)%size_x][(b-1)%size_y] == 1: lives += 1
return lives
# Draw all cells
def draw():
nLiving = 0
nDead = 0
for y in range(size_y):
for x in range(size_x):
if live[x][y]==0:
canvas.itemconfig(cell[x][y], fill="black")
nDead+=1
if live[x][y]==1:
canvas.itemconfig(cell[x][y], fill="white")
nLiving+=1
print nLiving,nDead
# count cells
def count():
nLiving = 0
nDead = 0
for y in range(size_y):
for x in range(size_x):
if live[x][y]==0:
nDead+=1
if live[x][y]==1:
nLiving+=1
z = nLiving / 10.0
print z,
print "%"
def one_game(initial):
load(initial)
for gen in range(1, 101):
print str(gen) + ":",
count()
process()
def many_games():
numbers = range(1,51)
for initial in numbers:
print initial/100.0
one_game(initial/100.0)
many_games()
#one_game(0.5)
The code for making a normal heat map with given input would be:
fig, ax = plt.subplots(1)
x = np.array( [[11,12,13], [21,22,23], [31,32,33]] )
p = ax.pcolormesh(x)
fig.colorbar(p)
plt.show()
How do I get my data (which in this case would be, the generations, the value which initializes the one_game() function, and nLiving) into an array?
I'm not 100% sure this is what you're intending, but it produced a pretty output heat map :)
def count():
nLiving = 0
nDead = 0
for y in range(size_y):
for x in range(size_x):
if live[x][y]==0:
nDead+=1
if live[x][y]==1:
nLiving+=1
z = nLiving / 10.0
print("nLiving over ten is: ", z,)
print("%")
return nLiving
def one_game(initial):
load(initial)
gen_array = []
for gen in range(1, 101):
print("Gen: ", str(gen) + ":",)
nLiving = count()
process()
gen_array.append(nLiving)
return gen_array
def many_games():
gen_output = []
numbers = range(1,51)
for initial in numbers:
print(initial/100.0)
gen_array = one_game(initial/100.0)
gen_output.append(gen_array)
return gen_output
gen_output = many_games()
#one_game(0.5)
fig, ax = plt.subplots(1)
x = np.array( gen_output )
p = ax.pcolormesh(x)
fig.colorbar(p)
plt.show()
That is just code modified from your count function to the end of the file. Basically you just need to return the output from the functions that you're calling into the right kind of data structures, I think...

Categories