Counting points in an array that meet certain conditions - arrays

I am having trouble getting my code to count the correct number of elements from three different arrays, with each array having its own parameter. I would like the element to be counted if its meets all three parameters this is what I have so far
import numpy as np
import random as rand
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')
n = 10
x0 = np.zeros(n)
y0 = np.zeros(n)
z0 = np.zeros(n)
x1 = np.zeros(n)
y1 = np.zeros(n)
z1 = np.zeros(n)
hit = 0
for k in range (n):
theta = rand.uniform(0.0, np.pi)
phi = rand.uniform(0, (2 * np.pi))
x0[k] = np.sin(phi) * np.cos(theta)
y0[k] = np.sin(phi) * np.sin(theta)
z0[k] = np.cos(theta)
for j in range (n):
theta = rand.uniform(0.0, np.pi)
phi = rand.uniform(0, (2 * np.pi))
x1[j] = np.sin(phi) * np.cos(theta)
y1[j] = np.sin(phi) * np.sin(theta)
z1[j] = np.cos(theta)
for i in range(n):
if np.any(x1[j] > -0.3) and np.any(x1[j] < 0.7) and np.any(y1[j] > -0.3) and np.any(y1[j] <0.7) and np.any(z1[j] > -0.3) and np.any(z1[j] < 0.3):
hit += 1
ax.plot_wireframe([x0[k],x1[j]],[y0[k],y1[j]],[z0[k],z1[j]])
print (hit)
print (x1,y1,z1)
plt.show()
I would like for only the end points to be counted if they meet the three parameters.
Thank you

Related

Quantum walk on 3D grid

