Texture the 3D figure (cylinder) - python
I need to texture my cylinder, I have texture.png and i already did a
polygonal mesh (with triangles).
Here is the code if you need
pastebin
import pyglet
import pyglet.gl as pgl
from pyglet.window import key
import math
win = pyglet.window.Window(1300, 1000, resizable=True)
WINDOW = 1000
tr = 90
INCREMENT = 5
transparant = False
xRotation = -70
zRotation = -30
yRotation = 180
zoom = 1
far = 100
dist = 35
x = -180
y = 70
z = 0
light = False
param = 0
t_prev = -5
start_loop = False
run_loop = False
def run_loop(dt):
on_draw()
def draw_figure():
angle = 0
t = 0
x = y = z = 0
a = 50
b = 100
if not transparant:
pgl.glPolygonMode(pgl.GL_FRONT_AND_BACK, pgl.GL_FILL)
else:
pgl.glPolygonMode(pgl.GL_FRONT_AND_BACK, pgl.GL_LINE)
pgl.glBegin(pgl.GL_TRIANGLE_STRIP)
for i in range(0, tr + 1):
pgl.glColor3ub(0, 0, 0)
if i >= 1:
t1 = a1
t2 = a2
t3 = a3
a1 = x + a * math.cos(i * 2 * math.pi / tr)
a2 = y + b * math.sin(i * 2 * math.pi / tr)
a3 = z + 8
pgl.glVertex3f(a1, a2, a3)
if i >= 1:
pgl.glNormal3f((b2 - t2) * (a3 - b3) - (b3 - t3) * (a2 - b2), (b3 - t3) * (a1 - b1) - (b1 - t1) * (a3 - b3),
(b1 - t1) * (a2 - b2) - (b2 - t2) * (a1 - b1))
b1 = x
b2 = y
b3 = z + 8
pgl.glVertex3f(b1, b2, b3)
pgl.glEnd()
for j in range(1, 27):
pgl.glBegin(pgl.GL_TRIANGLE_STRIP)
pgl.glColor3ub(0, 0, 0)
x1 = a * math.cos(0)
y1 = b * math.sin(0)
a1 = x1 * math.cos(t * math.pi / 360) + y1 * math.sin(t * math.pi / 360)
a2 = - x1 * math.sin(t * math.pi / 360) + y1 * math.cos(t * math.pi / 360)
a3 = z + j * 8
pgl.glVertex3f(a1, a2, a3)
x1 = a * math.cos(0)
y1 = b * math.sin(0)
b1 = x1 * math.cos((t + 16) * math.pi / 360) + y1 * math.sin((t + 16) * math.pi / 360)
b2 = - x1 * math.sin((t + 16) * math.pi / 360) + y1 * math.cos((t + 16) * math.pi / 360)
b3 = z + j * 8 + 8
pgl.glVertex3f(b1, b2, b3)
for i in range(1, tr + 1):
pgl.glColor3ub(0, 0, 0)
x1 = a * math.cos(i * 2 * math.pi / tr)
y1 = b * math.sin(i * 2 * math.pi / tr)
t1 = a1
t2 = a2
t3 = a3
a1 = x1 * math.cos(t * math.pi / 360) + y1 * math.sin(t * math.pi / 360)
a2 = - x1 * math.sin(t * math.pi / 360) + y1 * math.cos(t * math.pi / 360)
a3 = z + j * 8
pgl.glNormal3f((b2 - t2) * (a3 - b3) - (b3 - t3) * (a2 - b2), (b3 - t3) * (a1 - b1) - (b1 - t1) * (a3 - b3),
(b1 - t1) * (a2 - b2) - (b2 - t2) * (a1 - b1))
pgl.glVertex3f(a1, a2, a3)
x1 = a * math.cos(i * 2 * math.pi / tr)
y1 = b * math.sin(i * 2 * math.pi / tr)
b1 = x1 * math.cos((t + 16) * math.pi / 360) + y1 * math.sin((t + 16) * math.pi / 360)
b2 = - x1 * math.sin((t + 16) * math.pi / 360) + y1 * math.cos((t + 16) * math.pi / 360)
b3 = z + j * 8 + 8
pgl.glVertex3f(b1, b2, b3)
t = t + 16
pgl.glEnd()
pgl.glBegin(pgl.GL_TRIANGLE_STRIP)
t = 416
z = z + 144
angle = angle + t
for i in range(0, tr + 1):
pgl.glColor3ub(0, 0, 0)
x1 = x + a * math.cos(i * 2 * math.pi / tr)
y1 = y + b * math.sin(i * 2 * math.pi / tr)
x2 = x1 * math.cos(t * math.pi / 360) + y1 * math.sin(t * math.pi / 360)
y2 = - x1 * math.sin(t * math.pi / 360) + y1 * math.cos(t * math.pi / 360)
if i >= 1:
t1 = a1
t2 = a2
t3 = a3
a1 = x2
a2 = y2
a3 = z + 72
pgl.glVertex3f(a1, a2, a3)
if i >= 1:
pgl.glNormal3f((b2 - t2) * (a3 - b3) - (b3 - t3) * (a2 - b2), (b3 - t3) * (a1 - b1) - (b1 - t1) * (a3 - b3),
(b1 - t1) * (a2 - b2) - (b2 - t2) * (a1 - b1))
b1 = x
b2 = y
b3 = z + 72
pgl.glVertex3f(b1, b2, b3)
angle = angle + i
pgl.glEnd()
#win.event
def on_draw():
global x, y, z, start_loop, run_loop, param, t_prev, zRotation
pgl.glClearColor(0.3, 0.3, 0.3, 0.0)
pgl.glEnable(pgl.GL_DEPTH_TEST)
if light:
pgl.glEnable(pgl.GL_LIGHTING)
pgl.glLightModelf(pgl.GL_LIGHT_MODEL_TWO_SIDE, pgl.GL_TRUE)
pgl.glEnable(pgl.GL_NORMALIZE)
pgl.glClear(pgl.GL_COLOR_BUFFER_BIT | pgl.GL_DEPTH_BUFFER_BIT)
pgl.glLoadIdentity()
pgl.glViewport(0, 0, 1300, 1000)
pgl.glMatrixMode(pgl.GL_PROJECTION)
pgl.glLoadIdentity()
pgl.glOrtho(-1300 / 4, 1300 / 4, -1000 / 4, 1000 / 4, -400, 600)
pgl.glMatrixMode(pgl.GL_MODELVIEW)
pgl.glLoadIdentity()
if light:
material_diffuse = [1.0, 1.0, 1.0, 1.0]
pgl.glMaterialfv(pgl.GL_FRONT_AND_BACK, pgl.GL_DIFFUSE,
(pgl.GLfloat * len(material_diffuse))(*material_diffuse))
light5_diffuse = [1.0, 0.0, 0.0];
light5_position = [0.5, 0.5, 1.0, 0];
pgl.glEnable(pgl.GL_LIGHT5);
pgl.glLightfv(pgl.GL_LIGHT5, pgl.GL_DIFFUSE, (pgl.GLfloat * len(light5_diffuse))(*light5_diffuse));
pgl.glLightfv(pgl.GL_LIGHT5, pgl.GL_POSITION, (pgl.GLfloat * len(light5_position))(*light5_position));
pgl.glLightf(pgl.GL_LIGHT5, pgl.GL_CONSTANT_ATTENUATION, 0.0);
pgl.glLightf(pgl.GL_LIGHT5, pgl.GL_LINEAR_ATTENUATION, 0.4);
pgl.glLightf(pgl.GL_LIGHT5, pgl.GL_QUADRATIC_ATTENUATION, 0.8);
light6_diffuse = [0.0, 1.0, 0.0];
light6_position = [0.5 * math.cos(2 * math.pi / 3), 0.5 * math.sin(2 * math.pi / 3), 1.0, 0];
pgl.glEnable(pgl.GL_LIGHT6);
pgl.glLightfv(pgl.GL_LIGHT6, pgl.GL_DIFFUSE, (pgl.GLfloat * len(light6_diffuse))(*light6_diffuse));
pgl.glLightfv(pgl.GL_LIGHT6, pgl.GL_POSITION, (pgl.GLfloat * len(light6_position))(*light6_position));
pgl.glLightf(pgl.GL_LIGHT6, pgl.GL_CONSTANT_ATTENUATION, 0.0);
pgl.glLightf(pgl.GL_LIGHT6, pgl.GL_LINEAR_ATTENUATION, 0.4);
pgl.glLightf(pgl.GL_LIGHT6, pgl.GL_QUADRATIC_ATTENUATION, 0.8);
light7_diffuse = [0.0, 0.0, 1.0];
light7_position = [0.5 * math.cos(4 * math.pi / 3), 0.5 * math.sin(4 * math.pi / 3), 1.0, 0];
pgl.glEnable(pgl.GL_LIGHT7);
pgl.glLightfv(pgl.GL_LIGHT7, pgl.GL_DIFFUSE, (pgl.GLfloat * len(light7_diffuse))(*light7_diffuse));
pgl.glLightfv(pgl.GL_LIGHT7, pgl.GL_POSITION, (pgl.GLfloat * len(light7_position))(*light7_position));
pgl.glLightf(pgl.GL_LIGHT7, pgl.GL_CONSTANT_ATTENUATION, 0.0);
pgl.glLightf(pgl.GL_LIGHT7, pgl.GL_LINEAR_ATTENUATION, 0.4);
pgl.glLightf(pgl.GL_LIGHT7, pgl.GL_QUADRATIC_ATTENUATION, 0.8);
pgl.glPolygonMode(pgl.GL_FRONT_AND_BACK, pgl.GL_FILL)
pgl.glPushMatrix()
pgl.glTranslatef(x, y, z)
pgl.glRotatef(xRotation, 1, 0, 0)
pgl.glRotatef(yRotation, 0, 1, 0)
pgl.glRotatef(zRotation, 0, 0, 1)
pgl.glScalef(zoom, zoom, zoom)
draw_figure()
if start_loop:
start_loop = False
run_loop = True
x = ((1 - (param / 100)) ** 3) * (-180) + 3 * (param / 100) * ((1 - (param / 100)) ** 2) * (100) + 3 * (
(param / 100) ** 2) * (
1 - (param / 100)) * (0) + ((param / 100) ** 3) * (200)
y = ((1 - (param / 100)) ** 3) * 70 + 3 * (param / 100) * ((1 - (param / 100)) ** 2) * (140) + 3 * (
(param / 100) ** 2) * (
1 - (param / 100)) * (140) + ((param / 100) ** 3) * (
70)
z = ((1 - (param / 100)) ** 3) * 0 + 3 * (param / 100) * ((1 - (param / 100)) ** 2) * (100) + 3 * (
(param / 100) ** 2) * (
1 - (param / 100)) * (100) + ((param / 100) ** 3) * (
0)
elif run_loop:
if param < 100 and param > t_prev:
zRotation += INCREMENT
param = param + 1
t_prev = t_prev + 1
if (param == 100):
t_prev = 105
x = ((1 - (param / 100)) ** 3) * (-180) + 3 * (param / 100) * ((1 - (param / 100)) ** 2) * (100) + 3 * (
(param / 100) ** 2) * (1 - (param / 100)) * (0) + ((param / 100) ** 3) * (200)
y = ((1 - (param / 100)) ** 3) * 70 + 3 * (param / 100) * ((1 - (param / 100)) ** 2) * (140) + 3 * (
(param / 100) ** 2) * (1 - (param / 100)) * (140) + ((param / 100) ** 3) * (
70)
z = ((1 - (param / 100)) ** 3) * 0 + 3 * (param / 100) * ((1 - (param / 100)) ** 2) * (100) + 3 * (
(param / 100) ** 2) * (1 - (param / 100)) * (100) + ((param / 100) ** 3) * (
0)
print(param)
print("плюс")
if param > 0 and param < t_prev:
zRotation -= INCREMENT
param = param - 1
t_prev = t_prev - 1
if (param == 0):
t_prev = -5
x = ((1 - (param / 100)) ** 3) * (-180) + 3 * (param / 100) * ((1 - (param / 100)) ** 2) * (100) + 3 * (
(param / 100) ** 2) * (1 - (param / 100)) * (0) + ((param / 100) ** 3) * (200)
y = ((1 - (param / 100)) ** 3) * 70 + 3 * (param / 100) * ((1 - (param / 100)) ** 2) * (140) + 3 * (
(param / 100) ** 2) * (1 - (param / 100)) * (140) + ((param / 100) ** 3) * (
70)
z = ((1 - (param / 100)) ** 3) * 0 + 3 * (param / 100) * ((1 - (param / 100)) ** 2) * (100) + 3 * (
(param / 100) ** 2) * (1 - (param / 100)) * (100) + ((param / 100) ** 3) * (
0)
print(param)
print("минус")
pgl.glPopMatrix()
#win.event
def on_text_motion(motion):
global xRotation, yRotation, INCREMENT
if motion == key.UP:
xRotation -= INCREMENT
elif motion == key.DOWN:
xRotation += INCREMENT
elif motion == key.LEFT:
yRotation -= INCREMENT
elif motion == key.RIGHT:
yRotation += INCREMENT
#win.event
def on_key_press(symbol, modifiers):
global transparant, dist, tr, x, y, z, INCREMENT, zRotation, light, t, start_loop, run_loop
if symbol == key.T and not transparant:
transparant = True
elif symbol == key.T and transparant:
transparant = False
elif symbol == key.W:
x += 2.5
elif symbol == key.S:
x -= 2.5
elif symbol == key.A:
y -= 2.5
elif symbol == key.D:
y += 2.5
elif symbol == key.Q:
z -= 2.5
elif symbol == key.E:
z += 2.5
elif symbol == key.L:
light = not light
elif symbol == key.Z:
zRotation += INCREMENT
elif symbol == key.X:
zRotation -= INCREMENT
elif symbol == key.ESCAPE:
pyglet.app.exit()
elif symbol == key.P:
tr += 5
elif symbol == key.O:
if tr > 5:
tr -= 5
elif symbol == key.SPACE:
if not run_loop:
start_loop = True
else:
run_loop = False
#win.event
def on_mouse_scroll(x, y, scroll_x, scroll_y):
global zoom
if scroll_y < 0:
zoom += 0.1
elif scroll_y > 0 and zoom - 0.1 > 0:
zoom -= 0.1
#win.event
def on_mouse_press(x, y, button, modifiers):
if button == pyglet.window.mouse.LEFT:
print(x, y)
pyglet.clock.schedule_interval(run_loop, 0.1)
pyglet.app.run()
Edit:
First you have to load the texture image to a texture object by pyglet.image.load respectively get_texture():
texture_obj = pyglet.image.load('texture.png').get_texture()
The texture has to be bound by glBindTexture:
pgl.glBindTexture(pgl.GL_TEXTURE_2D, texture_obj.id)
Two-dimensional texturing is enabled by glEnable(GL_TEXTURE_2D) and can be disabled by glDisable(GL_TEXTURE_2D).
If texturing is enables then the texture wich is currently bound when the geometry is drawn by the glBegin/glEnd sequence is applied:
pgl.glEnable(pgl.GL_TEXTURE_2D)
If texturing is enabled, then by default the color of the texel is multiplied by the current color, because by default the texture environment mode (GL_TEXTURE_ENV_MODE) is GL_MODULATE. See glTexEnv.
This causes that the color of the texels of the texture is "mixed" by the last color which you have set by glColor3ub.
Set a "white" color before you render the texture, to solve your issue:
plg.glColor3ub(255, 255, 255)
or
pgl.glColor3f(1, 1, 1)
Likewise you can change the environment mode to GL_REPLACE, instead:
pgl.glTexEnvi(pgl.GL_TEXTURE_ENV, pgl.GL_TEXTURE_ENV_MODE, pgl.GL_REPLACE)
When glVertex is called, the the current texture coordinates are associated with the vertex coordinate. The texture coordinate is set by glTexCoord2f.
You've to set the texture coordinates corresponding to each vertex coordinate. The texture coordinates have to be in range [0, 1]. See also How do opengl texture coordinates work?.
e.g.
u = math.cos(i * 2 * math.pi / tr)
v = math.sin(i * 2 * math.pi / tr)
pgl.glTexCoord2f(u*0.5+0.5, v*0.5+0.5)
a1 = x + a * u
a2 = y + b * v
a3 = z + 8
pgl.glVertex3f(a1, a2, a3)
The function draw_figure may look as follows. Note, I don't exactly know how you want to wrap the texture to the mesh, so I calculate the texture coordinates as I thought. You may have to a adapt the calculation of the texture coordinates to your needs:
texture_obj = None
def draw_figure():
global texture_obj
# [...]
if texture_obj == None:
texture_obj = pyglet.image.load('texture.png').get_texture()
pgl.glBindTexture(pgl.GL_TEXTURE_2D, texture_obj.id)
pgl.glEnable(pgl.GL_TEXTURE_2D)
pgl.glTexEnvi(pgl.GL_TEXTURE_ENV, pgl.GL_TEXTURE_ENV_MODE, pgl.GL_REPLACE)
if not transparant:
pgl.glPolygonMode(pgl.GL_FRONT_AND_BACK, pgl.GL_FILL)
else:
pgl.glPolygonMode(pgl.GL_FRONT_AND_BACK, pgl.GL_LINE)
pgl.glBegin(pgl.GL_TRIANGLE_STRIP)
for i in range(0, tr + 1):
pgl.glColor3ub(255, 255, 255)
if i >= 1:
t1 = a1
t2 = a2
t3 = a3
u = math.cos(i * 2 * math.pi / tr)
v = math.sin(i * 2 * math.pi / tr)
a1 = x + a * u
a2 = y + b * v
a3 = z + 8
pgl.glTexCoord2f(u*0.5+0.5, v*0.5+0.5)
pgl.glVertex3f(a1, a2, a3)
if i >= 1:
pgl.glNormal3f((b2 - t2) * (a3 - b3) - (b3 - t3) * (a2 - b2), (b3 - t3) * (a1 - b1) - (b1 - t1) * (a3 - b3),
(b1 - t1) * (a2 - b2) - (b2 - t2) * (a1 - b1))
b1 = x
b2 = y
b3 = z + 8
pgl.glTexCoord2f(0.5, 0.5)
pgl.glVertex3f(b1, b2, b3)
pgl.glEnd()
for j in range(1, 27):
pgl.glBegin(pgl.GL_TRIANGLE_STRIP)
pgl.glColor3ub(255, 255, 255)
x1 = a * math.cos(0)
y1 = b * math.sin(0)
a1 = x1 * math.cos(t * math.pi / 360) + y1 * math.sin(t * math.pi / 360)
a2 = - x1 * math.sin(t * math.pi / 360) + y1 * math.cos(t * math.pi / 360)
a3 = z + j * 8
pgl.glTexCoord2f(0.0, 0.0)
pgl.glVertex3f(a1, a2, a3)
b1 = x1 * math.cos((t + 16) * math.pi / 360) + y1 * math.sin((t + 16) * math.pi / 360)
b2 = - x1 * math.sin((t + 16) * math.pi / 360) + y1 * math.cos((t + 16) * math.pi / 360)
b3 = z + j * 8 + 8
u = math.cos((t + 16) * math.pi / 360) + math.sin((t + 16) * math.pi / 360)
v = (j-1)/26
pgl.glTexCoord2f(0.0, 0.0)
pgl.glVertex3f(b1, b2, b3)
for i in range(1, tr + 1):
pgl.glColor3ub(255, 255, 255)
x1 = a * math.cos(i * 2 * math.pi / tr)
y1 = b * math.sin(i * 2 * math.pi / tr)
t1 = a1
t2 = a2
t3 = a3
a1 = x1 * math.cos(t * math.pi / 360) + y1 * math.sin(t * math.pi / 360)
a2 = - x1 * math.sin(t * math.pi / 360) + y1 * math.cos(t * math.pi / 360)
a3 = z + j * 8
pgl.glNormal3f((b2 - t2) * (a3 - b3) - (b3 - t3) * (a2 - b2), (b3 - t3) * (a1 - b1) - (b1 - t1) * (a3 - b3),
(b1 - t1) * (a2 - b2) - (b2 - t2) * (a1 - b1))
v = math.cos(t * math.pi / 360) + math.sin(t * math.pi / 360)
pgl.glTexCoord2f((i-1)/tr, (26-j)/26)
pgl.glVertex3f(a1, a2, a3)
x1 = a * math.cos(i * 2 * math.pi / tr)
y1 = b * math.sin(i * 2 * math.pi / tr)
b1 = x1 * math.cos((t + 16) * math.pi / 360) + y1 * math.sin((t + 16) * math.pi / 360)
b2 = - x1 * math.sin((t + 16) * math.pi / 360) + y1 * math.cos((t + 16) * math.pi / 360)
b3 = z + j * 8 + 8
v = math.cos((t + 16) * math.pi / 360) + math.sin((t + 16) * math.pi / 360)
pgl.glTexCoord2f((i-1)/tr, (25-j)/26)
pgl.glVertex3f(b1, b2, b3)
t = t + 16
pgl.glEnd()
pgl.glBegin(pgl.GL_TRIANGLE_STRIP)
t = 416
z = z + 144
angle = angle + t
for i in range(0, tr + 1):
pgl.glColor3ub(255, 255, 255)
u = math.cos(i * 2 * math.pi / tr)
v = math.sin(i * 2 * math.pi / tr)
x1 = x + a * u
y1 = y + b * v
x2 = x1 * math.cos(t * math.pi / 360) + y1 * math.sin(t * math.pi / 360)
y2 = - x1 * math.sin(t * math.pi / 360) + y1 * math.cos(t * math.pi / 360)
if i >= 1:
t1 = a1
t2 = a2
t3 = a3
a1 = x2
a2 = y2
a3 = z + 72
pgl.glTexCoord2f(u*0.5+0.5, v*0.5+0.5)
pgl.glVertex3f(a1, a2, a3)
if i >= 1:
pgl.glNormal3f((b2 - t2) * (a3 - b3) - (b3 - t3) * (a2 - b2), (b3 - t3) * (a1 - b1) - (b1 - t1) * (a3 - b3),
(b1 - t1) * (a2 - b2) - (b2 - t2) * (a1 - b1))
b1 = x
b2 = y
b3 = z + 72
pgl.glTexCoord2f(0.5, 0.5)
pgl.glVertex3f(b1, b2, b3)
angle = angle + i
pgl.glEnd()
Related
Cant exit while loop on Simpson's Rule
I am trying to calculate an integral using Simpson's Rule formula.The catch is that the value of the integral is the one that satisfies the following condition:You find the Ih and Ih/2.If the absolute of (Ih-Ih/2)<error the loop is complete.Otherwise you repeat the process with half the h,which means it calculates the absolute of (Ih/2-Ih/4) and so on and so on. while True: ###Ih part h = (b - a) / N y1 = np.linspace(a, b, N) Ez11 = (np.sqrt(ra ** 2 + R ** 2 - 2 * ra * R * np.cos(y1 - fa))) / ( (aa ** 2 - 2 * ra * R * np.cos(y1 - fa)) ** (3 / 2)) I11 = (h/3) * (Ez11[0] + 2*sum(Ez11[:N-2:2]) \ + 4*sum(Ez11[1:N-1:2]) + Ez11[N-1]) #####Ih/2 part h = (b-a)/(2*N) y2 = np.linspace(a, b, 2*N) Ez22 = (np.sqrt(ra ** 2 + R ** 2 - 2 * ra * R * np.cos(y2 - fa))) / ( (aa ** 2 - 2 * ra * R * np.cos(y2 - fa)) ** (3 / 2)) print(Ez22) I22 = (h/ 3) * (Ez22[0] + 2 * sum(Ez22[:N - 2:2]) \ + 4 * sum(Ez22[1:N - 1:2]) + Ez22[N - 1]) # error condition I1=Ih I2=Ih/2 if np.abs(I11 - I22) < error: break else: N = 2*N # h/2 print(np.abs(I11 - I22)) As far as I can tell,my approach should be correct.However the loop goes on and on,never to stop. My code is as follows: import numpy as np from scipy.integrate import simps import scipy.integrate as integrate import scipy.special as special # variables a = 0 b = np.pi * 2 N = 100 ra = 0.1 # ρα R = 0.05 fa = 35 * (np.pi / 180) # φα za = 0.4 Q = 10 ** (-6) k = 9 * 10 ** 9 aa = np.sqrt(ra ** 2 + R ** 2 + za ** 2) error = 0.55 * 10 ** (-8) h=(b-a)/N I1 = np.nan I11 = np.nan #Simpsons section ############ Ez #automated Simpson while True: ###Ih part y1 = np.linspace(a, b, N) Ez1 = (np.sqrt(ra ** 2 + R ** 2 - 2 * ra * R * np.cos(y1 - fa))) / ( (aa ** 2 - 2 * ra * R * np.cos(y1 - fa)) ** (3 / 2)) print(len(Ez1)) I1 = simps(Ez1, y1) #####Ih/2 part y2 = np.linspace(a, b, 2*N) Ez2 = (np.sqrt(ra ** 2 + R ** 2 - 2 * ra * R * np.cos(y2 - fa))) / ( (aa ** 2 - 2 * ra * R * np.cos(y2 - fa)) ** (3 / 2)) I2 = simps(Ez2, y2) # error condition I1=Ih I2=Ih/2 if np.abs(I1 - I2) < error: break else: N *= 2 # h/2 #custom-made Simpson N = 100 while True: ###Ih part h = (b - a) / N y1 = np.linspace(a, b, N) Ez11 = (np.sqrt(ra ** 2 + R ** 2 - 2 * ra * R * np.cos(y1 - fa))) / ( (aa ** 2 - 2 * ra * R * np.cos(y1 - fa)) ** (3 / 2)) I11 = (h/3) * (Ez11[0] + 2*sum(Ez11[:N-2:2]) \ + 4*sum(Ez11[1:N-1:2]) + Ez11[N-1]) #####Ih/2 part h = (b-a)/(2*N) y2 = np.linspace(a, b, 2*N) Ez22 = (np.sqrt(ra ** 2 + R ** 2 - 2 * ra * R * np.cos(y2 - fa))) / ( (aa ** 2 - 2 * ra * R * np.cos(y2 - fa)) ** (3 / 2)) print(Ez22) I22 = (h/ 3) * (Ez22[0] + 2 * sum(Ez22[:N - 2:2]) \ + 4 * sum(Ez22[1:N - 1:2]) + Ez22[N - 1]) # error condition I1=Ih I2=Ih/2 if np.abs(I11 - I22) < error: break else: N = 2*N # h/2 print(np.abs(I11 - I22)) print(I1) print(I11) Simpson's Rule is as follows: After a while it's stuck in this situation The 5.23 part is the absolute diff of those 2 which shouldnt be that high.
Python - Converting list of coordinates to latitude and longitude
I recently started learning programing and Python. Now I've been trying to convert a list of coordinates x,y to latitude and longitude. I searched and found a method in python in this post: How to convert from UTM to LatLng in python or Javascript But when I try to apply the function to a list of floats from a dataframe I get an error:" cannot convert the series to <class 'float'> ". What could I be doing wrong? My code: import math def utmToLatLng(zone, easting, northing, northernHemisphere=True): if not northernHemisphere: northing = 10000000 - northing a = 6378137 e = 0.081819191 e1sq = 0.006739497 k0 = 0.9996 arc = northing / k0 mu = arc / (a * (1 - math.pow(e, 2) / 4.0 - 3 * math.pow(e, 4) / 64.0 - 5 * math.pow(e, 6) / 256.0)) ei = (1 - math.pow((1 - e * e), (1 / 2.0))) / (1 + math.pow((1 - e * e), (1 / 2.0))) ca = 3 * ei / 2 - 27 * math.pow(ei, 3) / 32.0 cb = 21 * math.pow(ei, 2) / 16 - 55 * math.pow(ei, 4) / 32 cc = 151 * math.pow(ei, 3) / 96 cd = 1097 * math.pow(ei, 4) / 512 phi1 = mu + ca * math.sin(2 * mu) + cb * math.sin(4 * mu) + cc * math.sin(6 * mu) + cd * math.sin(8 * mu) n0 = a / math.pow((1 - math.pow((e * math.sin(phi1)), 2)), (1 / 2.0)) r0 = a * (1 - e * e) / math.pow((1 - math.pow((e * math.sin(phi1)), 2)), (3 / 2.0)) fact1 = n0 * math.tan(phi1) / r0 _a1 = 500000 - easting dd0 = _a1 / (n0 * k0) fact2 = dd0 * dd0 / 2 t0 = math.pow(math.tan(phi1), 2) Q0 = e1sq * math.pow(math.cos(phi1), 2) fact3 = (5 + 3 * t0 + 10 * Q0 - 4 * Q0 * Q0 - 9 * e1sq) * math.pow(dd0, 4) / 24 fact4 = (61 + 90 * t0 + 298 * Q0 + 45 * t0 * t0 - 252 * e1sq - 3 * Q0 * Q0) * math.pow(dd0, 6) / 720 lof1 = _a1 / (n0 * k0) lof2 = (1 + 2 * t0 + Q0) * math.pow(dd0, 3) / 6.0 lof3 = (5 - 2 * Q0 + 28 * t0 - 3 * math.pow(Q0, 2) + 8 * e1sq + 24 * math.pow(t0, 2)) * math.pow(dd0, 5) / 120 _a2 = (lof1 - lof2 + lof3) / math.cos(phi1) _a3 = _a2 * 180 / math.pi latitude = 180 * (phi1 - fact1 * (fact2 + fact3 + fact4)) / math.pi if not northernHemisphere: latitude = -latitude longitude = ((zone > 0) and (6 * zone - 183.0) or 3.0) - _a3 return (latitude, longitude) import pandas as pd df = pd.read_csv('Coord_rj.csv') x = df['x'] y = df['y'] for i in range(len(df)): lati,longi = utmToLatLng(23,x,y, False) What my data looks like: x y 529025.0 7422210.0 529114.0 7422343.0 545227.0 7435702.0 545582.0 7435741.0 The error: TypeError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_7368/1776418913.py in <module> 1 for i in range(len(df)): ----> 2 lati,longi = utmToLatLng(23,x,y, False) 3 ~\AppData\Local\Temp/ipykernel_7368/3107957551.py in utmToLatLng(zone, easting, northing, northernHemisphere) 20 cc = 151 * math.pow(ei, 3) / 96 21 cd = 1097 * math.pow(ei, 4) / 512 ---> 22 phi1 = mu + ca * math.sin(2 * mu) + cb * math.sin(4 * mu) + cc * math.sin(6 * mu) + cd * math.sin(8 * mu) 23 24 n0 = a / math.pow((1 - math.pow((e * math.sin(phi1)), 2)), (1 / 2.0)) ~\anaconda3\lib\site-packages\pandas\core\series.py in wrapper(self) 183 if len(self) == 1: 184 return converter(self.iloc[0]) --> 185 raise TypeError(f"cannot convert the series to {converter}") 186 187 wrapper.__name__ = f"__{converter.__name__}__" TypeError: cannot convert the series to <class 'float'>
When you're reading in your input file you're assigning all of the first column to a variable, and all of the second column to a variable: >>> import pandas as pd >>> df = pd.read_csv('Coord_rj.csv') >>> df x y 0 529025.0 7422210.0 1 529114.0 7422343.0 2 545227.0 7435702.0 3 545582.0 7435741.0 >>> df['x'] 0 529025.0 1 529114.0 2 545227.0 3 545582.0 Name: x, dtype: float64 >>> df['y'] 0 7422210.0 1 7422343.0 2 7435702.0 3 7435741.0 Name: y, dtype: float64 When you call your function you're passing the entire column to it for x and y, rather than just a row. Try this instead: for i in range(len(df)): lati,longi = utmToLatLng(23, x[i], y[i], False)
'IndexError: index 4 is out of bounds for axis 1 with size 4'
I'm doing this code but I have a problem in the line 40, with a Index Error. I don't know if there is a problem with the nr-1, inside the for. The code: import numpy Z = 1 R = 1 nr = 5 nz = 4 kn = 1 ks = 1 ke = 1 kw = 1 T = numpy.zeros((nr, nz), dtype=float) vetorq = 1 for a in range(1, 100, 1): for i in range(0, nz, 1): for j in range(0, nr, 1): an = (i + (1 / 2)) * (R ** 2)*nz*kn/ ((nr**2)* Z) ae = (i + 2) * Z*ke / nz aw = ((i+1)*kw * Z) / nz asul = (i + (1 / 2)) * (R ** 2)*nz*ks / (Z * (nr**2)) ap = an + ae + aw + asul aef = 0 if (i == 0 and j == 0): T[i, j] = ae * ((T[i, j + 1]) / ap) + asul * ( (T[i + 1, j]) / ap) + 1846.35 * Z * (R ** 2) * (i + 1/2) / ((nr ** 2) * nz * ap) + aef / ap elif(i == 0 and j != 0 and j != nr - 1): T[i, j] = ae * ((T[i, j + 1]) / ap) + aw * ((T[i, j - 1]) / ap) + asul * ( (T[i + 1, j]) / ap) + 1846.35 * Z * (R ** 2) * (i + 1/2) / ((nr ** 2) * nz * ap) + aef / ap elif(i == 0 and j == nr - 1): aef = (i + 2) * R * Z * vetorq / (nr * nz) T[i, j] = aw * ((T[i, j - 1]) / ap) + asul * ( (T[i + 1, j]) / ap) + 1846.35 * Z * (R ** 2) * (i + 1/2) / ((nr ** 2) * nz * ap) + aef / ap elif(i != 0 and i != nz - 1 and j == nr - 1): aef = (i + 2) * R * Z * vetorq / (nr * nz) T[i, j] = aw * ((T[i, j - 1]) / ap) + an * ((T[i - 1, j]) / ap) + asul * ( (T[i + 1, j]) / ap) + 1846.35 * Z * (R ** 2) * (i + 1/2) / ((nr ** 2) * nz * ap) + aef / ap elif(i == nz - 1 and j == nr - 1): aef = (i + 2) * R * Z * vetorq / (nr * nz) T[i, j] = aw * ((T[i, j - 1]) / ap) + an * ((T[i - 1, j]) / ap) + 1846.35 * Z * (R ** 2) * (i + 1/2) /((nr ** 2) * nz * ap) + aef / ap elif(i == nz - 1 and j != 0 and j != nr - 1): T[i, j] = ae * ((T[i, j + 1]) / ap) + aw * ((T[i, j - 1]) / ap) + an * ((T[i - 1, j]) / ap) + 1846.35 * Z * (R ** 2) * (i + 1/2) / ((nr ** 2) * nz * ap) + aef / ap elif(i == nz - 1 and j == 0): T[i, j] = ae * ((T[i, j + 1]) / ap) + an * ((T[i - 1, j]) / ap) + 1846.35 * Z * (R ** 2) * (i + 1/2) / ((nr ** 2) * nz * ap) + aef / ap elif(i != 0 and i != nz - 1 and j == 0): T[i, j] = ae * ((T[i, j + 1]) / ap) + an * ((T[i - 1, j]) / ap) + asul * ( (T[i + 1, j]) / ap) + 1846.35 * Z * (R ** 2) * (i + 1/2) / ((nr ** 2) * nz * ap) + aef / ap elif(i != 0 and i != nz - 1 and j != 0 and j!= nr - 1): T[i, j] = ae * ((T[i, j + 1]) / ap) + aw * ((T[i, j - 1]) / ap) + an * ((T[i - 1, j]) / ap) + asul * ( (T[i + 1, j]) / ap) + 1846.35 * Z * (R ** 2) * (i - 1/2) / ((nr ** 2) * nz * ap) + aef / ap print(T)
The problem with your code is you have interchanged nr(rows) and nz(columns) with the iterators i and j; Your two loops must be as shown below and change all if, elif conditions on i with (nr-1) and on j with (nz-1). It works fine. for i in range(0, nr, 1): for j in range(0, nz, 1):
Python: My python plot is reflecting across y = 0.5 line
Why would my Python plot reflect across the y = 0.5 line? The same plot in Mathematica doesn't. I checked the equations 5-10 times and I don't see a difference. If I put a -1 in front of the python plot it will flip over and drop down 1 unit to y = -0.5. Additionally, the definitions for alphag and betag are correct. import numpy as np import pylab r1 = 1 # AU Earth r2 = 1.524 # AU Mars deltanu = 75 * np.pi / 180 # angle in radians mu = 38.86984154054163 c = np.sqrt(r1 ** 2 + r2 ** 2 - 2 * r1 * r2 * np.cos(deltanu)) s = (r1 + r2 + c) / 2 am = s / 2 def g(a): alphag = 2* np.pi - 2 * np.arcsin(np.sqrt(s / (2 * a))) betag = -2 * np.arcsin(np.sqrt((s - c) / (2 * a))) return (np.sqrt(a ** 3 / mu) * (alphag - betag - (np.sin(alphag) - np.sin(betag))) - dt) a = np.linspace(am, 2, 500000) dt = np.linspace(0, 2, 500000) fig = pylab.figure() ax = fig.add_subplot(111) ax.plot(a, g(a), color = 'r') pylab.xlim((0.9, 2)) pylab.ylim((0, 2)) pylab.show() Python: Edit 2: There are actually 2 plots I am plotting and thanks to the comments, I noticed that there is something even stranger occurring. The two plots I am plotting are: dt = np.sqrt(a ** 3 / mu) * (alpha - beta - (sin(alpha) - sin(beta))) where alpha is 2 * np.arcsin(np.sqrt(s / (2 * a))) or 2 * np.pi - 2 * np.arcsin(np.sqrt(s / (2 * a))) and beta is 2 * np.arcsin(np.sqrt((s - c) / (2 * a))) or the negative of the first. In[13]:= r1 = 1; r2 = 1.524; dnu = 75 Degree; mu = 38.86984154054163; In[17]:= c = Sqrt[r1^2 + r2^2 - 2*r1*r2*Cos[dnu]] Out[17]= 1.59176 In[18]:= s = (r1 + r2 + c)/2 Out[18]= 2.05788 In[19]:= alp = 2 \[Pi] - 2*ArcSin[Sqrt[s/(2*a)]]; bet = -2*ArcSin[Sqrt[(s - c)/(2*a)]]; In[22]:= Plot[ Sqrt[a^3/mu]*(alp - bet - (Sin[alp] - Sin[bet])), {a, 0, 2}, PlotRange -> {{.8, 2}, {0, 2}}] This produces: and alp2 = 2*ArcSin[Sqrt[s/(2*a)]]; bet2 = 2*ArcSin[Sqrt[(s - c)/(2*a)]]; Plot[Sqrt[a^3/mu]*(alp2 - bet2 - (Sin[alp2] - Sin[bet2])), {a, 0, 2}, PlotRange -> {{.8, 2}, {0, 2}}] So the Python code matches the first Mathematica code but the plots the second picture and my python code for the the second Mathematica codes produces the flipped image for the first Mathematica picture.
I think you simply have to remove the -dt from the Python code: import numpy as np import matplotlib.pyplot as plt r1 = 1 # AU Earth r2 = 1.524 # AU Mars deltanu = 75 * np.pi / 180 # angle in radians mu = 38.86984154054163 c = np.sqrt(r1 ** 2 + r2 ** 2 - 2 * r1 * r2 * np.cos(deltanu)) s = (r1 + r2 + c) / 2 am = s / 2 def g(a): alphag = 2 * np.pi - 2 * np.arcsin(np.sqrt(s / (2 * a))) betag = -2 * np.arcsin(np.sqrt((s - c) / (2 * a))) return (np.sqrt(a ** 3 / mu) * (alphag - betag - (np.sin(alphag) - np.sin(betag)))) def g2(a): alphag = 2 * np.arcsin(np.sqrt(s / (2 * a))) betag = 2 * np.arcsin(np.sqrt((s - c) / (2 * a))) return (np.sqrt(a ** 3 / mu) * (alphag - betag - (np.sin(alphag) - np.sin(betag)))) a = np.linspace(am, 2, 500000) dt = np.linspace(0, 2, 500000) fig, ax = plt.subplots(ncols=2) ax[0].plot(a, g(a), color = 'r') ax[1].plot(a, g2(a), color = 'r') ax[0].set_xlim((0.9, 2)) ax[0].set_ylim((0, 2)) ax[1].set_xlim((0.9, 2)) ax[1].set_ylim((0, 2)) plt.show() yields
Python: Filling in a gap between two plots
How can I connect two plots at a discontinues point? I have an equation for the point of discontinuity. import numpy as np import pylab r1 = 1 # AU Earth r2 = 1.524 # AU Mars deltanu = 75 * np.pi / 180 # angle in radians mu = 38.86984154054163 c = np.sqrt(r1 ** 2 + r2 ** 2 - 2 * r1 * r2 * np.cos(deltanu)) s = (r1 + r2 + c) / 2 am = s / 2 def f(a): alpha = 2 * np.arcsin(np.sqrt(s / (2 * a))) beta = 2 * np.arcsin(np.sqrt((s - c) / (2 * a))) return (np.sqrt(a **3 / mu) * (alpha - beta - (np.sin(alpha) - np.sin(beta)))) def g(a): alphag = 2* np.pi - 2 * np.arcsin(np.sqrt(s / (2 * a))) betag = -2 * np.arcsin(np.sqrt((s - c) / (2 * a))) return (np.sqrt(a ** 3 / mu) * (alphag - betag - (np.sin(alphag) - np.sin(betag)))) a = np.linspace(am, 2, 500000) fig = pylab.figure() ax = fig.add_subplot(111) ax.plot(a, f(a), color = '#000000') ax.plot(a, g(a), color = '#000000') pylab.xlim((0.9, 2)) pylab.ylim((0, 2)) pylab.show() The equation that reflects the point is: dt = np.sqrt(s ** 3 / 8) * (np.pi - betam + np.sin(betam)) where betam = 2 * np.arcsin(np.sqrt(1 - c / s)) so dt = 0.5 at a = s / 2. However, the gap between the plots looks bigger than a point. I added: ax.plot([am, am], [.505, .55], color = '#000000') which fills in the gap but it feels out of place.
It seems as though perhaps you should only be using one value for betag: import numpy as np import matplotlib.pyplot as plt r1 = 1 # AU Earth r2 = 1.524 # AU Mars deltanu = 75 * np.pi / 180 # angle in radians mu = 38.86984154054163 c = np.sqrt(r1 ** 2 + r2 ** 2 - 2 * r1 * r2 * np.cos(deltanu)) s = (r1 + r2 + c) / 2 am = s / 2 def g(a, alphag, betag): return (np.sqrt(a ** 3 / mu) * (alphag - betag - (np.sin(alphag) - np.sin(betag)))) a = np.linspace(am, 2, 500000) fig, ax = plt.subplots() alphag = 2 * np.pi - 2 * np.arcsin(np.sqrt(s / (2 * a))) betag = 2 * np.arcsin(np.sqrt((s - c) / (2 * a))) ax.plot(a, g(a, alphag, betag), color = 'r') alphag = 2 * np.arcsin(np.sqrt(s / (2 * a))) ax.plot(a, g(a, alphag, betag), color = 'r') plt.show() yields I really don't know what's going on here; I found this serendipitously.
ax.plot([am,am],[f(am),g(am)],color== '#000000')