I have completed a code in Python for my summer internship.
Here is the code:
from numpy import loadtxt, abs, mean, float64
def Sum_radii(particle1, particle2): #Sum of radii - to be compared with distance
summ = particle1.radius+particle2.radius
return summ
def PBCdist(particle1, particle2): #PBC conditions to compute distance for any two particles
dx = abs(particle1.x-particle2.x)
dy = abs(particle1.y-particle2.y)
#dz = abs(particle1.z-particle2.z)
if dx > 0.5:
dx = 1.0-dx
else:
dx = dx
if dy > 0.5:
dy = 1.0-dy
else:
dy = dy
#if dz > 0.5:
# dz = 1.0-dz
#else:
# dz = dz
DX = dx**2
DY = dy**2
#DZ = dz**2
dist = DX+DY
distance = dist**0.5
return distance
def Final_step(my_particles):
for particle1 in my_particles:
if len(particle1.neighbours) <=2 :
for k in range(len(particle1.neighbours)):
n = particle1.neighbours[k]
my_particles[n].neighbours.remove(particle1.n)
for particle1 in my_particles:
if len(particle1.neighbours) <=2 :
my_particles.remove(particle1)
return my_particles
def Recursion(my_particles):
l1 = len(my_particles)
my_particles = Final_step(my_particles)
l2 = len(my_particles)
if (l1!=l2):
Recursion(my_particles)
else:
return my_particles
f = open("contacts.txt", "w")
for i in range(len(my_particles)):
list = []
list.append(my_particles[i].n,my_particles[i].neighbours)
print list
print >>f, list
f.close()
def mean_contacts(my_particles):
for k in range(len(my_particles)):
contact_number.append(len(my_particles[k].neighbours))
print ("%.20f" % mean(contact_number))
#Read data and define the class Particle
class Particle():
def __init__(self, (x,y), n, radius, neighbours):
self.n = n
self.x = x
self.y = y
#self.z = z
self.radius = radius
self.neighbours = neighbours
number = loadtxt("Final.dat", usecols=(0,), unpack=True, dtype = int)
c1,c2,r = loadtxt("Final.dat", usecols=(1,2,4), unpack=True, dtype=float64)
number_of_particles = len(number)
my_particles = []
overlap = []
contact_number = []
for i in range(number_of_particles):
n = number[i]
x = c1[i]
y = c2[i]
#z = c3[i]
radius = r[i]
neighbours = []
particle = Particle((x,y), n, radius, neighbours)
my_particles.append(particle)
for particle1 in my_particles:
for particle2 in my_particles:
distance = PBCdist(particle1, particle2)
sum_of_radii = Sum_radii(particle1, particle2)
if (distance < sum_of_radii) and (distance>0):
olap = sum_of_radii - distance
overlap.append(olap)
particle1.neighbours.append(particle2.n)
#Recursion(my_particles)
Final_step(my_particles)
mean_contacts(my_particles)
As you can see, I have not tried the Recursion function, just to make thing more straightforward.
Now, the file im a reading is formatted in the following way:
0 0.70138224747245225821 0.28586219648439409324 0 0.0037570717610070714435
1 0.94878397047547669008 0.17267104541971631249 0 0.0038326670080525947204
2 0.59078448810638095612 0.29243415714920478754 0 0.0037315418643608781225
3 0.38696755396911874936 0.15180438637928708734 0 0.004051606114197996676 2
4 0.71585843878867627676 0.47742962311059283786 0 0.0043035198430089825067
For 16383 rows of data. when I try to run the code after something like 4 mins i get the following error message:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 551, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/dist-packages/spyderlib/widgets/externalshell/monitor.py", line 575, in run
already_pickled=True)
File "/usr/lib/python2.7/dist-packages/spyderlib/utils/bsdsocket.py", line 24, in write_packet
sock.send(struct.pack("l", len(sent_data)) + sent_data)
error: [Errno 32] Broken pipe
I tried it with a 128-row data file and things work perfectly within 1 second.
I was wondering what that message means in the first place and how, if possible, to fix it.
I am running on a Ubuntu12.04, 4 GB ram, 64 bit desktop.
This seems like a known issue in Spyder 2.1.10 , according to Issue 1474 (Issue 1106) .
The fix seems to be available in Spyder 2.2.
Related
My robot use supervisor mode
I want to change value after robot action because i studying DQN now.
My purpose valuse are Robot position value(global coordinate x, y value), lidar value(distance and angle to obstacle), Robot's yaw(using IMU sensors)
Robot get value like this code
how to get robot position
def car_position(self):
self.pos = robot_node.getPosition()
x = self.pos[0]
y = self.pos[1]
return x, y
#how to get lidar value
lidar_point = lidar.getPointCloud() is input
def point_cloud(self, point, num):
lidar_distance = []
lidar_angle = []
for i in range(num):
point_distance = math.sqrt(point[i].x**2 + point[i].y**2 + point[i].z**2)
point_angle = math.atan(point[i].y / point[i].x)
lidar_distance.append(point_distance)
lidar_angle.append(point_angle)
min_dis = min(lidar_distance)
min_pos = lidar_distance.index(min_dis)
angle = lidar_angle[min_pos]
return min_dis, angle
distance function (goal position is random value)
#gx, gy is goal position
def distance(self, cx, cy, gx, gy):
distance = math.sqrt((cx - gx) ** 2 + (cy - gy) ** 2)
goal_angle = math.atan2((gy-cy),(gx-cx))
return distance, goal_angle
how to get Yaw
_, _, yaw = imu.getRollPitchYaw()
Robot main function
for n_epi in range(itteration):
while robot.step(timestep) != -1 and step < 6000:
lidar_point = lidar.getPointCloud()
_, _, yaw = imu.getRollPitchYaw()
car_x, car_y = env.car_position()
distance, robot_angle = env.distance(car_x, car_y, goal_x, goal_y)
obstacle_distance, obstacle_angle = env.point_cloud(lidar_point, len(lidar_point))
dif_angle = abs(robot_angle - yaw)
state = (distance, dif_angle, obstacle_distance, obstacle_angle)
select_action = car.sample_action(torch.tensor(state).float(), epsilon)
state_prime, total_reward, done_num = car.action(select_action, goal_x, goal_y)
action function example
def action(self, num, goal_x, goal_y):
left1.setVelocity(5.0)
right1.setVelocity(5.0)
nxt_car_x, nxt_car_y = env.car_position()
print("nxt_car_x", nxt_car_x)
_, _, next_yaw = imu.getRollPitchYaw()
next_dis, next_robot_angle = env.distance(nxt_car_x, nxt_car_y, goal_x, goal_y)
next_obs, next_angle = env.point_cloud(lidar_point, len(lidar_point))
next_dif_angle = abs(next_robot_angle - next_yaw)
return (next_dis, next_dif_angle, next_obs, next_angle)
OUTPUT (PROBLEM)
state = (7.6161052136099485, 2.6032981992833335, 0.3431832774215816, -1.5699999999690681)
state_prime = (7.6161052136099485, 2.6032981992833335, 0.3431832774215816, -1.5699999999690681)
My robot do action well, go straight and turn right, left But why my robot don't change value???
I think The Robot value must different past_value after action
example
state = (0,0,0,0) ---> action ---> state_prime = (1,1,1,1)
i think my code procedure is value save at car_x, car_y ~~ ---> do action like right1.setVelocity(5.0) --> save value car_x at next_car_x ----> abs(car_x - next_car_x) != 0
But my code value is 0
How can i solve this situation?
i try webots documentaition and code but don't change
plz help me
I im trying to define at what flow "pressure_hill" are equal to "pressure_returnline" in function def calculateflow(Q):
im trying to use sympy solve but get error message below.
pressure_returnlie and pressure_hill are calculating a pressure drop that depends on flowvalue from water. I know that both will have the same pressure drop and I want to calculate what flow I have in each pipe.
When running the code I get TypeError: cannot determine truth value of Relational
Is there a better way than using sympy solver?
Thanks // Sebastian
import numpy as np
import fluids
from scipy import stats
# #input h and D0
# h = 100 # mm
D0 = 149# mm
# flow = 5/60 #m3/min
# density = 999 #kg/m3
pi = 3.1416
# mu = 1E-3 # viscosity
# length = 10 # meter
# #calculation
def valve_pos(pos,control_sig,time):## Change / Secound
cntrl_max = 254
cntrl_min = 1
cntrl_mid = 127
time_forw = 1
time_back = 1.5
time_forw_min = 6
time_back_min = 5
min_pos = 5
max_pos = 149
cntrl_time = 0
cntrl_time_min = 0
way = 1
if control_sig == cntrl_mid:
return 0
if control_sig > cntrl_mid:
cntrl_time = time_forw
cntrl_time_min = time_forw_min
way = 1
else:
cntrl_time = time_back
cntrl_time_min = time_back_min
way = -1
coeff = stats.linregress([cntrl_min,cntrl_mid,cntrl_max],[-1,0,1])
rate = ((max_pos - min_pos) / cntrl_time) * (control_sig*coeff[0] + coeff[1]) * time
rate_min = ((max_pos - min_pos) / cntrl_time_min) * way * time
if abs(rate) < abs(rate_min):
rate = rate_min
if ((pos + rate) > max_pos) & (way > 0):
rate = 0
if ((pos - rate) < min_pos) & (way < 0):
rate = 0
return rate
def velocity(D0, flow):
d = D0/1000
area = (d**2*pi)/4
w0 = flow/area # flow velocity m/s
return w0
def knife_valve_pressure_loss (h,D0, density, flow):
w0 = velocity(D0,flow)
if h/D0 < 0.9 and h/D0 >= 0.2:
a = np.array([7.661175,-72.63827,345.7625,-897.8331,1275.939,-938.8331,278.8193])
i = np.array([0,1,2,3,4,5,6])
dzeta = np.exp(2.3*sum(a*(h/D0)**i))
elif h/D0 >= 0.9:
dzeta = 0.6 - 0.6 * (h/D0)
elif h/D0 < 0.2 and h/D0 >= 0.0:
dzeta = 13114 * (h/D0)**2 - 5216.1 * h/D0 + 553.17
else:
print ('formula cannot be used for this h/D0')
return 0
pressure_loss = dzeta * density * 0.5 * w0**2
if pressure_loss < 0:
pressure_loss = 0
return pressure_loss/100000
def pipe_losses(D0,flow,density,length,mu= 1E-3):
w0 = velocity(D0,flow)
Re = fluids.Reynolds(V=w0, D=D0/1000, rho=1000, mu=mu)
fd = fluids.friction_factor(Re, eD=1E-5/0.05)
K = fluids.K_from_f(fd=fd, L=length, D=D0/1000)
K += fluids.exit_normal()
K += 4*fluids.bend_rounded(Di=D0/1000, angle=90, fd=fd)
K += 3.6
pressure_loss_pipe_fittings = fluids.dP_from_K(K, rho=density, V=w0)/100000
liftheight_loss = 2/10.2
return pressure_loss_pipe_fittings + liftheight_loss
def pressure_hill(flow, h = 149, length = 17, D0 = 139, density = 999):
p_valve = knife_valve_pressure_loss (h,D0, density, flow)
p_system = pipe_losses(D0,flow,density,length)
return p_valve + p_system
def pressure_returnline(flow, h = 149, length = 1, D0 = 139, density = 999):
p_valve = knife_valve_pressure_loss (h,D0, density, flow)
p_system = pipe_losses((76/1000),flow,density,0.5)
return p_valve + p_system
def calculateflow(Q):
from sympy import symbols, solve, Eq, Symbol
x,y = symbols('x,y')
sol = solve(pressure_hill(x) - pressure_returnline(y) ,(x,y))
sol
calculateflow(0.1)
Traceback (most recent call last):
File "<ipython-input-59-42d41eef9605>", line 1, in <module>
calculateflow(0.1)
File "system_losses.py", line 122, in calculateflow
sol = solve(pressure_hill(x) - pressure_returnline(y) ,(x,y))
File "system_losses.py", line 109, in pressure_hill
p_valve = knife_valve_pressure_loss (h,D0, density, flow)
File "system_losses.py", line 90, in knife_valve_pressure_loss
if pressure_loss < 0:
File "relational.py", line 398, in __bool__
raise TypeError("cannot determine truth value of Relational")
TypeError: cannot determine truth value of Relational
There is my code. I fixed it like this:
# Take 3 digits for significant figures in this code
import numpy as np
from math import *
from astropy.constants import *
import matplotlib.pyplot as plt
import time
start_time = time.time()
"""
G = Gravitational constant
g0 = Standard acceleration of gravity ( 9.8 m/s2)
M_sun = Solar mass
M_earth = Earth mass
R_sun = Solar darius
R_earth = Earth equatorial radius
au = Astronomical unit
Astropy.constants doesn't have any parameter of moon.
So I bring the data from wikipedia(https://en.wikipedia.org/wiki/Moon)
"""
M_moon = 7.342E22
R_moon = 1.737E6
M_earth = M_earth.value
R_earth = R_earth.value
G = G.value
perigee, apogee = 3.626E8, 4.054E8
position_E = np.array([0,0])
position_M = np.array([(perigee+apogee)/2.,0])
position_com = (M_earth*position_E+M_moon*position_M)/(M_earth+M_moon)
rel_pE = position_E - position_com
rel_pM = position_M - position_com
F = G*M_moon*M_earth/(position_M[0]**2)
p_E = {"x":rel_pE[0], "y":rel_pE[1],"v_x":0, "v_y":(float(F*rel_pE[0])/M_earth)**.5}
p_M = {"x":rel_pM[0], "y":rel_pM[1],"v_x":0, "v_y":(float(F*rel_pM[0])/M_moon)**.5}
print(p_E, p_M)
t = range(0,365)
data_E , data_M = [], []
def s(initial_velocity, acceleration, time):
result = initial_velocity*time + 0.5*acceleration*time**2
return result
def v(initial_velocity, acceleration, time):
result = initial_velocity + acceleration*time
return result
dist = float(sqrt((p_E["x"]-p_M['x'])**2 + (p_E["y"]-p_M["y"])**2))
xE=[]
yE=[]
xM=[]
yM=[]
data_E, data_M = [None]*len(t), [None]*len(t)
for i in range(1,366):
data_E[i-1] = p_E
data_M[i-1] = p_M
dist = ((p_E["x"]-p_M["x"])**2 + (p_E["y"]-p_M["y"])**2)**0.5
Fg = G*M_moon*M_earth/(dist**2)
theta_E = np.arctan(p_E["y"]/p_E["x"])
theta_M = theta_E + np.pi #np.arctan(data_M[i-1]["y"]/data_M[i-1]["x"])
Fx_E = Fg*np.cos(theta_E)
Fy_E = Fg*np.sin(theta_E)
Fx_M = Fg*np.cos(theta_M)
Fy_M = Fg*np.sin(theta_M)
a_E = Fg/M_earth
a_M = Fg/M_moon
v_E = (p_E["v_x"]**2+p_E["v_y"]**2)**.5
v_M = (p_M["v_x"]**2+p_M["v_y"]**2)**.5
p_E["v_x"] = v(p_E["v_x"], Fx_E/M_earth, 24*3600)
p_E["v_y"] = v(p_E["v_y"], Fy_E/M_earth, 24*3600)
p_E["x"] += s(p_E['v_x'], Fx_E/M_earth, 24*3600)
p_E["y"] += s(p_E['v_y'], Fy_E/M_earth, 24*3600)
p_M["v_x"] = v(p_M["v_x"], Fx_M/M_moon, 24*3600)
p_M["v_y"] = v(p_M["v_y"], Fy_M/M_moon, 24*3600)
p_M["x"] += s(p_M['v_x'], Fx_M/M_moon, 24*3600)
p_M["y"] += s(p_M['v_y'], Fy_M/M_moon, 24*3600)
for i in range(0,len(t)):
xE += data_E[i]["x"]
yE += data_E[i]["y"]
xM += data_M[i]["x"]
yM += data_M[i]["y"]
print("\n Run time \n --- %d seconds ---" %(time.time()-start_time))
after run this code i tried to print data_E and data_M.
Then I can get data but there is no difference. All of the data is the same.
But when I printed data step by step, it totally different.
I have wrong data problem and increase distance problem. Please help me this problem..
The code exits near line 45, where you are trying to assign p_E by pulling the square root of a negative number on the right hand side (as you've moved the [0] coordinate of the Earth to negative values while shifting Earth and Moon into the coordinate system of their center of mass). In line 45, the value of F*rel_pE[0]/M_earth is negative. So the code never reaches the end of the program using python 2.7.14. That bug needs to be solved before trying to discuss any further aspects.
Running this code: Python simulation to calculate potential difference of a rod
Setup Statements:
from __future__ import division
from visual import *
from visual.graph import *
scene = display(x=0, y=0, width=600, height = 600)
graph = gdisplay(x=600, y=0, width=400, height=300)
Main body of code:
#Objects
Vgraph=gcurve(color=color.cyan)
marker = sphere(pos=vector(0,.15,0), radius=.05, color=color.red)
marker.v = vector(0,.5,0)
#Constants
e = 1.6e-19
oofpez = 9e9
scalefactor = 8e-3
dt = 0.001
#Initial values
L = 2 ##length of rod
N = 100 ##Number of point charges
Q = 3e-8
dQ = Q/N
dx = L/N
t = 0
x = (dx-L)/2
dVtotal = 0
Enet = vector(0,0,0)
##Calculations
while x < L/2:
sphere(pos=(x,0,0), radius =1/6, color=color.cyan)
x += dx
while marker.pos.y < 1.15:
x=(dx-L)/2
Enet=vector(0,0,0)
while x < L/2:
r=marker.pos - vector(x,0,0)
rmag=mag(r)
rhat=r/rmag
E=oofpez*dQ/rmag**2*rhat
Enet+=E
x+=dx
dV=-dot(Enet,.0005)
dVtotal=dVtotal+dV
t=t+dt
marker.pos=marker.pos+marker.v*dt
Vgraph.plot(pos=(t,dVtotal))
print ("dVtotal =", dVtotal, "volts")
Produces this error:
Traceback (most recent call last):
File "F:/Purdue/2nd semester/PHYS 272/Labs/lab5.py", line 49, in <module>
Vgraph.plot(pos=(t,dVtotal))
File "C:\Python32\lib\site-packages\vis\graph.py", line 742, in plot
pos,c = primitiveargs(self,args)
File "C:\Python32\lib\site-packages\vis\graph.py", line 708, in primitiveargs
pos = array(arguments['pos'], float)
ValueError: setting an array element with a sequence.
How do I fix it?
I am trying to create tiles using generate_tiles.py and every time I run the script, I get following error:
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 505, in run
self.__target(*self.__args, **self.__kwargs)
File "render_tiles.py", line 114, in loop
self.render_tile(tile_uri, x, y, z)
File "render_tiles.py", line 96, in render_tile
mapnik.render(self.m, im)
MemoryError
Here is my script.
#!/usr/bin/python
from math import pi,cos,sin,log,exp,atan
from subprocess import call
import sys, os
from Queue import Queue
import mapnik
import threading
import random
import argparse
custom_fonts_dir = '/usr/share/fonts/'
mapnik.register_fonts(custom_fonts_dir)
DEG_TO_RAD = pi/180
RAD_TO_DEG = 180/pi
# Default number of rendering threads to spawn, should be roughly equal to number of CPU cores available
NUM_THREADS = 4
def minmax (a,b,c):
a = max(a,b)
a = min(a,c)
return a
class GoogleProjection:
def __init__(self,levels=18):
self.Bc = []
self.Cc = []
self.zc = []
self.Ac = []
c = 256
for d in range(0,levels):
e = c/2;
self.Bc.append(c/360.0)
self.Cc.append(c/(2 * pi))
self.zc.append((e,e))
self.Ac.append(c)
c *= 2
def fromLLtoPixel(self,ll,zoom):
d = self.zc[int(zoom)]
e = round(d[0] + float(ll[0]) * self.Bc[zoom])
f = minmax(sin(DEG_TO_RAD * float(ll[1])),-0.9999,0.9999)
g = round(d[1] + 0.5*log((1+f)/(1-f))*-self.Cc[zoom])
return (e,g)
def fromPixelToLL(self,px,zoom):
e = self.zc[zoom]
f = (px[0] - e[0])/self.Bc[zoom]
g = (px[1] - e[1])/-self.Cc[zoom]
h = RAD_TO_DEG * ( 2 * atan(exp(g)) - 0.5 * pi)
return (f,h)
class RenderThread:
def __init__(self, tile_dir, mapfile, q, printLock, maxZoom):
self.tile_dir = tile_dir
self.q = q
self.m = mapnik.Map(256, 256)
self.printLock = printLock
# Load style XML
mapnik.load_map(self.m, mapfile)
# Obtain projection
self.prj = mapnik.Projection(self.m.srs)
# Projects between tile pixel co-ordinates and LatLong (EPSG:4326)
self.tileproj = GoogleProjection(maxZoom+1)
def render_tile(self, tile_uri, x, y, z):
# Calculate pixel positions of bottom-left & top-right
p0 = (x * 256, (y + 1) * 256)
p1 = ((x + 1) * 256, y * 256)
# Convert to LatLong (EPSG:4326)
l0 = self.tileproj.fromPixelToLL(p0, z);
l1 = self.tileproj.fromPixelToLL(p1, z);
# Convert to map projection (e.g. mercator co-ords EPSG:900913)
c0 = self.prj.forward(mapnik.Coord(l0[0],l0[1]))
c1 = self.prj.forward(mapnik.Coord(l1[0],l1[1]))
# Bounding box for the tile
if hasattr(mapnik,'mapnik_version') and mapnik.mapnik_version() >= 800:
bbox = mapnik.Box2d(c0.x,c0.y, c1.x,c1.y)
else:
bbox = mapnik.Envelope(c0.x,c0.y, c1.x,c1.y)
render_size = 256
self.m.resize(render_size, render_size)
self.m.zoom_to_box(bbox)
self.m.buffer_size = 128
# Render image with default Agg renderer
im = mapnik.Image(render_size, render_size)
mapnik.render(self.m, im)
im.save(tile_uri, 'png256')
def loop(self):
while True:
#Fetch a tile from the queue and render it
r = self.q.get()
if (r == None):
self.q.task_done()
break
else:
(name, tile_uri, x, y, z) = r
exists= ""
if os.path.isfile(tile_uri):
exists= "exists"
else:
self.render_tile(tile_uri, x, y, z)
bytes=os.stat(tile_uri)[6]
empty= ''
if bytes == 103:
empty = " Empty Tile "
self.printLock.acquire()
print name, ":", z, x, y, exists, empty
self.printLock.release()
self.q.task_done()
def render_tiles(bbox, mapfile, tile_dir, minZoom=1,maxZoom=18, name="unknown", num_threads=NUM_THREADS):
print "render_tiles(",bbox, mapfile, tile_dir, minZoom, maxZoom, name,")"
# Launch rendering threads
queue = Queue(32)
printLock = threading.Lock()
renderers = {}
for i in range(num_threads):
renderer = RenderThread(tile_dir, mapfile, queue, printLock, maxZoom)
render_thread = threading.Thread(target=renderer.loop)
render_thread.start()
#print "Started render thread %s" % render_thread.getName()
renderers[i] = render_thread
if not os.path.isdir(tile_dir):
os.mkdir(tile_dir)
gprj = GoogleProjection(maxZoom+1)
ll0 = (bbox[0],bbox[3])
ll1 = (bbox[2],bbox[1])
for z in range(minZoom,maxZoom + 1):
px0 = gprj.fromLLtoPixel(ll0,z)
px1 = gprj.fromLLtoPixel(ll1,z)
print "fromlattolon"
# check if we have directories in place
zoom = "%s" % z
if not os.path.isdir(tile_dir + zoom):
os.mkdir(tile_dir + zoom)
for x in range(int(px0[0]/256.0),int(px1[0]/256.0)+1):
# Validate x co-ordinate
if (x = 2**z):
continue
# check if we have directories in place
str_x = "%s" % x
if not os.path.isdir(tile_dir + zoom + '/' + str_x):
os.mkdir(tile_dir + zoom + '/' + str_x)
for y in range(int(px0[1]/256.0),int(px1[1]/256.0)+1):
# Validate x co-ordinate
if (y = 2**z):
continue
str_y = "%s" % y
tile_uri = tile_dir + zoom + '/' + str_x + '/' + str_y + '.png'
# Submit tile to be rendered into the queue
t = (name, tile_uri, x, y, z)
queue.put(t)
# Signal render threads to exit by sending empty request to queue
for i in range(num_threads):
queue.put(None)
# wait for pending rendering jobs to complete
queue.join()
for i in range(num_threads):
renderers[i].join()
if __name__ == "__main__":
MIN_LON = '29.5732';
MAX_LON = '35.0360';
MIN_LAT = '-1.4840';
MAX_LAT = '4.2144';
bbox = ( MIN_LON, MIN_LAT,MAX_LON, MAX_LAT)
style_file="/home/mossplix/projects/Dev/mapit/map/static/tilemill/uganda_districts.xml"
tile_dir="/home/mossplix/projects/UnicefDev/mapit/map/static/tiles/"
min_zoom=7
max_zoom=14
render_tiles(bbox, style_file, tile_dir, min_zoom, max_zoom)
Here is the mapnik config file
mapnik config
and here is the shapefile. I compiled mapnik from source , so it should be good. what could be the problem?
I can tell that is generate_tiles.py originally, modified slightly.
A MemoryError indicates that you either are requesting an abnormally large image to be rendered or you have found a Mapnik bug.
Since the former is more likely I figure that you have made a mistake during modification of generate_tiles.py. So I took your script, overwrote the latest version in svn and got out a diff of the differences: https://gist.github.com/1197587.
On line #106 and #115 you likely want to use == not = because otherwise you are making very large x and y values that are invalid and may be the cause of very large image requests (that are wrong for a given tile).
Default number of rendering threads to spawn, should be roughly equal to number of CPU cores available
NUM_THREADS = 4
I had exactly the same error with NUM_THREADS=4.
Change the default value of NUM_THREADS to 1. I have an i5 (4 cores/1 thread per core) and NUM_THREADS=4 is very unstable. With NUM_THREADS=1 it works fine. If it works with NUM_THREADS=1 for you, try with NUM_THREADS=2 and NUM_THREADS=3 if nothing crashed.