I am trying to write a numerical integral calculator as my first Python project. The method takes a starting x value, a delta x value, and a set of y values and returns a lower and an upper bound. I am expecting the result of the numerical integration to converge as dx gets smaller, but it is getting larger.
I am trying to integrate an exponential from 0 to 1 and get the result to converge to 1/3 as dx gets smaller. Currently a dx of 0.1 gives me bounds of (0.14000000000000004, 0.17200000000000004). A dx of 0.01 has bounds of (0.30894500000000014, 0.313747).
Here is my code:
class Linear:
"""Creates a linear function from 2 points"""
def __init__(self, x0, y0, x1, y1):
self.__x0 = x0
self.__y0 = y0
self.__x1 = x1
self.__y1 = y1
self.__a = ((y1 - y0) / (x1 - x0))
self.__b = y0 - (self.__a * x0)
def fun(self, x):
return self.__a * x + self.__b
def integrate(x0, dx, data):
if len(data) < 3:
raise ValueError("data passed to integrate doesn't have enough data")
else:
i, lb, ub = 2, 0, 0
while i < len(data):
y0, y1, y2 = data[i - 2], data[i - 1], data[i]
lin = Linear(x0, y0, x0 + dx + dx, y2)
lin_delta = lin.fun(x0 + dx)
if y1 < lin_delta:
if y0 < y1:
lb += (y0 * dx)
ub += ((((y1 - y0) * dx) / 2) + (y0 * dx))
else:
lb += (y1 * dx)
ub += ((((y0 - y1) * dx) / 2) + (y1 * dx))
else:
if y0 < y1:
ub += (y1 * dx)
lb += ((((y1 - y0) * dx) / 2) + (y0 * dx))
else:
ub += (y0 * dx)
lb += ((((y0 - y1) * dx) / 2) + (y1 * dx))
i += 1
x0 += dx
return lb, ub
if __name__ == '__main__':
j = 0
d = []
dxj = 0.1
while j < (1/dxj):
d += [(j * dxj) * (j * dxj)]
j += 1
print(d)
print(integrate(0, dxj, d))
Also, what is the best way to avoid name collisions with counters like i?
Related
I want to generate Chen's hyperchaotic sequence. Formulas are given as:Chen's hyperchaotic sequence equations
Code I have written is attached.
import math
a = 36
b = 3
c = 28
d = 16
k = 0.2
def chen(x0, y0, z0, q0):
xdot = a * (y0 - x0)
ydot = (-x0 * z0) + (d * x0) + (c * y0) - q0
zdot = (x0 * y0) - (b * z0)
qdot = x0 + k
return xdot, ydot, zdot, qdot
def chaotic_seq(x0, y0, z0, q0, length):
for i in range(length):
xdot, ydot, zdot, qdot = chen(x0, y0, z0, q0)
if math.isnan(xdot) or math.isnan(ydot) or math.isnan(zdot) or math.isnan(qdot):
print(i)
x0 = xdot
y0 = ydot
z0 = zdot
q0 = qdot
if __name__ == '__main__':
x0 = 0.3
y0 = -0.4
z0 = 1.2
q0 = 1
length = 2048
chaotic_seq(x0=x0, y0=y0, z0=z0, q0=q0, length=length)
Problem I am facing is, after 'i=11' all the values (xdot, ydot, zdot, qdot) are NaN.
I think you have a couple problems.
One is that your functions quickly seem to run into overflow errors with the Python float, which returns nan values, so you'll need a data type that supports higher precision values than what the default float that the Python built-in data type provides. So you might look at using the numpy library's float128 data type (shown below) — or investigate using the decimal module (not shown).
Secondly, the dot notation represents the rate of change in the input variables. For example, xdot is shorthand notation for the differential expression dx/dt.
You can add a time increment variable (e.g., t) which changes the values of x0, y0, z0, and q0 in small increments, which simulates their respective differentials.
Here's a modified version of your script that runs for 2048 iterations:
#!/usr/bin/env python
import sys
import numpy as np
a = np.float128(36)
b = np.float128(3)
c = np.float128(28)
d = np.float128(16)
k = np.float128(0.2)
t = np.float128(0.001)
def chen(x0, y0, z0, q0):
xdot = a * (y0 - x0)
ydot = (-x0 * z0) + (d * x0) + (c * y0) - q0
zdot = (x0 * y0) - (b * z0)
qdot = q0 + k
return xdot, ydot, zdot, qdot
def chaotic_seq(x0, y0, z0, q0, length):
for i in range(length):
xdot, ydot, zdot, qdot = chen(x0, y0, z0, q0)
if np.isnan(xdot) or np.isnan(ydot) or np.isnan(zdot) or np.isnan(qdot):
raise OverflowError("Overflow in dot variable calculation")
x0 += t * xdot
y0 += t * ydot
z0 += t * zdot
q0 += t * qdot
sys.stdout.write('after: [{}] {}\t{}\t{}\t{}\n'.format(i, x0, y0, z0, q0))
if __name__ == '__main__':
x0 = np.float128(0.3)
y0 = np.float128(-0.4)
z0 = np.float128(1.2)
q0 = np.float128(1)
length = 2048
chaotic_seq(x0=x0, y0=y0, z0=z0, q0=q0, length=length)
Your code comes quite far from achieving what you wish: you're going to have to solve that differential equation at some point, which you aren't doing anywhere in the above sample. This explains why your values quickly diverge to infinity, then start becoming NaNs.
Using scipy to solve the differential equation we get the code below, which gives seemingly satisfactory results:
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
a = 36
b = 3
c = 12
d = 7
k = 0.2
def chen(_, y):
x0, y0, z0, q0 = y
xdot = a * (y0 - x0)
ydot = (-x0 * z0) + (d * x0) + (c * y0) - q0
zdot = (x0 * y0) - (b * z0)
qdot = x0 + k
return xdot, ydot, zdot, qdot
def chaotic_seq(x0, y0, z0, q0, length):
return solve_ivp(chen, [0, length], [x0, y0, z0, q0])
x0 = 0.3
y0 = -0.4
z0 = 1.2
q0 = 1
length = 50
sol = chaotic_seq(x0=x0, y0=y0, z0=z0, q0=q0, length=length).y
# plot x,y
plt.plot(sol[0], sol[1])
I am implementing a bilinear interpolation as in How to perform bilinear interpolation in Python
I have a sorted list of points that are the vertexes of my regular grid.
[[x1,y1,z1],[x2,y2,z2],[x3,y3,z3],[x4,y4,z4],[x5,y5,z5],...]
I want to interpolate linearly on the point (x,y). I have written the following code
def f(x, y, points):
for i in range(len(points)-1, -1, -1):
if (x>points[i][0])and(y>points[i][1]):
break
try:
pp = [points[i], points[i+1]]
except IndexError:
pp = [points[i], points[i-1]]
for j in range(len(points)):
if (x<points[j][0])and(y<points[j][1]):
break
pp.append(points[j-1])
pp.append(points[j])
(x1, y1, q11), (_x1, y2, q12), (x2, _y1, q21), (_x2, _y2, q22) = pp
return (q11 * (x2 - x) * (y2 - y) +
q21 * (x - x1) * (y2 - y) +
q12 * (x2 - x) * (y - y1) +
q22 * (x - x1) * (y - y1)) / ((x2 - x1) * (y2 - y1))
but this code doesn't work on the boundaries. I would think this is common problem in interpolation, so I was wondering how I should select the smallest rectangle of points around (x,y) from my regular grid.
Your grid is regular, so you don't need to traverse all points to determine cell indexes. Just divide coordinates by cell size and round result to smaller integer. 1D example: if first point has coordinate 1 and cell size is 2, point 6 lies at int (6-1)/2 = 2-nd interval
Restrict result index to ensure that it is in grid limits - so points outside grid will use border cells
i = int((x - points[i][0]) / xsize) #not sure what is the best way in Python
if (i < 0):
i = 0
if (i >= XCount):
i = XCount - 1
// same for j and y-coordinate
Following the suggestions in the comments I have written the following code:
def f(x, y, points):
points = sorted(points)
xunique = np.unique([point[0] for point in points])
yunique = np.unique([point[1] for point in points])
xmax = np.max(xunique)
ymax = np.max(yunique)
deltax = xunique[1] - xunique[0]
deltay = yunique[1] - yunique[0]
x0 = xunique[0]
y0 = yunique[0]
ni = len(xunique)
nj = len(yunique)
i1 = int(np.floor((x-x0)/deltax))
if i1 == ni:
i1 = i1 - 1
i2 = int(np.ceil((x-x0)/deltax))
if i2 == ni:
i2 = i2 - 1
j1 = int(np.floor((y-y0)/deltay))
if j1 == nj:
j1 = j1 - 1
j2 = int(np.ceil((y-y0)/deltay))
if j2 == ni:
j2 = j2 - 1
pp=[]
if (i1==i2):
if i1>0:
i1=i1-1
else:
i2=i2+1
if (j1==j2):
if j1>0:
j1=j1-1
else:
j2=j2+1
pp=[points[i1 * nj + j1], points[i1 * nj + j2],
points[i2 * nj + j1], points[i2 * nj + j2]]
(x1, y1, q11), (_x1, y2, q12), (x2, _y1, q21), (_x2, _y2, q22) = pp
return (q11 * (x2 - x) * (y2 - y) +
q21 * (x - x1) * (y2 - y) +
q12 * (x2 - x) * (y - y1) +
q22 * (x - x1) * (y - y1)) / ((x2 - x1) * (y2 - y1))
Right now, I am working on something (in Python) to create an ellipse and display it on the screen (in the console). I have the ellipse creation already, but rotating the ellipse gives me problems.
Ellipse Method:
def ellipse(yc, xc, b, a, rotation=0):
yc_min_b = yc - b
# divide b to account for spacing in console
b = int(round(b / 2 + 0.01)) - 1
yc = yc_min_b + b
points = []
a2 = a*a
b2 = b*b
fa2 = 4 * a2
fb2 = 4 * b2
x = 0
y = b
sigma = 2 * b2 + a2 * (1 - 2 * b)
while b2 * x <= a2 * y:
points.append((xc + x, yc + y))
points.append((xc - x, yc + y))
points.append((xc + x, yc - y))
points.append((xc - x, yc - y))
if sigma >= 0:
sigma += fa2 * (1 - y)
y -= 1
sigma += b2 * ((4 * x) + 6)
x += 1 # INCREMENT
x = a
y = 0
sigma = 2 * a2 + b2 * (1 - 2 * a)
while a2 * y <= b2 * x:
points.append((xc + x, yc + y))
points.append((xc - x, yc + y))
points.append((xc + x, yc - y))
points.append((xc - x, yc - y))
if sigma >= 0:
sigma += fb2 * (1 - x)
x -= 1
sigma += a2 * ((4 * y) + 6)
y += 1 # INCREMENT
# now rotate points
sin = math.sin(rotation)
cos = math.cos(rotation)
rotated = []
for point in points:
x = point[0]
y = point[1]
'''
px -= xc
py -= yc
xnew = px * c - py * s
ynew = px * s + py * c
px = xnew + xc
py = ynew + yc
'''
#XRot := Round(XCenter + (X - XCenter) * CAngle - (Y - YCenter) * SAngle);
#YRot := Round(YCenter + (X - XCenter) * SAngle + (Y - YCenter) * CAngle);
x = round(xc + (x + xc) * cos - (y - yc) * sin)
y = round(yc + (x - xc) * sin + (y - yc) * cos)
rotated.append((int(x), int(y)))
points = rotated
print points
ell_matr = []
# set up empty matrix
maxx = 0
maxy = 0
for point in points:
y = point[1]
x = point[0]
if y > maxy:
maxy = y
if x > maxx:
maxx = x
for i in range(maxy + 1):
ell_matr.append([])
for j in range(maxx + 1):
ell_matr[i].append(' ')
for point in points:
y = point[1]
x = point[0]
ell_matr[y][x] = fill
return ell_matr
I would ignore the matrix part, as it is translating the points into a matrix to display on screen.
Here is the output of an ellipse without rotation.
And when I add a 45 degree rotation (converted to radians)
Is there a better way to rotate the points?
I'm trying traverse all the cells that a line goes through. I've found the Fast Voxel Traversal Algorithm that seems to fit my needs, but I'm currently finding to be inaccurate. Below is a graph with a red line and points as voxel coordinates that the algorithm gives. As you can see it is almost correct except for the (4, 7) point, as it should be (5,6). I'm not sure if i'm implementing the algorithm correctly either so I've included it in Python. So i guess my question is my implementation correct or is there a better algo to this?
Thanks
def getVoxelTraversalPts(strPt, endPt, geom):
Max_Delta = 1000000.0
#origin
x0 = geom[0]
y0 = geom[3]
(sX, sY) = (strPt[0], strPt[1])
(eX, eY) = (endPt[0], endPt[1])
dx = geom[1]
dy = geom[5]
sXIndex = ((sX - x0) / dx)
sYIndex = ((sY - y0) / dy)
eXIndex = ((eX - sXIndex) / dx) + sXIndex
eYIndex = ((eY - sYIndex) / dy) + sYIndex
deltaX = float(eXIndex - sXIndex)
deltaXSign = 1 if deltaX > 0 else -1 if deltaX < 0 else 0
stepX = deltaXSign
tDeltaX = min((deltaXSign / deltaX), Max_Delta) if deltaXSign != 0 else Max_Delta
maxX = tDeltaX * (1 - sXIndex + int(sXIndex)) if deltaXSign > 0 else tDeltaX * (sXIndex - int(sXIndex))
deltaY = float(eYIndex - sYIndex)
deltaYSign = 1 if deltaY > 0 else -1 if deltaY < 0 else 0
stepY = deltaYSign
tDeltaY = min(deltaYSign / deltaY, Max_Delta) if deltaYSign != 0 else Max_Delta
maxY = tDeltaY * (1 - sYIndex + int(sYIndex)) if deltaYSign > 0 else tDeltaY * (sYIndex - int(sYIndex))
x = sXIndex
y = sYIndex
ptsIndexes = []
pt = [round(x), round(y)]
ptsIndexes.append(pt)
prevPt = pt
while True:
if maxX < maxY:
maxX += tDeltaX
x += deltaXSign
else:
maxY += tDeltaY
y += deltaYSign
pt = [round(x), round(y)]
if pt != prevPt:
#print pt
ptsIndexes.append(pt)
prevPt = pt
if maxX > 1 and maxY > 1:
break
return (ptsIndexes)
The voxels that you are walking start at 0.0, i.e. the first voxel spans space from 0.0 to 1.0, a not from -0.5 to 0.5 as you seem to be assuming. In other words, they are the ones marked with dashed line, and not the solid one.
If you want voxels to be your way, you will have to fix initial maxX and maxY calculations.
Ain't nobody got time to read the paper you posted and figure out if you've implemented it correctly.
Here's a question, though. Is the algorithm you've used (a) actually meant to determine all the cells that a line passes through or (b) form a decent voxel approximation of a straight line between two points?
I'm more familiar with Bresenham's line algorithm which performs (b). Here's a picture of it in action:
Note that the choice of cells is "aesthetic", but omits certain cells the line passes through. Including these would make the line "uglier".
I suspect a similar thing is going on with your voxel line algorithm. However, looking at your data and the Bresenham image suggests a simple solution. Walk along the line of discovered cells, but, whenever you have to make a diagonal step, consider the two intermediate cells. You can then use a line-rectangle intersection algorithm (see here) to determine which of the candidate cells should have, but wasn't, included.
I guess just to be complete, I decided to use a different algo. the one referenced here dtb's answer on another question.
here's the implementation
def getIntersectPts(strPt, endPt, geom=[0,1,0,0,0,1]):
'''
Find intersections pts for every half cell size
** cell size has only been tested with 1
Returns cell coordinates that the line passes through
'''
x0 = geom[0]
y0 = geom[3]
(sX, sY) = (strPt[0], strPt[1])
(eX, eY) = (endPt[0], endPt[1])
xSpace = geom[1]
ySpace = geom[5]
sXIndex = ((sX - x0) / xSpace)
sYIndex = ((sY - y0) / ySpace)
eXIndex = ((eX - sXIndex) / xSpace) + sXIndex
eYIndex = ((eY - sYIndex) / ySpace) + sYIndex
dx = (eXIndex - sXIndex)
dy = (eYIndex - sYIndex)
xHeading = 1.0 if dx > 0 else -1.0 if dx < 0 else 0.0
yHeading = 1.0 if dy > 0 else -1.0 if dy < 0 else 0.0
xOffset = (1 - (math.modf(sXIndex)[0]))
yOffset = (1 - (math.modf(sYIndex)[0]))
ptsIndexes = []
x = sXIndex
y = sYIndex
pt = (x, y) #1st pt
if dx != 0:
m = (float(dy) / float(dx))
b = float(sY - sX * m )
dx = abs(int(dx))
dy = abs(int(dy))
if dx == 0:
for h in range(0, dy + 1):
pt = (x, y + (yHeading *h))
ptsIndexes.append(pt)
return ptsIndexes
#print("m {}, dx {}, dy {}, b {}, xdir {}, ydir {}".format(m, dx, dy, b, xHeading, yHeading))
#print("x {}, y {}, {} {}".format(sXIndex, sYIndex, eXIndex, eYIndex))
#snap to half a cell size so we can find intersections on cell boundaries
sXIdxSp = round(2.0 * sXIndex) / 2.0
sYIdxSp = round(2.0 * sYIndex) / 2.0
eXIdxSp = round(2.0 * eXIndex) / 2.0
eYIdxSp = round(2.0 * eYIndex) / 2.0
# ptsIndexes.append(pt)
prevPt = False
#advance half grid size
for w in range(0, dx * 4):
x = xHeading * (w / 2.0) + sXIdxSp
y = (x * m + b)
if xHeading < 0:
if x < eXIdxSp:
break
else:
if x > eXIdxSp:
break
pt = (round(x), round(y)) #snapToGrid
# print(w, x, y)
if prevPt != pt:
ptsIndexes.append(pt)
prevPt = pt
#advance half grid size
for h in range(0, dy * 4):
y = yHeading * (h / 2.0) + sYIdxSp
x = ((y - b) / m)
if yHeading < 0:
if y < eYIdxSp:
break
else:
if y > eYIdxSp:
break
pt = (round(x), round(y)) # snapToGrid
# print(h, x, y)
if prevPt != pt:
ptsIndexes.append(pt)
prevPt = pt
return set(ptsIndexes) #elminate duplicates
I have the following two sets of position each correspond to the start and end position:
line T: t1-t2 (t1 = start_pos, t2 = end_pos)
line S: s1-s2 (s1 = start_pos, t2 = end_pos)
I want to write the algorithm in Python to check if T intersect with S.
Example 1:
t1-t2=55-122 and s1-s2=58-97
s1------------s2
t1-----------------t2
This should return True
Example 2:
t1-t2=4-66 / t1-t2=143-166 and s1-s2=80-141
s1----s2
t1--t2 t1---t2
Both instances of T should return False
But why this code failed:
def is_overlap(pos, dompos):
"""docstring for is_overlap"""
t1,t2 = [int(x) for x in pos.split("-")]
s1,s2 = [int(x) for x in dompos.split("-")]
# Here we define the instance of overlapness
if (t1 >= s1 and t2 >= s2) or \
(t1 >= s1 and t2 <= s2) or \
(t1 <= s1 and t2 >= s2) or \
(t1 <= s1 and t2 <= s2):
return True
else:
return False
which output this:
In [2]: is_overlap('55-122', '58-97')
Out[2]: True
In [3]: is_overlap('4-66', '80-141')
Out[3]: True
In [4]: is_overlap('143-166', '80-141')
Out[4]: True
What's the right way to do it?
Consider a span [a, b] and another span [x, y]. They either overlap or they are separate.
If they are separate, one of two things must be true:
[a, b] is to the left of [x, y], or
[x, y] is to the left of [a, b].
If [a, b] is to the left of [x, y], we have b < x.
If [x, y] is to the left of [a, b], we have y < a.
If neither of these is true, the spans cannot be separate. They must overlap.
This logic is implemented in the following function.
def are_separate(r, s): # r and s are ordered pairs
(a, b) = r
(x, y) = s
if b < x or y < a:
return True
else:
return False
More concisely:
def are_separate(r, s):
(a, b) = r
(x, y) = s
return b < x or y < a
Even more concisely:
def are_separate(r, s):
return r[1] < s[0] or s[1] < r[0]
If you want the contrary function, are_overlapping, just negate the expression:
def are_overlapping(r, s):
return not(r[1] < s[0] or s[1] < r[0])
Which is logically equivalent to:
def are_overlapping(r, s):
return r[1] >= s[0] and s[1] >= r[0]
Your conditions are wrong; check them again. For instance, the first condition implies that (t_1, t_2) = (100, 200) and (s_1, s_2) = (50, 60) to be a valid set of overlapping lines. But clearly, they aren't.
Something else you might want to consider is if the user inputs the coordinates in backwards. What if he puts in something like '80-30'?
For those who want two lines in two dimensions, #michael's answer is not enough. The following code is based on the equation found in the Wikipedia page listed just above the code as well as a little Pythagoras to check the intersection lies between the appropriate points. https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection
x1, y1, x2, y2 = 200, 200, 300, 300
x3, y3, x4, y4 = 200, 150, 300, 350
px = ((x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4)) / \
((x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4))
py = ((x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4)) / \
((x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4))
if ((x1 - px) ** 2 + (y1 - py) ** 2) ** 0.5 + ((x2 - px) ** 2 + (y2 - py) ** 2) ** 0.5 == \
((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5 and \
((x3 - px) ** 2 + (y3 - py) ** 2) ** 0.5 + ((x4 - px) ** 2 + (y4 - py) ** 2) ** 0.5 == \
((x3 - x4) ** 2 + (y3 - y4) ** 2) ** 0.5:
print("Overlap at point: (%s, %s)" % (px, py))
else:
print("No overlap.")