I am trying to plot a function which looks like that: .
Where, D range from 0.01 to 300km,
N is number of craters with dia > D per sq.km per giga year,
coefficients values are in code.
I get empty plot and obviously I am doing something very wrong which I am not able to understand. I am sharing my code.
'''
a_0 = -3.0876
a_1 = -3.557528
a_2 = 0.781027
a_3 = 1.021521
a_4 = -0.156012
a_5 = -0.444058
a_6 = 0.019977
a_7 = 0.086850
a_8 = -0.005874
a_9 = -0.006809
a_10 = 8.25*10**-4
a_11 = 5.54*10**-5
a_n = a_0 + a_1 + a_2 + a_3 + a_4 + a_5 + a_6 + a_7 + a_8 + a_9 + a_10 + a_11
for d in range(1, 200000):
n = a_0 + np.multiply(a_1, np.log(d))
+ np.multiply(a_2, np.log(d)**2)
+ np.multiply(a_3, np.log(d)**3)
+ np.multiply(a_4, np.log(d)**4)
+ np.multiply(a_5, np.log(d)**5)
+ np.multiply(a_6, np.log(d)**6)
+ np.multiply(a_7, np.log(d)**7)
+ np.multiply(a_8, np.log(d)**8)
+ np.multiply(a_9, np.log(d)**9)
+ np.multiply(a_10, np.log(d)**10)
+ np.multiply(a_11, np.log(d)**11)
print(10**n)
plt.plot(10**n, color='green')
plt.show()
'''
The graphical curve should look something like that
I can not understand your code, but if you want to plot the function you wrote you can try this:
import numpy as np
import matplotlib.pyplot as plt
a_0 = -3.0876
a_1 = -3.557528
a_2 = 0.781027
a_3 = 1.021521
a_4 = -0.156012
a_5 = -0.444058
a_6 = 0.019977
a_7 = 0.086850
a_8 = -0.005874
a_9 = -0.006809
a_10 = 8.25*10**(-4)
a_11 = 5.54*10**(-5)
N_POINTS = 100
a_coeff = np.array([a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11])
distance = np.logspace(np.log10(0.01), np.log10(200), N_POINTS)
exponents = np.arange(12)
distance_matrix = distance[:, np.newaxis]*np.ones([N_POINTS, 12])
N = 10**np.sum(a_coeff * (np.log10(distance_matrix)**exponents), axis=1)
fig, ax = plt.subplots(1, figsize=(3, 8))
ax.scatter(distance, N)
ax.set(xscale='log', yscale='log', ylim=(1e-7, 1e4), xlim=(0.001, 300))
Related
How to fill between two lines with different x and y? Now, the filling is for two y functions with the common x-axis, which is not true. When I tried x1, x2, y1, y2 I have got a worse result than displayed below.
import matplotlib.pyplot as plt
import numpy as np
from numpy import exp, sin
def g(y):
amp = 0.6
return amp*exp(-2.5*y)*sin(9.8*y)
def g_e(y):
amp = 0.66
return amp*exp(-2.5*y_e)*sin(8.1*y_e)
y = np.linspace(0, 0.83, 501)
y_e = np.linspace(0, 1.08, 501)
values = g(y)
values_e = g_e(y)
theta = np.radians(-65.9)
c, s = np.cos(theta), np.sin(theta)
rot_matrix = np.array(((c, s), (-s, c)))
xy = np.array([y, values]).T # rot_matrix
theta_e = np.radians(-60)
c_e, s_e = np.cos(theta_e), np.sin(theta_e)
rot_matrix_e = np.array(((c_e, s_e), (-s_e, c_e)))
xy_e = np.array([y, values_e]).T # rot_matrix_e
fig, ax = plt.subplots(figsize=(5,5))
ax.axis('equal')
x_shift = 0.59
y_shift = 0.813
x_shift_e = 0.54
y_shift_e = 0.83
ax.plot(xy[:, 0]+x_shift, xy[:, 1]+y_shift, c='red')
ax.plot(xy_e[:, 0]+x_shift_e, xy_e[:, 1]+y_shift_e, c='black')
ax.fill_between(xy[:, 0]+x_shift, xy[:, 1]+y_shift, xy_e[:, 1]+y_shift_e)
plt.show()
Script for additional question:
for i in range(len(x)-1):
for j in range(i-1):
xs_ys = intersection(x[i],x[i+1],x[j],x[j+1],y[i],y[i+1],y[j],y[j+1])
if xs_ys in not None:
xs.append(xs_ys[0])
ys.append(xs_ys[1])
I got an error:
if xs_ys in not None:
^
SyntaxError: invalid syntax
Here is an approach creating a "polygon" by concatenating the reverse of one curve to the other curve. ax.fill() can be used to fill the polygon. Note that fill_between() can look strange when the x-values aren't nicely ordered (as is the case here after the rotation). Also, the mirror function fill_betweenx() wouldn't be adequate in this case.
import matplotlib.pyplot as plt
import numpy as np
def g(y):
amp = 0.6
return amp * np.exp(-2.5 * y) * np.sin(9.8 * y)
def g_e(y):
amp = 0.66
return amp * np.exp(-2.5 * y_e) * np.sin(8.1 * y_e)
y = np.linspace(0, 0.83, 501)
y_e = np.linspace(0, 1.08, 501)
values = g(y)
values_e = g_e(y)
theta = np.radians(-65.9)
c, s = np.cos(theta), np.sin(theta)
rot_matrix = np.array(((c, s), (-s, c)))
xy = np.array([y, values]).T # rot_matrix
theta_e = np.radians(-60)
c_e, s_e = np.cos(theta_e), np.sin(theta_e)
rot_matrix_e = np.array(((c_e, s_e), (-s_e, c_e)))
xy_e = np.array([y, values_e]).T # rot_matrix_e
fig, ax = plt.subplots(figsize=(5, 5))
ax.axis('equal')
x_shift = 0.59
y_shift = 0.813
x_shift_e = 0.54
y_shift_e = 0.83
xf = np.concatenate([xy[:, 0] + x_shift, xy_e[::-1, 0] + x_shift_e])
yf = np.concatenate([xy[:, 1] + y_shift, xy_e[::-1, 1] + y_shift_e])
ax.plot(xy[:, 0] + x_shift, xy[:, 1] + y_shift, c='red')
ax.plot(xy_e[:, 0] + x_shift_e, xy_e[:, 1] + y_shift_e, c='black')
ax.fill(xf, yf, color='dodgerblue', alpha=0.3)
plt.show()
I'm trying to input a comandline argument to set values for a and r from the comandline. I'm really new to python so any help would be appreciated.
a = 1/(# days infected)
r = infectiousness of disease
import matplotlib.pyplot as plt
import numpy as np
import sys
population = 763
Scur = population -1 # number of people susceptible
Icur = 1 # number of people infected
Rcur = 0 # number of people recovered
trans_const = 0.00218 # infectiousness of disease r = kb/N
recov_rate = 0.5 # recovery rate a = 1/(# days infected)
simlength = 20 # number of days in simulation
SIRarray = np.zeros((simlength+1,3)) # using floats as ~% of popn
SIRarray[0,:] = Scur, Icur, Rcur # record initial values
for i in range(1, simlength+1):
new_infected = trans_const * Scur * Icur # = rSI
new_recovered = recov_rate * Icur # = aI
Scur = Scur - new_infected
Icur = Icur + new_infected - new_recovered
Rcur = Rcur + new_recovered
SIRarray[i,:] = Scur, Icur, Rcur
print("SIR Model Simulation")
print("Scur\t\tIcur\t\tRcur")
print("----------------------------------------")
for i in range(len(SIRarray)):
print("{0:.2f}\t\t{1:.2f}\t\t {2:.2f}".format(SIRarray[i,0],
SIRarray[i,1], SIRarray[i,2]))
a = int(sys.argv[1])
r = int(sys.argv[1])
plt.plot(SIRarray[:,0], "b")
plt.plot(SIRarray[:,1], "r")
plt.plot(SIRarray[:,2], "g" )
plt.title("SIR model parameters r = " + str(trans_const) + " a = " + str(recov_rate))
plt.xlabel("Number of People")
plt.ylabel("Number of People")
plt.legend(['Susceptible People', 'Infected', 'Recovered', 'y = 4x'],
loc='upper left')
plt.legend(['Susceptible People', 'Infected', 'Recovered', 'y = 4x'],
loc='upper left')
plt.savefig('SIR Model Simulation')
plt.show()
I am trying to implement Floyd-Steinberg dithering in Python after using KMeans. I realised, that after dithering I receive colours which are not included in the reduced palette, so I modify the image again with KMeans. However, when trying with this picture, I see no dithering at all. I got stucked, I got tired - please, help me. My ideas become almost extinct.
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
k = 16
im = Image.open('Image.png').convert('RGB') #Image converted to RGB
pic = np.array(im, dtype = np.float)/255 #Enables imshow()
im.close()
def kmeans(pic): #Prepares algorithmic data
v, c, s = pic.shape
repic = np.resize(pic, (c*v, 3))
kme = KMeans(n_clusters = k).fit(repic)
cl = kme.cluster_centers_
return kme, cl, repic, v, c
kme, cl, repic, v, c = kmeans(pic)
pred = kme.predict(repic)
def picture(v, c, cl, pred): #Creates a picture with reduced colors
image = np.ones((v, c, 3))
ind = 0
for i in range(v):
for j in range(c):
image[i][j] = cl[pred[ind]]
ind+=1
return image
image = picture(v, c, cl, pred)
def dither(pic, image): #Floyd-Steinberg dithering
v, c, s = pic.shape
Floyd = np.copy(image)
for i in range(1, v-1):
for j in range(1, c-1):
quan = pic[i][j] - image[i][j]
Floyd[i][j + 1] = quan * (np.float(7 / 16)) + pic[i][j + 1]
Floyd[i + 1][j - 1] = quan * (np.float(5 / 16)) + pic[i + 1][j - 1]
Floyd[i + 1][j] = quan * (np.float(3 / 16)) + pic[i + 1][j]
Floyd[i + 1][j + 1] = quan * (np.float(1 / 16)) + pic[i + 1][j + 1]
return Floyd
fld = dither(pic, image)
a1, a2, reim, a3, a4 = kmeans(fld)
lab = kme.predict(reim)
Floyd = picture(v, c, cl, lab)
plt.imshow(Floyd)
plt.show()
I am trying to find the values of temperatures between 2250 K to 2300 K and have written a basic equation that uses linear interpolation to define the enthalpies between these temperatures. I am not exactly sure how to do this.
This is the equation:
T1_e = 868739/(0.9*h1_co2 + 0.1*h1_co + 2*h1_h2o + 0.05*h1_o2 + 7.52*h1_n2)
T2_e = 868739/(0.9*h2_co2 + 0.1*h2_co + 2*h2_h2o + 0.05*h2_o2 + 7.52*h2_n2)
The values of h1_co2, h1_co, h2_co2, h2_co and so forth are constants for the respective temperatures of K.
T1_e represents the temperature at 2250 K.
T2_e represents the temperature at 2300 K.
I imagine your answer would something like this
import numpy as np
import matplotlib.pyplot as plt
# define your constants
h1_co2 = 7
h1_co = 12
h2_co2 = 6
h2_co = .5
# etc...
def T1_e(h1_co2, h1_co, h1_h2o, h1_o2, h1_n2):
t1_e = 868739/(0.9*h1_co2 + 0.1*h1_co + 2*h1_h2o + 0.05*h1_o2 + 7.52*h1_n2)
return t1_e
def T2_e(h2_co2, h2_co, h2_h2o, h2_o2, h2_n2):
t2_e = 868739/(0.9*h2_co2 + 0.1*h2_co + 2*h2_h2o + 0.05*h2_o2 + 7.52*h2_n2)
return t2_e
temp = [2250, 2300]
e1 = T1_e(h1_co2, h1_co, h1_h2o, h1_o2, h1_n2)
e2 = T2_e(h2_co2, h2_co, h2_h2o, h2_o2, h2_n2)
e = [e1, e2]
p = np.polyfit(temp, e, 1)
x = np.linspace(2250, 2300, 100)
plt.plot(x, np.poly1d(x))
plt.show()
I need to optimize a non-convex problem (max likelihood), and when I try quadratic optmiziation algorithms such as bfgs, Nelder-Mead, it fails to find the extremum, I frequently get saddle point, instead.
You can download data from here.
import numpy as np
import csv
from scipy.stats import norm
f=open('data.csv','r')
reader = csv.reader(f)
headers = next(reader)
column={}
for h in headers:
column[h] = []
for row in reader:
for h,v in zip(headers, row):
column[h].append(float(v))
ini=[-0.0002,-0.01,.002,-0.09,-0.04,0.01,-0.02,-.0004]
for i in range(0,len(x[0])):
ini.append(float(x[0][i]))
x_header = list(Coef_headers)
N = 19 # no of observations
I = 4
P =7
Yobs=np.zeros(N)
Yobs[:] = column['size']
X=np.zeros((N,P))
X[:,0] = column['costTon']
X[:,1] = column['com1']
X[:,2] = column['com3']
X[:,3] = column['com4']
X[:,4] = column['com5']
X[:,5] = column['night']
X[:,6] = 1 #constant
def myfunction(B):
beta = B[0.299,18.495,2.181,2.754,3.59,2.866,-12.846]
theta = 30
U=np.zeros((N,I))
mm=np.zeros(I)
u = np.zeros((N,I))
F = np.zeros((N,I))
G = np.zeros(N)
l = 0
s1 = np.expm1(-theta)
for n in range (0,N):
m = 0
U[n,0] = B[0]*column['cost_van'][n]+ B[4]*column['cap_van'][n]
U[n,1] = B[1]+ B[5]*column['ex'][n]+ B[8]*column['dist'][n]+ B[0]*column['cost_t'][n]+ B[4]*column['cap_t'][n]
U[n,2] = B[2]+ B[6]*column['ex'][n]+ B[9]*column['dist'][n] + B[0]*column['cost_Ht'][n]+ B[4]*column['cap_Ht'][n]
U[n,3] = B[3]+ B[7]*column['ex'][n]+ B[10]*column['dist'][n]+ B[0]*column['cost_tr'][n]+ B[4]*column['cap_tr'][n]
for i in range(0,I):
mm[i]=np.exp(U[n,i])
m= sum(mm)
for i in range(0,I):
u[n,i]=1/(1+ np.exp(U[n,i]- np.log(m-np.exp(U[n,i]))))
F[n,i] = np.expm1(-u[n,i]*theta)
CDF = np.zeros(N)
Y = X.dot(beta)
resid = 0
for n in range (0,N):
resid = resid + (np.square(Yobs[n]-Y[n]))
SSR = resid / N
dof = N - P - 1
s2 = resid/dof # MSE, or variance: the mean squarred error of residuals
for n in range(0,N):
CDF[n] = norm.cdf((Yobs[n]+1),SSR,s2) - norm.cdf((Yobs[n]-1),SSR,s2)
G[n] = np.expm1(-CDF[n]*theta)
k = column['Choice_Veh'][n]-1
l = l + (np.log10(1+(F[n,k]*G[n]/s1))/(-theta))
loglikelihood = np.log10(l)
return -loglikelihood
rranges = np.repeat(slice(-10, 10, 1),11, axis = 0)
a = rranges
from scipy import optimize
resbrute = optimize.brute(myfunction, rranges, full_output=True,finish=optimize.fmin)
print("# global minimum:", resbrute[0])
print("function value at global minimum :", resbrute[1])
Now, I decided to go for grid search and tried scipy.optimize.brute, but I get this error. In fact, my real variables are 47, I decreased it to 31 to work, but still doesn't. please help.
File "C:\...\site-packages\numpy\core\numeric.py", line 1906, in indices
res = empty((N,)+dimensions, dtype=dtype)
ValueError: array is too big.