I am trying to plot the streamlines. The problem I have is my coordinates are polar. Even when I try to convert my data to cartesian, the rows are not equal. This is not even necessary for quiver. So, is there really not a workaround to have some sort of streamlines when the "x rows" are not equal.
So basically I have X and Y which define my domain, and U,V the associated velocity field.
When calling
plt.streamplot(X,Y,U,V)
I get the error that "x rows must be equal", which I strongly think means that that each row in X must be the same, which is not the case. My domain is skewed with a certain angle so rows in X nor Y will never be equal. How do I cope with this.
The sizes of X,Y,U,V are all equal and quadratic with shape of N x N
Note: if calling the quiver function, it works perfectly fine.
Related
I am trying to calculate the wind gradient given u-wind and v-wind. The u and v values have a 3d-array with the following shape:
u(122,9,9) such that u(time,latitude,longitude). The same applies for v.
I have also calculated the dx and dy values (in 2-d array for both lat and lon direction)
The sample of my code is as below at time 0 for example:
dudx = np.gradient(u[0,0,:], dx[0,0], edge_order=2)
dvdy = np.gradient(v[0,:,0], dy[0,0], edge_order=2)
I can then sum dudx and dvdy to get the gradient. I have a data that has already calculated the divergence, and upon comparing my calculation with the divergence data, i expected the values to be the same, but they're not. I can't seem to figure out where i went wrong besides using the np.gradient function incorrectly.
I would like to know if my methods above to calculate the gradient of u and v winds are correct.
Cheers.
Edit
The full code i am using to calculate the wind gradient is as below:
dqu_dx = np.zeros((122,9,9))
dqv_dy = np.zeros((122,9,9))
for i in range(122):
for j in range(9):
for k in range(9):
dqu_dx[i,j,:] = np.gradient(dqu_18hr[i,j,:], dx[0,k], edge_order=2)
dqv_dy[i,:,k] = np.gradient(dqv_18hr[i,:,k], dy[j,0], edge_order=2)
Unfortunately I can't comment on your question to ask for explanations because I don't have enough reputation, so I am forced to make some assumptions. Feel free to correct me if I am wrong.
I will assume that dqu_18hr and dqv_18hr are arrays storing the value of two different functions, u(t, y, x) and v(t, y, x). If I understand correctly you want to calculate du/dx and dv/dy.
I don't know what are the dx and dy values that you store in the arrays, also because you define them as 2D-arrays but use them as 1D-arrays. I will assume that dx and dy are coordinates of the points at which you computed u and v, and that the grid they produce is regular.
A first problem with your code is that you are passing a single scalar number as the second argument of np.gradient. When this is done, numpy assumes that this is the distance between points. However, this distance changes at every iteration. I can think of a quite convoluted case for which the definition of dx is such that this gives the correct result, but generally this is a mistake.
Another problem with the code is that it doesn't take advantage of numpy vectorization, using explicitly three for loops. This is extremely inefficient computationally.
I would suggest you the following code:
x = dx[0, :] # or whatever is the correct definition
y = dy[:, 0] # not enough info in the post to understand it
a = np.gradient(dqu_18hr, x, axis=2, edge_order=2)
b = np.gradient(dqv_18hr, y, axis=1, edge_order=2)
Please also notice that in your code x is associated to the axis 2 and y to the axis 1, which is absolutely legit but unusual so you might want to check if that's a mistake.
I have the following curve as two arrays, of x and y positions.
Imagine if you were to draw vertical lines going through each point, and add points on the curve wherever these lines intersect the curve. This is what I want.
I tried using np.interp(x, x, y), but I ended up with the following mess:
How can I do this? Is it possible with np.interp?
This might be something that should be asked in a different question, but I would also like there to be points added where the curve crosses over itself.
According to the docs the array of X values should be sorted (or periodic), otherwise "the result is nonsense". You can try to split your curve into sections, and then interpolate each part on the others. You can find the correct splitting places by looking at where np.diff(x) changes sign.
I'm trying to simulate Conway's Game of Life in python(here is some of the code), and now I need to handle the ouput. Right now, I'm just plotting points in matplotlib but I want something like what this guy did(That script shows error in my PC but it generates the images anyway). I understand that the code I am looking for is:
plt.imshow(A, cmap='bone', interpolation='nearest')
plt.axis('off')
and that A is a numpy array alike a matrix with just True and False as entries.
By the way, I've already realized that instead of True and False I can put 1's and 0's.
I have the data of living cells as a set of points ([(x1,y1),(x2,y2),....,(xn,yn)]) of the plane(coordinates all integers). As you can see, my script is finite(it uses a for loop until 30), so I preset the plots' axis before the loop...for example, the minimum x coordinate of the plots is the minimum coordinate of the initial points minus 30, assuring then that all the points are visible in the last image.
To represent each configuration, I had the idea to do:
SuperArray=np.zeros(maxx+30,maxy+30)
for (i,j) in livecells:
SuperArray[i,j]=1
But that idea won't work, because the indices of SuperArray are all positives, and my coordinates maybe negative. To solve this I was thinking in translate ALL of the points in livecells so their coordinates be positive. I would do that by adding |minx|+30 to the x coordinate and |miny|+30 to the y coordinate
of each (x,y) in livecells...I haven't put it in practice yet, but it seems too complicated and memory consuming...Do you guys have any suggestion?
Hey so I'm trying to plot variables like age against its frequency, for a rotating body. I am given the period and period derivative aswell as their associated errors. Since frequency is related to period by:
f = 1/T
where frequency is f and period is T
then,
df = - (1/(T^2)) * dT
where dT and dF are the derivatives of period and frequency
but when it comes to plotting the log of this I can't do it in python as it doesn't accept negative values for a loglog plot.
I've tried a work around of using only absolute values but then I only get half the errors when plotting error bars. Is there a way to make python plot both the negative and positive error bars? The frequency derivative itself is a negative quantity.
Unfortunately, log(x) cannot be negative because log(x) = y <=> 10^y = x.
Is 10^y ever going to be -5?
Unfortunately it is impossible to make 10^y<=0 because as y becomes -infinity, x approaches 1/infinity; x approaches, but never passes 0.
Is it possible to plot log(x), where x is negative?
One simple solution to your problem however, is to take the absolute value of df. By doing this, negative numbers become positive. The only downside is that after you've transformed the data this way, you will need to undo the transformation. If the number was negative (and turned positive due to abs(df)), then you must multiply it by -1 afterwards.
You may need to define your own absolute value function that records any values it needs to make positive:
changeList = []
def absRecordChanges(value):
if value < 0 :
value = value * -1
changeList.append(value)
return value
There are other ways to solve the problem, but they are all centred around transforming your data to meet the conditions of a log tranformation (x > 0), and having the data you changed recorded so you can change it back afterward (before you plot it).
EDIT:
While fiddling around in desmos, I was able to plot log(x) where x is any integer. I used a piecewise function to do this: {x<0:-log(abs(x)),log (x)}.
def piecewiseLog(x)
If x <= 0 :
return -log(abs(x))
else :
return log(x)
As I'm not familiar with matlab syntax, this link has an alternative solution: http://www.mathworks.com/matlabcentral/answers/31566-display-negative-values-on-logarithmic-graph
I am trying to create a fool proof graphing calculator using python and pygame.
I created a graphing calculator that works for most functions. It takes a user string infix expression and converts it to postfix for easier calculations. I then loop through and pass in x values into the postfix expression to get a Y value for graphing using pygame.
The first problem I ran into was when taking calculations of impossible things. (like dividing by zero, square root of -1, 0 ^ non-positive number). If something like this would happen I would output None and that pixel wouldn't be added to the list of points to be graphed.
* I have showed all the different attempts I have made at this to help you understand where I cam coming from. If you would like to only see my most current code and method, jump down to where it says "current".
Method 1
My first method was after I acquired all my pixel values, I would paint them using the pygame aalines function. This worked, except it wouldn't work when there were missing points in between actual points because it would just draw the line across the points. (1/x would not work but something like 0^x would)
This is what 1/x looks like using the aalines method
Method 1.1
My next Idea was to split the line into two lines every time a None was printed back. This worked for 1/x, but I quickly realized that it would only work if one of the passed in X values exactly landed on a Y value of None. 1/x might work, but 1/(x+0.0001) wouldn't work.
Method 2
My next method was to convert the each pixel x value into the corresponding x point value in the window (for example, (0,0) on the graphing window actually would be pixel (249,249) on a 500x500 program window). I would then calculate every y value with the x values I just created. This would work for any line that doesn't have a slope > 1 or < -1.
This is what 1/x would look like using this method.
Current
My most current method is supposed to be a advanced working version of method 2.
Its kind of hard to explain. Basically I would take the x value in between each column on the display window. For every pixel I would do this just to the left and just to the right of it. I would then plug those two values into the expression to get two Y values. I would then loop through each y value on that column and check if the current value is in between both of the Y values calculated earlier.
size is a list of size two that is the dimensions of the program window.
xWin is a list of size two that holds the x Min and x Max of the graphing window.
yWin is a list of size two that holds the y Min and y Max of the graphing window.
pixelToPoint is a function that takes scalar pixel value (just x or just y) and converts it to its corresponding value on the graphing window
pixels = []
for x in range(size[0]):
leftX = pixelToPoint(x,size[0]+1, xWin, False)
rightX = pixelToPoint(x+1, size[0]+1, xWin, False)
leftY = calcPostfix(postfix, leftX)
rightY = calcPostfix(postfix, rightX)
for y in range(size[1]):
if leftY != None and rightY != None:
yPoint = pixelToPoint(y,size[1],yWin, True)
if (rightY <= yPoint <= leftY) or (rightY >= yPoint >= leftY):
pixels.append((x,y))
for p in pixels:
screen.fill(BLACK, (p, (1, 1)))
This fixed the problem in method 2 of having the pixels not connected into a continuous line. However, it wouldn't fix the problem of method 1 and when graphing 1/x, it looked exactly the same as the aalines method.
-------------------------------------------------------------------------------------------------------------------------------
I am stuck and can't think of a solution. The only way I can think of fixing this is by using a whole bunch of x values. But this way seems really inefficient. Also I am trying to make my program as resizable and customizable as possible so everything must be variably driven and I am not sure what type of calculations are needed to find out how many x values are needed to be used depending on the program window size and the graph's window size.
I'm not sure if I am on the right track or if there is a completely different method of doing this, but I want to create my graphing calculator to able to graph any function (just like my actual graphing calculator).
Edit 1
I just tried using as many x values as there are pixels (500x500 display window calculates 250,000 y values).
Its worked for every function I've tried with it, but it is really slow. It takes about 4 seconds to calculate (it fluctuates depending on the equation). I've looked around online and have found graphing calculators that are almost instantaneous in their graphing, but I cant figure out how they do it.
This online graphing calcuator is extremely fast and effective. There must be some algorithm other than using a bunch of x values than can achieve what I want because that site is doing it..
The problem you have is that to be able to know if between two point you can reasonably draw a line you have to know if the function is continuous in the interval.
It is a complex problem in General what you could do is use the following heuristic. If the slope of the line have changed too much from the previous one guess you have a non continuous point in the interval and don't draw a line.
Another solution would be based on solution 2.
After have draw the points that correspond to every value of the x axis try to draw for every adjacent x: (x1, x2) the y within (y1 = f(x1), y2 = f(x2)) that can be reach by an x within (x1, x2).
This can be done by searching by dichotomy or via the Newton search heuristic an x that could fit.