Here is the code:
import random
import numpy as np
class Room:
def __init__(self, name, contents):
self.name = name
self.contents = contents
rooms = np.zeros((11, 11))
maxRooms = 7
possibleNextRoom = []
def resetLevel():
global rooms
for r in range(len(rooms[0])):
for c in range(len(rooms[1])):
rooms[r][c] = 0
possibleNextRoom = []
halfHeight = int(len(rooms[1]) / 2)
halfWidth = int(len(rooms[0]) / 2)
rooms[halfWidth][halfHeight] = 1
def countRooms():
global rooms
roomCount = 0
for r in range(len(rooms)):
for c in range(len(rooms)):
if rooms[r][c] == 1:
roomCount += 1
return roomCount
def findPossibleRooms():
for r in range(len(rooms) - 1):
for c in range(len(rooms) - 1):
if rooms[r][c] == 1:
if rooms[r][c+1] != 1:
possibleNextRoom.append((r, c+1))
if rooms[r][c-1] != 1:
possibleNextRoom.append((r, c-1))
if rooms[r-1][c] != 1:
possibleNextRoom.append((r-1, c))
if rooms[r+1][c] != 1:
possibleNextRoom.append((r+1, c))
def addRoom():
nextRoom = random.randrange(0, len(possibleNextRoom))
rooms[possibleNextRoom[nextRoom][0]][possibleNextRoom[nextRoom][1]] = 1
possibleNextRoom.pop(nextRoom)
def generateLevel():
resetLevel()
while countRooms() < maxRooms:
countRooms()
findPossibleRooms()
addRoom()
def displayLevel():
print(rooms)
generateLevel()
displayLevel()
Here is the Error:
ValueError: empty range for randrange() (0, 0, 0)
I thought I was using random correctly, but appearantly not. I tried making the array start with something in it, but it still gave me the same error. I have been working on this for a long time and its giving me a headache. Any help with this is greatly appreciated. The error is on line 54.
In [90]: import random
In [91]: random.randrange?
Signature: random.randrange(start, stop=None, step=1, _int=<class 'int'>)
Docstring:
Choose a random item from range(start, stop[, step]).
...
This produces your error:
In [92]: random.randrange(0,0)
Traceback (most recent call last):
File "<ipython-input-92-566d68980a89>", line 1, in <module>
random.randrange(0,0)
File "/usr/lib/python3.8/random.py", line 226, in randrange
raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (0, 0, 0)
So if the error occurs in (telling us the line number if 52 is nearly useless)
nextRoom = random.randrange(0, len(possibleNextRoom))
it means possibleNextRoom is an empty list, [] (or possibly something else with a 0 len).
I see a
possibleNextRoom = []
The append in findPossibleRooms operate in-place, so can modify this global list. But they are wrapped in for and if, so I can't say whether they run at all.
In any case, the error tells that nothing has been appended, for one reason or other.
I have written a program (see below) as an implementation of cellular automata in python. When I run the program, I receive a pattern of random seeded noise and the new pattern that has been run through the program. The "." are zeros and the "#" is a one. The issue is, when I run the program I receive the random noise (looks right) but when I receive the smoothed version, I only get periods (zeros).
app.py
import perlin
line = ""
noise = perlin.Noise(20,20, 420, 1)
print(" ")
for i in range(20):
line += "="
print(line)
# Parses smoothed map
line = ""
print(" ")
for i in range(len(noise.map)):
for j in range(len(noise.map[i])):
if noise.map[i][j] == 0:
line += "."
else:
line += "#"
print(line)
line = ""
perlin.py
import numpy as np
class Noise:
def inbounds(self,x,y):
if (x >= 0 and x <= self.width) and (y >=0 and y <= self.height):
return True
else:
return False
def smooth(self,iterations):
for i in range(iterations):
temp_map = self.map
for j in range(self.height):
for k in range(self.width):
neighbor_wall_count = 0
for y in range(j-1,j+1):
for x in range(k-1, k+1):
if self.inbounds(x,y):
if y != j or x != k:
if temp_map[y][x] == 1:
neighbor_wall_count += 1
else:
neighbor_wall_count += 1
if neighbor_wall_count > 3:
self.map[j][k] = 1
else:
self.map[j][k] = 0
def __init__(self, width, height, seed, iter):
# Sets all of the self variables
self.width = width
self.height = height
self.seed = seed
np.random.seed(self.seed)
w, h = self.width, self.height
# Declares the pattern map list
map = [[0 for i in range(w)] for j in range(h)]
#Generator
for y in range(h):
for x in range(w):
map[y][x] = np.random.randint(0,2)
self.map = map
# Parser
line = ""
for i in range(len(self.map)):
for j in range(len(self.map[i])):
if self.map[i][j] == 0:
line += "."
else:
line += "#"
print(line)
line = ""
self.smooth(iter)
Output
#..###.#....#...#..#
..#####..##.#.###..#
###.###.###..####...
###....##..###.#.#..
#.#.###..##...##..##
#......#..#..#.##..#
.###.#.#.##..#...##.
##...##....#####..#.
#..##...#....###..#.
#.....#.##.####...##
#..#..#.#.##..##..#.
.#.###.###...#..#..#
...#.##....#..#.##..
#.#..#.#.#.###..####
.#..#....#..##.###..
#..#.#.#........###.
.#####..#.#..####...
##..#.#.##.##..#..##
##.#.#.##.####.#..##
####.........##..##.
====================
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
the stop argument in python ranges is excluded from the range (range < stop)
For a positive step, the contents of a range r are determined by the
formula r[i] = start + step*i where i >= 0 and r[i] < stop.
For a negative step, the contents of the range are still determined by
the formula r[i] = start + step*i, but the constraints are i >= 0 and
r[i] > stop.
you can tune the smoothness (eg 3 here), by changing the value of that test:
if neighbor_wall_count > 3:
I'm trying to implement a custom IterableDataset in which I read words from a file, get theirs unique id, gather them and return them batched.
import os
import torch
import tqdm
from torch.utils.data import IterableDataset, DataLoader
import vocab # C++ class bound to python with pybind11
class MyIterableDataset(IterableDataset):
def __init__(self, file_path, v, num_workers=4):
super(MyIterableDataset).__init__()
self.file_path = file_path
self.file_size = os.stat(file_path).st_size
self.v = v # vocab object, bound from a C++ class with pybind11
chunk_size = self.file_size // num_workers
start = 0
end = chunk_size
bonus = self.file_size - chunk_size * num_workers
if (bonus > 0):
end = chunk_size + 1
bonus -= 1
self.endpoints = [(start, end)]
for i in range(1, num_workers):
start = end
if (bonus > 0):
end += chunk_size + 1
bonus -= 1
else:
end += chunk_size
self.endpoints.append((start, end))
def read_word(self, f):
ch = ''
word = ""
while True:
ch = f.read(1)
if not ch:
return ''
if (str.isspace(ch)):
if len(word) > 0:
break
if (ch == '\n'):
return "\n"
else:
continue
word += ch
return word
def parse_file(self, start, words_to_read, id):
words_read = 0
f = open(self.file_path, "r")
f.seek(start, 0)
if id > 0:
while True:
ch = f.read(1)
if not ch or str.isspace(ch):
break
start += 1
f.seek(start, 0)
while True:
word = self.read_word(f)
if word and word != "\n":
wid = self.v.word2id(word)
if wid != -1:
words_read += 1
yield wid # if I yield 'word' instead, everything works. You can also yield 1 and you get the error
if words_read >= words_to_read or not word:
break
f.close()
def __iter__(self):
worker_info = torch.utils.data.get_worker_info()
words_to_read = self.v.get_train_words() // worker_info.num_workers
start, end = self.endpoints[worker_info.id]
return self.parse_file(start, words_to_read, worker_info.id)
Upon running a DataLoader over my dataset with
num_workers = 7
v = vocab.Vocab("./text8") # Vocab is a C++ class bound to python with pybind11
ds = MyIterableDataset(file_path=file_path, v=v, num_workers=num_workers)
wids = [j for _, j in tqdm.tqdm(enumerate(DataLoader(ds, num_workers=num_workers, batch_size=10)))]
whenever I yield the word id I get the following error:
RuntimeError Traceback (most recent call last)
<ipython-input-18-04575fb9c982> in <module>
2
3 t0 = time.time()
----> 4 tokens = [j for _, j in tqdm.tqdm(enumerate(DataLoader(ds, num_workers=num_workers, batch_size=10)))]
5 print()
6 print(time.time() - t0)
<ipython-input-18-04575fb9c982> in <listcomp>(.0)
2
3 t0 = time.time()
----> 4 tokens = [j for _, j in tqdm.tqdm(enumerate(DataLoader(ds, num_workers=num_workers, batch_size=10)))]
5 print()
6 print(time.time() - t0)
~/miniconda3/envs/word2gm/lib/python3.8/site-packages/tqdm/std.py in __iter__(self)
1165
1166 try:
-> 1167 for obj in iterable:
1168 yield obj
1169 # Update and possibly print the progressbar.
~/miniconda3/envs/word2gm/lib/python3.8/site-packages/torch/utils/data/dataloader.py in __next__(self)
433 if self._sampler_iter is None:
434 self._reset()
--> 435 data = self._next_data()
436 self._num_yielded += 1
437 if self._dataset_kind == _DatasetKind.Iterable and \
~/miniconda3/envs/word2gm/lib/python3.8/site-packages/torch/utils/data/dataloader.py in _next_data(self)
1066
1067 assert not self._shutdown and self._tasks_outstanding > 0
-> 1068 idx, data = self._get_data()
1069 self._tasks_outstanding -= 1
1070 if self._dataset_kind == _DatasetKind.Iterable:
~/miniconda3/envs/word2gm/lib/python3.8/site-packages/torch/utils/data/dataloader.py in _get_data(self)
1032 else:
1033 while True:
-> 1034 success, data = self._try_get_data()
1035 if success:
1036 return data
~/miniconda3/envs/word2gm/lib/python3.8/site-packages/torch/utils/data/dataloader.py in _try_get_data(self, timeout)
897 except OSError as e:
898 if e.errno == errno.EMFILE:
--> 899 raise RuntimeError(
900 "Too many open files. Communication with the"
901 " workers is no longer possible. Please increase the"
RuntimeError: Too many open files. Communication with the workers is no longer possible. Please increase the limit using `ulimit -n` in the shell or change the sharing strategy by calling `torch.multiprocessing.set_sharing_strategy('file_system')` at the beginning of your code
while if I yield the word everything works!
Can someone help me understand why this is happening in the first place?
I have written some code that cycles multiple variables through a range of roughly 1-255 at different rates in order to cycle through some colors in a graphics program I am writing. My code works, but it is a bit ugly and repeats a lot of code. How could I write this more elegantly?
...
toggleDecrementi = False
toggleDecrementj = False
toggleDecrementk = False
...
for x in range(1,10000):
...
if i >= 250:
toggleDecrementi = True
elif i <= 5:
toggleDecrementi = False
if toggleDecrementi == False:
i = i + 2.5
else:
i = i - 2
if j >= 255:
toggleDecrementj = True
elif j <= 0:
toggleDecrementj = False
if toggleDecrementj == False:
j = j + 1
else:
j = j - 1
if k >= 240:
toggleDecrementk = True
elif k <= 10:
toggleDecrementk = False
if toggleDecrementk == False:
k = k + 3
else:
k = k - 3
Making a single class for your color may simplify your code.
Here's an example:
Note: It doesn't support different values for increment/decrement.
class ColorCycler:
def __init__(self, color_int, color_min, color_max, color_change_value):
self.value = color_int
self.min = color_min
self.max = color_max
self.change = color_change_value
self.increment = True
def __next__(self):
if self.value >= self.max:
self.increment = False
elif self.value <= self.min:
self.increment = True
if self.increment:
self.value += self.change
else:
self.value -= self.change
return self.value
r = ColorCycler(130, 5, 250, 2)
g = ColorCycler(120, 0, 255, 1)
b = ColorCycler(200, 10, 240, 3)
for i in range(10):
print(next(r), next(g), next(b))
Gives you:
128 119 197
126 118 194
124 117 191
122 116 188
120 115 185
118 114 182
116 113 179
114 112 176
112 111 173
110 110 170
You can also contract the logic further by combining the boundary checks and the invert operation, to something like:
if not self.min < self.value < self.max:
self.change = self.change * -1
self.value = max(min(self.value + self.change, self.max), self.min)
Naturally you may want to constrain the result value as initial conditions, if outside, will result in the number flip-flop between two values outside it. That said, contracting the code doesn't necessarily make it simpler to understand, but in this case it's relatively straightforward.
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