import matplotlib.pyplot as plt
import numpy as np
import os
import sys
import time
MissionName = "Mars"
savename = "Mission"
start_time = time.time()
t = np.arange(0.0, 200.0, 0.01)
vE = np.where(t<50, 2580, 0)
M0 = 2970000
mps = 12857.1429
mT = (mps * t)
m = (M0 - mT)
G = (6.67 * (10**-11))
MAarde = ((5.972) * (10**24))
rAarde = 6371000
h1 = (vE * M0/mps)
h2 = (1-(m / M0))
h3 = (np.log(M0 / m) / np.log(2.718281828)) + 1
h = h1 * h2 * h3
Fz = ((m * G * MAarde) / ((rAarde + h)**2))
Fstuw = 35100000 # - Fz
a = Fstuw / m
v = vE * (np.log(M0 / m) / np.log(2.718281828))
plt.plot(t,v)
plt.xlabel('time (s)')
plt.ylabel('Velocity (m/s)')
plt.title('Model raketmissie ' + str(MissionName))
plt.grid(True)
plt.savefig(savename + ".png")
print("it cost %s seconds to execute" % float((time.time()) - float(start_time)))
plt.show()
so it's working fine, but say i'd want vE to be 5000 when t > 150, how would i go about that? since i know how to do it with 1 but not with 2... thanks!
You may can check if concatenate works for this.
t1 = np.arange(0.0, 150.0, 0.01)
t2 = np.arange(150.0, 200.0, 0.01)
t = np.concatenate((t1,t2))
vE1 = np.where(t1<50, 2580, 0)
vE2 = np.where(t2>150, 5000, 0)
vE = np.concatenate((vE1,vE2))
Related
I have been trying to simulate Two Temperature Model using fipy
the math of the model:
C_e(∂T_e)/∂t=∇[k_e∇T_e ]-G(T_e-T_ph )+ A(r,t)
C_ph(∂T_ph)/∂t=∇[k_ph∇T_ph] + G(T_e-T_ph)
the source supposed to heat the electrons T_e, then the heat transferred to phonons T_ph through G, when T_ph reach melting point for example 2700 K, some of heat (360000 J) goes as latent heat before melting.
here is my code:
from fipy.tools import numerix
import scipy
import fipy
import numpy as np
from fipy import CylindricalGrid1D
from fipy import Variable, CellVariable, TransientTerm, DiffusionTerm, Viewer, LinearLUSolver, LinearPCGSolver, \
LinearGMRESSolver, ImplicitDiffusionTerm, Grid1D, ImplicitSourceTerm
## Mesh
nr = 50
dr = 1e-7
# r = nr * dr
mesh = CylindricalGrid1D(nr=nr, dr=dr, origin=0)
x = mesh.cellCenters[0]
# Variables
T_e = CellVariable(name="electronTemp", mesh=mesh,hasOld=True)
T_e.setValue(300)
T_ph = CellVariable(name="phononTemp", mesh=mesh, hasOld=True)
T_ph.setValue(300)
G = CellVariable(name="EPC", mesh=mesh)
t = Variable()
# Material parameters
C_e = CellVariable(name="C_e", mesh=mesh)
k_e = CellVariable(name="k_e", mesh=mesh)
C_ph = CellVariable(name="C_ph", mesh=mesh)
k_ph = CellVariable(name="k_ph", mesh=mesh)
C_e = 4.15303 - (4.06897 * numerix.exp(T_e / -85120.8644))
C_ph = 4.10446 - 3.886 * numerix.exp(-T_ph / 373.8)
k_e = 0.1549 * T_e**-0.052
k_ph =1.24 + 16.29 * numerix.exp(-T_ph / 151.57)
G = numerix.exp(21.87 + 10.062 * numerix.log(numerix.log(T_e )- 5.4))
# Boundary conditions
T_e.constrain(300, where=mesh.facesRight)
T_ph.constrain(300, where=mesh.facesRight)
# Source 𝐴(𝑟,𝑡) = 𝑎𝐷(𝑟)𝜏−1 𝑒−𝑡/𝜏 , 𝐷(𝑟) = 𝑆𝑒 exp (−𝑟2/𝜎2)/√2𝜋𝜎2
sig = 1.0e-6
tau = 1e-15
S_e = 35
d_r = (S_e * 1.6e-9 * numerix.exp(-x**2 /sig**2)) / (numerix.sqrt(2. * 3.14 * sig**2))
A_t = numerix.exp(-t/tau)
a = (numerix.sqrt(2. * 3.14)) / (3.14 * sig)
A_r = a * d_r * tau**-1 * A_t
eq0 = (
TransientTerm(var=T_e, coeff=C_e) == \
DiffusionTerm(var=T_e, coeff=k_e) - \
ImplicitSourceTerm(coeff=G, var=T_e) + \
ImplicitSourceTerm(var=T_ph, coeff=G) + \
A_r)
eq1 = (TransientTerm(var=T_ph, coeff=C_ph) == DiffusionTerm(var=T_ph, coeff=k_ph) + ImplicitSourceTerm(var=T_e, coeff=G) - ImplicitSourceTerm(coeff=G, var=T_ph))
eq = eq0 & eq1
dt = 1e-18
steps = 7000
elapsed = 0.
vi = Viewer((T_e, T_ph), datamin=0., datamax=2e4)
for step in range(steps):
T_e.updateOld()
T_ph.updateOld()
vi.plot()
res = 1e100
dt *= 1.01
count = 0
while res > 1:
res = eq.sweep(dt=dt, underRelaxation=0.5)
print(t, res)
t.setValue(t + dt)
As I understood I can include the latent heat as source term as sink in eq1, or add a gaussian peak to C_ph and the peak center should be around melting point.
I have no idea which one is better and more stable, I have no idea how to implement any one of them .
please help me with that
Based on the comments (please edit that into the question), change eq1 to
eq1 = (TransientTerm(var=T_ph, coeff=C_ph)
== DiffusionTerm(var=T_ph, coeff=k_ph)
+ ImplicitSourceTerm(var=T_e, coeff=G)
- ImplicitSourceTerm(coeff=G, var=T_ph)
+ (1/numerix.sqrt(2*numerix.pi * sig2)) * numerix.exp(-(T_ph - 1850)**2 / 2 * sig2)))
It will be evaluated explicitly, but it will update whenever T_ph updates.
I'm trying to figure out whats wrong about the following code sample. Running this I end up with a syntax error on line 18. Can't figure out why though.
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
def hex(x, A):
Tf = x[0]
Tk = x[1]
Nk = 0.1
Tg = 300
b = 0.2
ag = 30
k = 20
Hvap = 80000
cpg = 100
cpk = 600
ng = 30
cpf = 600
q = k * (Tf-Tk)
n1 = ng * b * np.log(y2f/y2b)
dTfdA = (ag * phi * (Hvap/cpg + (Tg-Tf)/(1-np.exp(-phi))) - q / (Nf * cpf)
dTkdA = -q / (Nk * cpk)
return [dTfdA, dTkdA]
I think you're missing a bracket
dTfdA = (ag * phi * (Hvap/cpg + (Tg-Tf)/(1-np.exp(-phi))) - q / (Nf * cpf)
to
dTfdA = (ag * phi * (Hvap/cpg + (Tg-Tf)/(1-np.exp(-phi))) - q / (Nf * cpf))
You should write the equation as:
dTkdA = 0 - q / (Nk * cpk)
So the purpose of my code is to use inputted data points to give a gaussian plot distribution. I figured out how to make it work with a double gaussian but I'm having a lot of trouble adding a third. Im not quite sure what I'm doing wrong. 1 of the errors I keep getting is an Index Error saying that the list index is out of range. I would appreciate any help with this.
Heres my code:
from pylab import *
import numpy as np
from numpy import loadtxt
from scipy.optimize import leastsq
from scipy.optimize import least_squares
from scipy.stats import iqr
import math
import matplotlib.pyplot as plt
import sys
matplotlib.rcParams['mathtext.default'] = 'regular'
fitfunc_triple = lambda p, x: np.abs(p[0]) * exp(-0.5 * ((x - p[1]) / p[2]) ** 2) + np.abs(p[3]) * exp(
-0.5 * ((x - p[4]) / p[5]) ** 2) + np.abs(p[6]) * exp(-0.5 * ((x - p[7])/ p[8] **2 ))
fitfunc_double = lambda p, x: np.abs(p[0]) * exp(-0.5 * ((x - p[1]) / p[2]) ** 2) + np.abs(p[3]) * exp(
-0.5 * ((x - p[4]) / p[5]) ** 2)
fitfunc_single = lambda p, x: np.abs(p[0]) * exp(-0.5 * ((x - p[1]) / p[2]) ** 2)
errfunc = lambda p, x, y: (y - fitfunc(p, x))
dataR = np.loadtxt("/Users/Safi/Library/Preferences/PyCharmCE2018.1/scratches/rspecial1385.a2261.dat5", skiprows=0)
RA = dataR[:, 0]
DEC = dataR[:, 1]
VELR = dataR[:, 2]
REDSH = dataR[:, 3]
RADD = dataR[:, 4]
sl = 3E5
zbar = np.mean(REDSH)
vc = zbar * sl
VEL = vc + sl * ((REDSH - zbar) / (1 + zbar))
wdith = 200
iters = 10
sig2 = 500
binN = int(math.ceil((np.max(VEL) - np.min(VEL)) / wdith))
sys.stdout = open(str(wdith) + "_1sigma_" + str(iters) + "_sig2_" + str(sig2) + ".txt", "w")
plt.figure(1)
y, x, _ = plt.hist(VEL, binN, alpha=0.5, label='data')
x = (x[1:] + x[:-1]) / 2 # for len(x)==len(y)
data = np.vstack((x, y)).T
xdata = data[:, 0]
ydata = data[:, 1]
yerr = ydata ** 0.5
init = [10, 69500, 1200, 5, 68000, sig2]
bds = ([0, 66000, 800, 0, 66000, sig2], [50, 70000, 1750, 20, 70000, sig2 + 0.01])
def index_outlier(data):
inter_quart = iqr(data) * 1.5
bd2 = np.percentile(data, 75) + inter_quart
bd1 = np.percentile(data, 25) - inter_quart
index = []
for i in [i for i, x in enumerate(data) if x < bd1 or x > bd2]:
index.append(i)
return (index)
#### Bootstrapping Estimation Function ####
def fit_bootstrap(fitfunc, datax, datay, init, bds, sigma, iterations=iters):
errfunc = lambda p, x, y: (y - fitfunc(p, x))
# Fit first time
pfit = least_squares(errfunc, init, bounds=bds, args=(datax, datay), max_nfev=10000)
model = fitfunc(pfit.x, datax)
residuals = pfit.fun
# Random data sets are generated and fitted
ps = []
for i in range(iterations):
randomdataY = []
for k in range(len(sigma)):
randomDelta = np.random.normal(0., sigma[k], 1)
randomdataY.append(datay[k] + randomDelta)
out = np.concatenate(randomdataY)
randomfit = least_squares(errfunc, init, bounds=bds, args=(datax, out))
ps.append(randomfit.x)
# Removing outliers
# Finding outliers and indexing them
master_list = []
indexed = []
for k in range(len(ps[0])): # 0-6
it = []
for i in range(len(ps)): # 0-1000
it.append(ps[i][k])
master_list.append(it)
# indexed.append(index_outlier(master_list[k]))
# # List of outlier indicies
# flat_list=[item for sublist in indexed for item in sublist]
# no_dups= list(set(flat_list))
# # Removing bad fits
# for k in range(len(master_list)):
# for i in sorted(no_dups,reverse=True):
# del master_list[k][i]
pfit_bootstrap = []
perr_bootstrap = []
for i in master_list:
pfit_bootstrap.append(np.median(i))
perr_pos = np.round(np.percentile(i, 84) - np.median(i), 4)
perr_neg = np.round(np.median(i) - np.percentile(i, 16), 4)
perr_bootstrap.append(str('[+') + str(perr_pos) + str(',-') + str(perr_neg) + str(']'))
return (pfit_bootstrap, perr_bootstrap, residuals, pfit.nfev, master_list)
pfit, perr, residuals, nfev, master_list = fit_bootstrap(fitfunc_double, xdata, ydata, init, bds, yerr)
pfit1, perr1, residuals1, nfev1, master_list1 = fit_bootstrap(fitfunc_single, xdata, ydata, init, bds, yerr)
more_data = np.linspace(np.min(xdata), np.max(xdata), 1000)
real_func = fitfunc_double(pfit, more_data)
real_func1 = fitfunc_single(pfit1, more_data)
######## Saving Coefficients #########
A1 = pfit[0]
m1 = pfit[1]
s1 = pfit[2]
A2 = pfit[3]
m2 = pfit[4]
s2 = pfit[5]
A3 = pfit[6]
m3 = pfit[7]
s3 = pfit[8]
pecp = VEL - vc
m1p = m1 - vc
m2p = m2 - vc
m3p = m3 - vc
xdatap = xdata - vc
plt.figure(6)
plt.hist(pecp, binN, alpha=.5, label='data', color='skyblue')
xhmax = np.amax(pecp + 1500)
xhmin = np.amin(pecp - 1500)
xh = np.linspace(xhmin, xhmax, 50)
# yh1=(mlab.normpdf(xh, c[1], c[2]))
yh1 = np.abs(A1) * exp(-0.5 * (((xh - m1p) / (s1)) ** 2))
yh2 = np.abs(A2) * exp(-0.5 * (((xh - m2p) / (s2)) ** 2))
yh3 = np.abs(A3) * exp(-0.5 * (((xh - m3p) / (s3)) ** 2))
plt.plot(xh, yh1, color='b', linewidth=2)
plt.plot(xh, yh2, color='r', linewidth=2)
plt.plot(xh, yh3, color='g', linewidth=2)
plt.plot(xh, yh1 + yh2 + yh3, color='purple', linewidth=3)
# plt.errorbar(xdatap,y,xerr=wdith/2,ls='none', yerr=yerr,color='k',linewidth=2)
# plt.plot(xdatap, ydata,'.',color='k')
plt.ylim(0, np.max(ydata) + 2)
plt.xlabel('Peculiar Velocity (km/s)')
plt.ylabel('N$_{gal}$')
plt.text(-4800, 15, '$\mu_{2}$-$\mu_{1}$ = ' + str(int(m2 - m1)) + ' km/s')
plt.savefig(str(wdith) + "_1sigma_" + str(iters) + "_sig2_" + str(sig2) + "_hist.ps")
divi = -1800
memlow = np.array([[0 for x in range(2)] for y in range(1)])
memhigh = np.array([[0 for x in range(2)] for y in range(1)])
j = 0
k = 0
plt.show()
I have written code to solve the protoplanetary hydrostatic equilibria equations using first order euler method, and the results are as expected. I now want to rewrite it using fourth order Runge-Kutta solution, which is builtin to scipy.integrate.ode
Expected result, attained by using a custom written euler method:
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import ode
universalGasConstant = 8.31
gravitationalConstant = 6.67 * 10**-11
astronomicalUnit = 1.5 * (10**11)
coreMass = 5.9 * 10**24
sunMass = 2 * (10**30)
coreRadius = 0
coreDensity = 5500.0
semiMajorAxis = 5 * astronomicalUnit
gasMeanMolecularMass = 2.3 * 10**-3
coreRadius = (coreMass / ((4 / 3) * np.pi * coreDensity))**(1 / 3)
print('coreradius is', coreRadius)
hillSphere = (1**-4)*(semiMajorAxis) * (((coreMass) / (3 * sunMass))**(1 / 3))
print('hillsphere is', hillSphere)#THIS IS THE HILLSPHERE
numberOfSlices = 100000000 #NUMBER OF SLICES
deltaRadius = hillSphere / numberOfSlices
print('slice length is', deltaRadius)
#gravitationalForce = ((gravitationalConstant * coreMass) /
#(coreRadius + (deltaRadius)))
sunSurfaceTemperature = 5800
sunRadius = 6.96 * 10**8
equilibriumTemperature = sunSurfaceTemperature * \
(sunRadius / (2 * semiMajorAxis))**(1 / 2)
print('equilibrium temperature at', semiMajorAxis,
'metres is', equilibriumTemperature, 'kelvin')
pressureAtRadius = 0
initialDensity = 10.0 #INITIAL DENSITY
densityAtRadius = 0
muOverRT = gasMeanMolecularMass/(equilibriumTemperature * universalGasConstant)
print('muOverRT is', muOverRT)
totalMass = coreMass
densityAtRadius = initialDensity
def function(y, r):
totalMass = y[0]
distanceFromCOG = y[1]
# the differential equations
dRhodr = -(((gravitationalConstant*totalMass*
densityAtRadius*muOverRT))/(distanceFromCOG**2))
dMdr = 4*np.pi*gravitationalConstant*densityAtRadius
#dPdr = (1/(muOverRT))*dRhodr
return [dRhodr, dMdr]
distanceFromCOG = coreRadius+np.linspace(0,numberOfSlices) #number of points
initialDensity = [0,0]
solution = ode(function,initialDensity,distanceFromCOG).set_integrator('vode', method = 'dopri5')
plt.plot(solution)
solution.set_integrator('dopri5')
I am new to python, transiting from Matlab. I wrote the following code to solve a nonlinear equation system but somehow failed in python. It worked in matlab fsolve for many initial values unless I put an extremely large number. But it only works for python fsolve if the initial value is close enough to the solution. I don't always have good initial guess to the problem so I want it to work most of the time. Thank you very much! Solution is [0.003,0.0053] according to Matlab.
Python code
param = {'r': 0.04,
'mu': 0.112,
'delta': 0.02,
'alpha': 0.35,
'g': 0.0187 + 0.5*0.16*0.16,
'sigma': 0.20,
'xi0': 0.02,
'xi1':1.05,
'lambda0':0.02,
'lambda1':1.05};
param['sgsq'] = 0.5*param['sigma']**2;
param['g0'] = param['g'] - (param['mu'] - param['r']) - param['sgsq'];
#%% Polynomial
import numpy as np
import numpy.polynomial.polynomial as poly
import scipy.optimize as spyopt
param['coef'] = (- (param['r']+param['delta']), (param['g0']+param['delta']
-param['sgsq']), param['sgsq'])
charfun = poly.Polynomial(param['coef'])
param['psi'] = np.max(poly.polyroots(param['coef']))
param['halpha'] = poly.polyval(param['alpha'],param['coef'])
def lumpyfun(x0, param0):
xstar,B = x0
AIPx = - np.power(xstar,param0['alpha']) / param0['halpha']
BigA = ((1.0-param0['alpha'])*(B**param0['alpha'])/(1.0-param0['psi'])/param0['halpha']
+ (param0['lambda1']-param0['lambda0'])/(1.0-param0['psi']))
vprimex = param0['alpha']*AIPx/xstar + param0['psi']*np.power((xstar/B),(param0['psi']-1.0)) * BigA/B
vprimeB = (param0['psi']-param0['alpha'])*np.power(B,param0['alpha']-1.0)/(1.0-param0['psi'])/param0['halpha'] + param0['psi']*(param0['lambda1']-param0['lambda0'])/(1.0-param0['psi'])/B
diffy = (AIPx + np.power(xstar/B,param0['psi']) * BigA - xstar*vprimex - param0['lambda1'], vprimex - vprimeB)
return diffy`def lumpyfun(x0, param0):
#%% Solve the problem
#worked
x0 = np.multiply(np.sqrt(-param['halpha']),(1.0,2.0))/100.0
#lumpyfun(x0,param)
spyopt.fsolve(lumpyfun, x0, args=param)
# not worked
x0 = np.multiply(np.sqrt(-param['halpha']),(1.0,2.0))/10.0
spyopt.fsolve(lumpyfun, x0, args=param, maxfev = 5000000)
Matlab code:
r = 0.04;
mu = 0.112;
delta = 0.02;
alpha = 0.35;
g = 0.0187 + 0.5*0.16*0.16 ; % 0.0187 + 0.5*sigma*sigma;
sigma = 0.20; % 0.16 default;
a2 = 0.5*sigma*sigma;
g0 = g - (mu-r) - a2; % risk-neutral growth;
lambda0 = 0.02;
lambda1 = 1.05;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%h = #(x) sgsq05*x^2 + (mu+delta-sgsq05)*x - (r+delta);
coef = [a2, (g0+delta-a2), - (r+delta)];
halpha = polyval(coef,alpha);
phi = max(roots(coef))
x0 = realsqrt(-halpha)*[1;2]/10;
options = optimoptions('fsolve','Display','off','MaxFunEvals',2000);
sol = fsolve(#(x) diffinvestmentoption(x,phi,alpha,lambda1,lambda0,halpha), x0, options);
function [diffy,X] = diffinvestmentoption(xin,phi,alpha,lambda1,lambda0,halpha)
xstar = xin(1);
B = xin(2);
AIPx = -xstar.^alpha / halpha;
%AIPB = -B.^alpha / halpha;
BigA = (1-alpha)*(B^alpha)/(1-phi)/halpha + (lambda1-lambda0)/(1-phi);
vprimex = alpha*AIPx/xstar + phi*(xstar/B)^(phi-1) * BigA/B;
vprimeB = (phi-alpha)*(B^(alpha-1))/(1-phi)/halpha + phi*(lambda1-lambda0)/(1-phi)/B;
diffy = [AIPx + (xstar/B)^phi * BigA - xstar*vprimex - lambda1;
vprimex - vprimeB];