I am trying to apply the quantum coin walk on a 3D grid, with 3 Hadamard coins. However I can't seem to get symmetric results after 3 steps. Is it simply not possible to have a probability distribution which is symmetric with such a coin?
Thank you
ps the implementation is based on http://susan-stepney.blogspot.com/2014/02/mathjax.html and the position vector captures a 3D grid.
pps Has this been attempted on qiskit? I couldn't use the hard coded matrix to get result perfectly symmetric for some reasons...
Not sure I answered your question, but
from the code reference you mentioned, I only changed line 30 to:ax = fig.add_subplot(111, projection = '3d') and line 3 to:from mpl_toolkits.mplot3d import Axes3D
from numpy import *
from matplotlib.pyplot import *
from mpl_toolkits.mplot3d import Axes3D
N = 100 # number of random steps
P = 2*N+1 # number of positions
coin0 = array([1, 0]) # |0>
coin1 = array([0, 1]) # |1>
C00 = outer(coin0, coin0) # |0><0|
C01 = outer(coin0, coin1) # |0><1|
C10 = outer(coin1, coin0) # |1><0|
C11 = outer(coin1, coin1) # |1><1|
C_hat = (C00 + C01 + C10 - C11)/sqrt(2.)
ShiftPlus = roll(eye(P), 1, axis=0)
ShiftMinus = roll(eye(P), -1, axis=0)
S_hat = kron(ShiftPlus, C00) + kron(ShiftMinus, C11)
U = S_hat.dot(kron(eye(P), C_hat))
posn0 = zeros(P)
posn0[N] = 1 # array indexing starts from 0, so index N is the central posn
psi0 = kron(posn0,(coin0+coin1*1j)/sqrt(2.))
psiN = linalg.matrix_power(U, N).dot(psi0)
prob = empty(P)
for k in range(P):
posn = zeros(P)
posn[k] = 1
M_hat_k = kron( outer(posn,posn), eye(2))
proj = M_hat_k.dot(psiN)
prob[k] = proj.dot(proj.conjugate()).real
fig = figure()
ax = fig.add_subplot(111, projection = '3d')
plot(arange(P), prob)
plot(arange(P), prob, 'o')
loc = range(0, P, P // 10) #Location of ticks
xticks(loc)
xlim(0, P)
ax.set_xticklabels(range(-N, N+1, P // 10))
show()

Convert multi-variable discrete list of lists into a scattered plot

I have a list of lists in the form of a multi-value function
*[[var1, [a1,b1,...,z1], [var2, [a2,b2,...,z2]],,,[varn, [an,bn,,,,zn]]]*.
I would like to convert this into a multi-value list first in the form of
*[[var1,a1], [var1,b1],,,[var1,z1],[var2,a2],[var2,b2],,,[var2,z2],,,,]*
so I can then plot those as scattered plot and do further analysis with them. Is there an easier way to do it? If not, how do you do such a conversion?
If I was dealing with a single-value list of lists, here is what I have learned (from this post of mine How to make a binned version of a barplot?):
import numpy as np
import matplotlib.pyplot as plt
A = [[var1,val1], [var2,val2], ...[varn,valn]] # Some single value list of lists
A = np.array(A)
numbins = 7
xmin = 8
xmax = xmin + numbins * 0.6
xrange = xmax - xmin
bounds = np.linspace(xmin, xmax, numbins + 1, endpoint=True)
mids = (bounds[:-1] + bounds[1:]) / 2
bins = [[] for _ in range(numbins)]
for x, y in A:
bins[int((x - xmin) / xrange * numbins)].append(y)
bins = [np.array(b) for b in bins]
means = np.array([np.mean(bin) if len(bin) > 0 else np.nan for bin in bins])
stds = np.array([np.std(bin) if len(bin) > 0 else np.nan for bin in bins])
plt.stem(mids, means + stds, linefmt='k-', markerfmt='k_', use_line_collection=True)
plt.bar(mids, means, width=xrange / numbins, color='salmon', ec='k', zorder=2)
plt.scatter(A[:, 0]+np.random.uniform(-.02, .02, A.shape[0]), A[:, 1],
s=2, color='b', alpha=0.5, zorder=3)
plt.xticks(bounds, [f'{b:.1f}' for b in bounds])
plt.yscale('log')
plt.show()
Thanks,
Try:
[[x[0], x[1][i]] for x in A for i in range(len(x[1]))]

Appending 2D array to a list of arrays

My code has a problem. I know what the problem is.
I cant append an array to another array with the append method.
I need to find something else. What is an effective and not complicated way to append an array to an array?
This code should plot the trajectory of a ball that is fired from different angles ( 5 to 85 degrees).
import numpy as np
import matplotlib.pyplot as plt
alpha = np.arange(5,86,5)
v0 = 30
Cd = 1.2
A = 0.02
M = 1.5
gvec = np.array([0,-9.813])
rho = 1.225
dt = 0.01
for a in alpha:
xvec = np.array([0.0,0.0])
vvec = v0 * np.array([np.cos(a),np.sin(a)])
xall = []
while xvec[1] > 0:
V = np.sqrt(np.sum(vvec*vvec))
Dvec = -0.5 * rho * Cd * A * V**2 * vvec /V
accvec = gvec + Dvec/M
vvec = vvec + accvec*dt
xvec = xvec + vvec*dt
xall.append(xvec)
xall = np.array(xall)
plt.plot(xall[:,0] ,xall[:,1])
plt.show()
I would like to create an array " xall" in the following format.
xall are all the coordinates. so this is what i want.
xall = array([x1,y1], [x2,y2], ....... , [xn, yn])
Your code is ok, but the condition of while is somehow wrong.
xvec = np.array([0.0,0.0])
vvec = v0 * np.array([np.cos(a),np.sin(a)])
xall = []
while xvec[1] > 0:
Since you define xvec as many 0's array, the condition for while is not met and just passed. Once you include xvec[1] = 0, you can obtain a plot.
Btw, the sin and cos function treats the angle as radian, so you have to modify a bit
vvec = v0 * np.array([np.cos(np.pi * a / 180), np.sin(np.pi * a / 180)])
and the result will be:

How can I get output from a for loop into a separate set in python?

So I need all the output for 'distance in the program to be in one set so I can perform operations on it. Here is the code, most calculations are irrelevant. Python 3.6.
import json
with open('strings.json') as data_file:
data = json.load(data_file)
from math import sin, cos, sqrt, atan2, radians
R = 6373.0
for i in range(0, 81):
dataPoint = data[i]
dataPoint1 = data [i+1]
coordinate = dataPoint['coordinates']
coordinate1 = dataPoint1['coordinates']
x = coordinate[0]
y = coordinate[1]
x1 = coordinate1[0]
y1 = coordinate1[1]
#Irrelevant math here
import math
lat1 = math.cos(math.radians(x)) #converts degrees of long or latitude into rads
lon1 = math.cos(math.radians(y))
lat2 = math.cos(math.radians(x1))
lon2 = math.cos(math.radians(y1))
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2 #formula for distance
c = 2 * atan2(sqrt(a), sqrt(1 - a))
Here lies the problem-
distance = R * c
SetDist = [distance] #this gives me just the final value of distance
from the iteration, I need all.
print("distance between the 2 points:", distance)
I'd also print the set outside the loop block. Thanks.

Two dimensional convolution in matlab . Result differs from conv2 of matlab toolbox.Any tip?

[r,c] = size(x);
[m,n] = size(y);
h = rot90(y, 2);
center = floor((size(h)+1)/2);
Rep = zeros(r + m*2-2, c + n*2-2);
return
for x1 = m : m+r-1
for y1 = n : n+r-1
Rep(x1,y1) = x(x1-m+1, y1-n+1);
end
end
B = zeros(r+m-1,n+c-1);
for x1 = 1 : r+m-1
for y1 = 1 : n+c-1
for i = 1 : m
for j = 1 : n
B(x1, y1) = B(x1, y1) + (Rep(x1+i-1, y1+j-1) * h(i, j));
end
end
end
end
Con=conv2(Rep,h);
I have this code for 2d convolution.But Con and B are different(last column of correct convolution(=Con) does not exist in B,and other elements also differ.I cant understand what i do wrong.

Resources