real gas, 1D pipe flow in Pyomo + SCIP failing through energy equation? - python
Hi there smart people!
I am trying to implement a 1D, steady-state, real gas (compressibility factor) pipe flow model in Python using Pyomo + SCIP. It basically amounts to solving a DAE system. The formulation is an adopted version from chapter 10 in Koch, T.; Hiller, B.; Pfetsch, M.E.; Schewe, L. Evaluating Gas Network Capacities; Series on Optimization, MOS-SIAM, 2015.
However, I am encountering several problems:
The problem seems to be numerically sensitive to a combination of the discretization step length and input parameters (mass flow, pipe length).
Does not solve for any other model but ideal gas.
With a suitable discretization, and an ideal gas law, I get a result that seems reasonable (see example). In all other cases it turns out to be infeasible.
I may be overlooking something here, but I do not see it. Therefore, if anyone is inclined to try and help me out here, I would be thankful.
The example below should produce a valid output.
Edit: I realized I had one false constraint in there belonging to another model. The energy equation works now. However, the problems mentioned above remain.
from pyomo.dae import *
from pyomo.environ import *
import matplotlib.pyplot as plt
from math import pi
from dataclasses import dataclass
#dataclass
class ShomateParameters:
A: float
B: float
C: float
D: float
E: float
def specific_isobaric_heat_capacity(self, temperature):
# in J/(mol*K)
return self.A + self.B * (temperature/1000) + self.C * (temperature/1000)**2 + self.D * (temperature/1000)**3 + self.E/(temperature/1000)**2
def plot(self, temperature_start, temperature_end, points_to_mark=None):
assert temperature_start <= temperature_end, "temperature_start <= temperature_end must hold."
temperatures = [i for i in range(temperature_start, temperature_end+1)]
values = [self.specific_isobaric_heat_capacity(temp) for temp in temperatures]
fig, ax = plt.subplots()
ax.plot(temperatures, values)
if points_to_mark is not None:
ax.scatter(points_to_mark, [self.specific_isobaric_heat_capacity(temp) for temp in points_to_mark])
ax.set(xlabel='temperature [K]', ylabel='specific isobaric heat capacity [J/(mol*K)]',
title='Shomate equation:\n A + B*T + C*T^2 + D*T^3 + E/T^2')
ax.grid()
plt.show()
#dataclass
class Species:
MOLAR_MASS: float # kg/mol
CRITICAL_TEMPERATURE: float # Kelvin
CRITICAL_PRESSURE: float # Pa
DYNAMIC_VISCOSITY: float # Pa*s
SHOMATE_PARAMETERS: ShomateParameters
METHANE = Species(MOLAR_MASS=0.016043,
CRITICAL_TEMPERATURE=190.56,
CRITICAL_PRESSURE=4599000,
DYNAMIC_VISCOSITY=1.0245e-5,
SHOMATE_PARAMETERS=ShomateParameters(
A=-0.703029,
B=108.4773,
C=-42.52157,
D=5.862788,
E=0.678565))
# select gas species
gas = METHANE
# select equation of state ('ideal', 'AGA' or 'Papay')
formula = 'ideal'
PIPE_LENGTH = 24000 # meter
start = 0 # meter
end = start + PIPE_LENGTH
MASS_FLOW = 350 # kg/s
PIPE_SLOPE = 0.0
PIPE_DIAMETER = 1.0 # meter
PIPE_INNER_ROUGHNESS = 6e-5 # 15e-6 # meter 6e-6 # meter
# gravitational acceleration
G = 9.81 # meter**2/s**2
# gas temperature at entry
TEMPERATURE = 283.15
# temperature ambient soil
TEMPERATURE_SOIL = 283.15 # Kelvin
# gas pressure at entry
PRESSURE = 4.2e6 # Pa
GAS_CONSTANT = 8.314 # J/(mol*K)
print(gas.SHOMATE_PARAMETERS)
print(gas.SHOMATE_PARAMETERS.specific_isobaric_heat_capacity(TEMPERATURE))
gas.SHOMATE_PARAMETERS.plot(273, 400, points_to_mark=[TEMPERATURE])
##################################################################################
# Variable bounds
##################################################################################
pressure_bounds = (0, 1e7) # Pa
temperature_bounds = (0, 650) # Kelvin
density_bounds = (0, 100)
idealMolarIsobaricHeatCapacityBounds = (0, 200)
correctionIdealMolarIsobaricHeatCapacityBounds = (-250, 250)
velocity_bounds = (0, 300)
##################################################################################
# Create model
##################################################################################
m = ConcreteModel()
##################################################################################
# Parameters
##################################################################################
m.criticalPressure = Param(initialize=gas.CRITICAL_PRESSURE)
m.criticalTemperature = Param(initialize=gas.CRITICAL_TEMPERATURE)
m.molarMass = Param(initialize=gas.MOLAR_MASS)
m.dynamicViscosity = Param(initialize=gas.DYNAMIC_VISCOSITY)
m.gravitationalAcceleration = Param(initialize=G)
m.pipeSlope = Param(initialize=PIPE_SLOPE)
m.innerPipeRoughness = Param(initialize=PIPE_INNER_ROUGHNESS)
m.c_HT = Param(initialize=2)
m.pi = Param(initialize=pi)
m.temperatureSoil = Param(initialize=TEMPERATURE_SOIL)
m.gasConstantR = Param(initialize=GAS_CONSTANT)
m.massFlow = Param(initialize=MASS_FLOW)
m.pipeDiameter = Param(initialize=PIPE_DIAMETER)
m.crossSectionalArea = Param(initialize=m.pi * m.pipeDiameter**2 / 4)
m.alpha = Param(initialize=3.52)
m.beta = Param(initialize=-2.26)
m.gamma = Param(initialize=0.274)
m.delta = Param(initialize=-1.878)
m.e = Param(initialize=2.2)
m.d = Param(initialize=2.2)
##################################################################################
# Variables
##################################################################################
m.x = ContinuousSet(bounds=(start, end))
m.pressure = Var(m.x, bounds=pressure_bounds) #
m.dpressuredx = DerivativeVar(m.pressure, wrt=m.x, initialize=0, bounds=(-100, 100))
m.temperature = Var(m.x, bounds=temperature_bounds) #
m.dtemperaturedx = DerivativeVar(m.temperature, wrt=m.x, initialize=0, bounds=(-100, 100))
m.density = Var(m.x, bounds=density_bounds)
m.ddensitydx = DerivativeVar(m.density, wrt=m.x, initialize=0, bounds=(-100, 100))
m.z = Var(m.x, bounds=(-10, 10))
m.specificIsobaricHeatCapacity = Var(m.x)
m.idealMolarIsobaricHeatCapacity = Var(m.x, bounds=idealMolarIsobaricHeatCapacityBounds)
m.correctionIdealMolarIsobaricHeatCapacity = Var(m.x, bounds=correctionIdealMolarIsobaricHeatCapacityBounds)
m.mue_jt = Var(bounds=(-100, 100))
m.velocity = Var(m.x, bounds=velocity_bounds)
m.phiVar = Var()
##################################################################################
# Constraint rules
##################################################################################
# compressibility factor z and its derivatives; (pV/(nRT)=z
def z(p,
T,
p_c,
T_c,
formula=None):
p_r = p/p_c
T_r = T/T_c
if formula is None:
raise ValueError("formula must be equal to 'AGA' or 'Papay' or 'ideal'")
elif formula == 'AGA':
return 1 + 0.257 * p_r - 0.533 * p_r/T_r
elif formula == 'Papay':
return 1-3.52 * p_r * exp(-2.26 * T_r) + 0.247 * p_r**2 * exp(-1.878 * T_r)
elif formula == 'ideal':
return 1
else:
raise ValueError("formula must be equal to 'AGA' or 'Papay' or 'ideal'")
def dzdT(p,
T,
p_c,
T_c,
formula=None):
p_r = p/p_c
T_r = T/T_c
if formula is None:
raise ValueError("formula must be equal to 'AGA' or 'Papay'")
elif formula == 'AGA':
return 0.533 * p/p_c * T_c * 1/T**2
elif formula == 'Papay':
return 3.52 * p_r * (2.26/T_c) * exp(-2.26 * T_r) + 0.247 * p_r**2 * (-1.878/T_c) * exp(-1.878 * T_r)
elif formula == 'ideal':
return 0
else:
raise ValueError("formula must be equal to 'AGA' or 'Papay' or 'ideal'")
def dzdp(p,
T,
p_c,
T_c,
formula=None):
p_r = p/p_c
T_r = T/T_c
if formula is None:
raise ValueError("formula must be equal to 'AGA' or 'Papay' or 'ideal'")
elif formula == 'AGA':
return 0.257 * 1/p_c - 0.533 * (1/p_c)/T_r
elif formula == 'Papay':
return -3.52 * 1/p_c * exp(-2.26 * T_r) + 0.274 * 1/(p_c**2) * 2 * p * exp(-1.878 * T_r)
elif formula == 'ideal':
return 0
else:
raise ValueError("formula must be equal to 'AGA' or 'Papay' or 'ideal'")
def make_c_compr(formula):
assert formula == 'AGA' or formula == 'Papay' or formula == 'ideal'
def _c_compr(z_var,
p,
T,
p_c,
T_c):
return z_var - z(p, T, p_c, T_c, formula=formula)
return _c_compr
_c_compr = make_c_compr(formula)
def _c_compr_rule(m, x):
return 0 == _c_compr(m.z[x],
m.pressure[x],
m.temperature[x],
m.criticalPressure,
m.criticalTemperature)
m.c_compr = Constraint(m.x, rule=_c_compr_rule)
# specific isobaric heat capacity: ideal + correction term
def _c_mhc_real(molarMass,
specificIsobaricHeatCapacity,
idealMolarIsobaricHeatCapacity,
correctionIdealMolarIsobaricHeatCapacity):
return molarMass * specificIsobaricHeatCapacity - (idealMolarIsobaricHeatCapacity +
correctionIdealMolarIsobaricHeatCapacity)
def _c_mhc_real_rule(m, x):
return 0 == _c_mhc_real(m.molarMass,
m.specificIsobaricHeatCapacity[x],
m.idealMolarIsobaricHeatCapacity[x],
m.correctionIdealMolarIsobaricHeatCapacity[x])
m.c_mhc_real = Constraint(m.x, rule=_c_mhc_real_rule)
# _c_mhc_ideal_Shomate
def _c_mhc_ideal_Shomate(idealMolarIsobaricHeatCapacity, A, B, C, D, E, T):
return idealMolarIsobaricHeatCapacity - (A + B * (T/1000) + C * (T/1000)**2 + D * (T/1000)**3 + E/(T/1000)**2)
def _c_mhc_ideal_Shomate_rule(m, x):
return 0 == _c_mhc_ideal_Shomate(m.idealMolarIsobaricHeatCapacity[x],
gas.SHOMATE_PARAMETERS.A,
gas.SHOMATE_PARAMETERS.B,
gas.SHOMATE_PARAMETERS.C,
gas.SHOMATE_PARAMETERS.D,
gas.SHOMATE_PARAMETERS.E,
m.temperature[x])
m.c_mhc_ideal_Shomate = Constraint(m.x, rule=_c_mhc_ideal_Shomate_rule)
# _c_mhc_corr
def make_c_mhc_corr(formula):
assert formula == 'AGA' or formula == 'Papay' or formula == 'ideal'
if formula == 'AGA':
def _c_mhc_corr(correctionIdealMolarIsobaricHeatCapacity, alpha, beta, gamma, delta, p, T, p_c, T_c, R):
return correctionIdealMolarIsobaricHeatCapacity
elif formula == 'Papay':
def _c_mhc_corr(correctionIdealMolarIsobaricHeatCapacity, alpha, beta, gamma, delta, p, T, p_c, T_c, R):
# m.alpha = 3.52
# m.beta = -2.26
# m.gamma = 0.274
# m.delta = -1.878
p_r = p/p_c
T_r = T/T_c
return correctionIdealMolarIsobaricHeatCapacity + R * (
(gamma * delta + 0.5 * gamma * delta**2 * T_r) * p_r**2 * T_r * exp(delta * T_r) -
(2 * alpha * beta + alpha * beta**2 * T_r) * p_r * T_r * exp(beta * T_r))
elif formula == 'ideal':
def _c_mhc_corr(correctionIdealMolarIsobaricHeatCapacity, alpha, beta, gamma, delta, p, T, p_c, T_c, R):
return correctionIdealMolarIsobaricHeatCapacity
return _c_mhc_corr
_c_mhc_corr = make_c_mhc_corr(formula)
def _c_mhc_corr_rule(m, x):
return 0 == _c_mhc_corr(m.correctionIdealMolarIsobaricHeatCapacity[x],
m.alpha,
m.beta,
m.gamma,
m.delta,
m.pressure[x],
m.temperature[x],
m.criticalPressure,
m.criticalTemperature,
m.gasConstantR)
m.c_mhc_corr = Constraint(m.x, rule=_c_mhc_corr_rule)
# equation of state
def _c_eos(p, T, rho, molarMass, R, z):
return rho * z * R * T - p * molarMass
def _c_eos_rule(m, x):
return 0 == _c_eos(m.pressure[x],
m.temperature[x],
m.density[x],
m.molarMass,
m.gasConstantR,
m.z[x])
m.c_eos = Constraint(m.x, rule=_c_eos_rule)
# flow velocity equation
def _c_vel_flow(q, v, rho, A):
return A * rho * v - q
def _c_vel_flow_rule(m, x):
return 0 == _c_vel_flow(m.massFlow,
m.velocity[x],
m.density[x],
m.crossSectionalArea)
m.c_vel_flow = Constraint(m.x, rule=_c_vel_flow_rule)
# a smooth reformulation of the flow term with friction: lambda(q)|q|q (=phi)
def _c_friction(phi, q, k, D, e, d, A, eta):
beta = k/(3.71 * D)
lambda_slant = 1/(2*log10(beta))**2
alpha = 2.51 * A * eta / D
delta = 2 * alpha/(beta*log(10))
b = 2 * delta
c = (log(beta) + 1) * delta**2 - (e**2 / 2)
root1 = sqrt(q**2 + e**2)
root2 = sqrt(q**2 + d**2)
return phi - lambda_slant * (root1 + b + c/root2) * q
def _c_friction_rule(m):
return 0 == _c_friction(m.phiVar,
m.massFlow,
m.innerPipeRoughness,
m.pipeDiameter,
m.e,
m.d,
m.crossSectionalArea,
m.dynamicViscosity)
m.c_friction = Constraint(rule=_c_friction_rule)
# energy balance
def _diffeq_energy(q, specificIsobaricHeatCapacity, dTdx, T, rho, z, dzdT, dpdx, g, s, pi, D, c_HT, T_soil):
return q * specificIsobaricHeatCapacity * dTdx - (q * T / (rho * z) * dzdT * dpdx) + (q * g * s) + (pi * D * c_HT * (T - T_soil))
def _diffeq_energy_rule(m, x):
# if x == start:
# return Constraint.Skip
return 0 == _diffeq_energy(m.massFlow,
m.specificIsobaricHeatCapacity[x],
m.dtemperaturedx[x],
m.temperature[x],
m.density[x],
m.z[x],
dzdT(m.pressure[x],
m.temperature[x],
m.criticalPressure,
m.criticalTemperature,
formula=formula),
m.dpressuredx[x],
m.gravitationalAcceleration,
m.pipeSlope,
m.pi,
m.pipeDiameter,
m.c_HT,
m.temperatureSoil)
m.diffeq_energy = Constraint(m.x, rule=_diffeq_energy_rule)
# momentum balance
def _diffeq_momentum(rho, dpdx, q, A, drhodx, g, s, phi, D):
return rho * dpdx - q**2 / (A**2) * drhodx / rho + g * rho**2 * s + phi / (2 * A**2 * D)
def _diffeq_momentum_rule(m, x):
# if x == start:
# return Constraint.Skip
return 0 == _diffeq_momentum(m.density[x],
m.dpressuredx[x],
m.massFlow,
m.crossSectionalArea,
m.ddensitydx[x],
m.gravitationalAcceleration,
m.pipeSlope,
m.phiVar,
m.pipeDiameter)
m.diffeq_momentum = Constraint(m.x, rule=_diffeq_momentum_rule)
##################################################################################
# Discretization
##################################################################################
discretizer = TransformationFactory('dae.finite_difference')
discretizer.apply_to(m, nfe=60, wrt=m.x, scheme='BACKWARD')
##################################################################################
# Initial conditions
##################################################################################
m.pressure[start].fix(PRESSURE)
m.temperature[start].fix(TEMPERATURE)
##################################################################################
# Objective
##################################################################################
# constant
m.obj = Objective(expr=1)
m.pprint()
##################################################################################
# Solve
##################################################################################
solver = SolverFactory('scip')
# solver = SolverFactory('scip', executable="C:/Users/t.triesch/Desktop/scipampl-7.0.0.win.x86_64.intel.opt.spx2.exe")
results = solver.solve(m, tee=True, logfile="pipe.log")
##################################################################################
# Plot
##################################################################################
distance = [i/1000 for i in list(m.x)]
p = [value(m.pressure[x])/1e6 for x in m.x]
t = [value(m.temperature[x]) for x in m.x]
rho = [value(m.density[x]) for x in m.x]
v = [value(m.velocity[x]) for x in m.x]
fig = plt.figure()
gs = fig.add_gridspec(4, hspace=0.5)
axs = gs.subplots(sharex=True)
fig.suptitle('p[start] = {0} [MPa], p[end] = {1} [MPa],\n T[start]= {2} [K],\n massFlow[:]= {3} [kg/s],\n total length: {4} m'.format(
p[0], p[-1], t[0], m.massFlow.value, PIPE_LENGTH))
axs[0].plot(distance, p, '-')
axs[0].set(ylabel='p [MPa]')
axs[0].set_ylim([0, 10])
axs[0].grid()
axs[0].set_yticks([i for i in range(0, 11)])
axs[1].plot(distance, t, '-')
axs[1].set(ylabel='T [K]')
axs[1].set_ylim([250, 350])
axs[1].grid()
axs[2].plot(distance, rho, '-')
axs[2].set(ylabel='rho [kg/m^3]')
axs[2].grid()
axs[3].plot(distance, v, '-')
axs[3].set(ylabel='v [m/s]')
axs[3].grid()
for ax in axs.flat:
ax.set(xlabel='distance [km]')
plt.show()
Related
plt.quiver() plots dots instead of arrows
I am trying to draw a vector field with two ordinary differential equations using plt.quiver, but in some parts of the vector field, it shows dots not arrows. I don't know what these dots mean and how to change it to arrow. I would really appreciate if someone helps me. My result is here. MY VECTOR PLOT and what i expected to get is here. I used mathematica to get this. EXPECTED RESULT import numpy as np import matplotlib.pyplot as plt from scipy.integrate import solve_ivp from sympy import * from sympy.solvers import solve from sympy.abc import x ######## Parameters and functions ############################################### A = 5; b = 0.6; theta = 0.7; Lambda = 1; rho = 0.9; eta = 0.3; B = 2; alpha = 1; i = 0.1; uppergamma = 1.4; lowergamma = 0.4; delta = 1; N = 1 def u(y): out = A*y**b return out def up(y): out = A*b*y**(b-1) return out def F(y): func = Piecewise((1, x>uppergamma), (0, x<lowergamma), ((x - lowergamma)/(uppergamma - lowergamma), True) ) out = func.subs(x,y) if type(y) == float: out = float(out) return out F_vec = np.vectorize(F) def integrate_F(y): func = Piecewise((0, x<lowergamma), ( x-uppergamma + 0.5, x>uppergamma), (0.5*(x-lowergamma)**2 , True)) out = func.subs(x,y) if type(y) == float: out = float(out) return out integrate_F_vec = np.vectorize(integrate_F) def findy(i,n): y = Symbol('y') sol = solve(theta*(up(y)-1)/((1-theta)*up(y)+theta) - i/(alpha*n), y) if len(sol) == 0: out = 0 else: out = float(sol[0]) return out findy_vec = np.vectorize(findy) def niso(gamma): out = max(0, N*Lambda*F_vec(gamma)/(delta+Lambda*F_vec(gamma))) return out def gammaiso(i,n): g = Symbol('g') sol = solve((rho+delta)*g + Lambda*integrate_F(g) - alpha*(1-theta)*(u(findy(i,n))-findy(i,n)), g) if len(sol) == 0: out = 0 else: out = float(sol[0]) return out ######################################################################### ###### Plot a vector field ######################### n = np.linspace(0.01, 0.6, 20) g = np.linspace(0.01, 1.5, 20) nn, gg = np.meshgrid(n,g) ndot = (N-nn)*Lambda*F_vec(gg) - delta*nn gdot = (rho+delta)*gg + Lambda*integrate_F_vec(gg) - alpha*(1-theta)*(u(findy_vec(i,nn))-findy_vec(i,nn)) ndot = ndot.astype('float') gdot = gdot.astype('float') plt.figure(figsize=(5*1.2,7.5*1.2)) plt.plot(ngrid1, gamma_grid1) plt.plot(ngrid2, gamma_grid2) plt.grid(True) plt.xlim((0, 0.6)) plt.quiver(nn,gg,ndot,gdot, color='blue', headwidth= 6, minlength = 3)
Romberg doesn't work with my function i python
i have a problem with my Code. Both Codes work fine seperated, but if I combine them i get the 'float objekt is not callable' error in line 111, 97, 87, 105. I am not a programmer (physicist) so i would apreiate your help. I beleave it is probably a stupid mistake. Here comes the Code, if you need additional information, just ask. Thanks. import numpy import matplotlib.pyplot as plt def V_eff(r,m,l): GM = 3.9860042e14 return -GM*m/r+l**2/(2*m*r**2) def EminusVeff(r,m,l,E): return E-V_eff(r,m,l) E = -1.2e10 m = 1000 l1 = 68.8e12 l2 = 57.3e12 l3 = 81.35e12 xmin = 1 xmax = 4e7 xdata = numpy.linspace(xmin,xmax,1000) plt.plot(xdata, -EminusVeff(xdata, 1000, l3, E), label='{0:.3e}'.format(l3)) plt.plot(xdata, -EminusVeff(xdata, 1000, l1, E), label='{0:.3e}'.format(l1)) plt.plot(xdata, -EminusVeff(xdata, 1000, l2, E), label='{0:.3e}'.format(l2)) plt.xlabel("r") plt.ylabel(r'$V_\mathrm{eff} - E$') plt.ylim(-0.14e11,0.2e11) plt.xlim(0.3e7,4e7) plt.legend(title="L") plt.hlines(0, xmin, xmax, lw=0.5) def regulaFalsi(func, x0, x1, args=()): epsilon = 1 maxIterationen = 100 iterationen = 0 xArray = numpy.array([]) y0 = func(x0, *args) y1 = func(x1, *args) if (y0*y1 > 0): return numpy.nan, -1 if (x0 > x1): x2 = x0 x0 = x1 x1 = x2 x2 = (x0*func(x1, *args) - x1*func(x0, *args))/(func(x1, *args) - func(x0, *args)) xArray = numpy.append(xArray, x1) xArray = numpy.append(xArray, x2) while (abs(func(x2, *args)) >= epsilon): y0 = func(x0, *args) y2 = func(x2, *args) if (y0*y2 > 0): x0 = x2 else: x1 = x2 x2 = (x0*func(x1, *args) - x1*func(x0, *args))/(func(x1, *args) - func(x0, *args)) iterationen += 1 if (iterationen > maxIterationen): return x2, -1 xArray = numpy.append(xArray, x2) return xArray[-1], iterationen def r_min_max_analytisch(m,l,E): GM = 3.9860042e14 p = (GM*m)/(E) q = - l**2/(2*E*m) r1 = -p/2-numpy.sqrt((p/2)**2 - q) r2 = -p/2+numpy.sqrt((p/2)**2 - q) if r1 < r2: return r1,r2 else: return r2,r1 print("l1 analytisch: ", '{0:.0f} {1:.0f}'.format(*r_min_max_analytisch(m,l1,E))) print("l1 numerisch : ",'{0:.0f}'.format(*regulaFalsi(EminusVeff, 7e6, 8e6, (m,l1,E))), \ '{0:.0f}'.format(*regulaFalsi(EminusVeff, 2e7, 3e7, (m,l1,E)))) print("l2 analytisch: ", '{0:.0f} {1:.0f}'.format(*r_min_max_analytisch(m,l2,E))) print("l2 numerisch : ",'{0:.0f}'.format(*regulaFalsi(EminusVeff, 4e6, 9e6, (m,l2,E))), \ '{0:.0f}'.format(*regulaFalsi(EminusVeff, 2e7, 3e7, (m,l2,E)))) print("l3 analytisch: ", '{0:.0f} {1:.0f}'.format(*r_min_max_analytisch(m,l3,E))) print("l3 numerisch : ", '{0:.0f}'.format(*regulaFalsi(EminusVeff, 1.6e7, 1.65e7, (m,l3,E))), \ '{0:.0f}'.format(*regulaFalsi(EminusVeff, 1.65e7, 1.75e7, (m,l3,E)))) def Trapez(f, a, b, n): h = (b - a) / n x = a In = f(a) for k in range(1, n): x = x + h In += 2*f(x) return (In + f(b))*h*0.5 def romberg(f, a, b, p): I = np.zeros((p, p)) for i in range(0, p): I[i, 0] = Trapez(f, a, b, 2**i) for j in range(0, i): I[i, j+1] = (4**(j+1) * I[i, j] - I[i-1, j]) / (4**(j+1) - 1) print(I[i,0:i+1]) return I def func(r): phi = 1/(r**2*np.sqrt(((2*m)/l1**2)(EminusVeff(r,m,l1,E)))) return phi p_rows = 10 I = romberg(func, 7742086, 25474616, p_rows) solution = I[p_rows-1, p_rows-1] print(solution)
Take a look into your func method: phi = 1 / (r ** 2 * np.sqrt(((2 * m) / l1 ** 2)(EminusVeff(r, m, l1, E)))) # ^^ There are two expressions without an operator. This means: Call (the result of) (r ** 2 * np.sqrt(((2 * m) / l1 ** 2) with the argument EminusVeff(r, m, l1, E). Probably you want to multiply here, for that you have to add the * explicitly.
Surge in energy at start of N-body simulation
I am trying to use an n-body simulation to simulate the collapse of a globular cluster, starting from a point where the bodies all have 0 initial velocities generated in random positions of a sphere of a fixed radius and I am investigating the time taken to form an equilibrium system. However, when running my code when the particles initially come close together there is a large surge in potential energy. Is there a way to avoid this? I am using the leapfrog approximation to calculate subsequent velocities and positions of the particles. initial conditions sun_mass = 1.989e30 N = 50 mass = 25 * sun_mass M = np.full([N],mass) R = 3.086e+16 # 1pc epsilon = 0.1 * R collision_radius = 7e8 V = np.zeros([N,3]) P = np.zeros([N,3]) t = 50000000 * 365 * 24 * 60 * 60 dt = 18000000 * 24 * 60 * 60 print(t/dt) np.random.seed(54321) for i in range(N): #M[i] = np.random.uniform(sun_mass, 100*sun_mass, 1) phi = np.random.uniform(0,(2*np.pi)) costheta = np.random.uniform(-1,1) u = np.random.uniform(0,1) theta = np.arccos( costheta ) r = R * (u) **(1/3) x = r * np.sin( theta) * np.cos( phi ) y = r * np.sin( theta) * np.sin( phi ) z = r * np.cos( theta ) P[i] = (x,y,z) code to run programme: def programe(position, mass, velocity, softening, time, dt, R, collision_radius): #print(len(mass)) no_of_time_steps = (round(time/dt)) #all_positions = np.full((no_of_time_steps, len(mass), 3), 0.0) all_positions = [] all_velocities = [] #print(all_positions) #print(len(all_positions[0])) kinetic_energy = [] potential_energy = [] total_energy = [] #previous_velocity = calc_previous_half_velocity(velocity, calc_acceleration(position, mass, softening), dt) for i in range(no_of_time_steps): position, mass, velocity = detect_collisions(position, mass, velocity, collision_radius) #all_positions[i] = position all_positions.append(position) all_velocities.append(velocity) 'graph' plots = np.round(np.linspace(0,no_of_time_steps,num=500)) for k in range(len(plots)): if i == plots[k]: print("test") #print(i) graph(position, mass, R, i, dt, k) 'energies' kinetic_energy.append(calc_kinetic_energy(velocity, mass)) potential_energy.append(calc_potential_energy(position, mass)) total_energy.append(calc_total_energy(position, velocity, mass)) 'leap frog' velocity = calc_next_v_half(position, mass, velocity, softening, dt) position = calc_next_position(position, mass, velocity, dt) velocity = calc_next_v_half(position, mass, velocity, softening, dt) #columns_to_delete = len(all_velocities) #print(no_of_time_steps) #print(len(kinetic_energy), len(potential_energy), len(total_energy)) all_positions = np.array(all_positions) all_velocities = np.array(all_velocities) #print(all_positions) graphing(all_positions, all_velocities, mass, time, dt, kinetic_energy, potential_energy, total_energy, no_of_time_steps, R) #print(len(mass)) return(all_positions, all_velocities, kinetic_energy, potential_energy, total_energy) leapfrog functions: 'LeapFrog functions' 'Acceleration Calculation' def calc_acceleration(position, mass, softening): G = 6.67 * 10**(-11) N = position.shape[0] # N = number of rows in particle_positions array acceleration = np.zeros([N,3]) #print(N) for i in range(N): #print(i) for j in range(N): if i != j: #print("j", j) dx = position[i,0] - position[j,0] dy = position[i,1] - position[j,1] dz = position[i,2] - position[j,2] #print(dx,dy,dz) inv_r3 = ((dx**2 + dy**2 + dz**2 + softening**2)**(-1.5)) acceleration[i,0] += - G * mass[j] * dx * inv_r3 acceleration[i,1] += - G * mass[j] * dy * inv_r3 acceleration[i,2] += - G * mass[j] * dz * inv_r3 return(acceleration) #, print(acceleration)) def calc_previous_half_velocity(velocity, acceleration, dt): previous_velocity = np.zero_like(velocity) previous_velocity = velocity - acceleration * dt/2 return(previous_velocity) def calc_next_v_half(position, mass, velocity, softening, dt): half_velocity = np.zeros_like(velocity) half_velocity = velocity + calc_acceleration(position, mass, softening) * dt/2 return(half_velocity) def calc_next_velocity(position, mass, velocity, softening, dt): next_velocity = np.zeros_like(velocity) next_velocity = velocity + calc_acceleration(position, mass, softening) * dt return(next_velocity) def calc_next_position(position, mass, velocity, dt): next_position = np.zeros_like(position) next_position = position + velocity * dt return(next_position) other functions used: def calc_CoM(position, mass): sumMR = np.zeros(3) sumM = 0.0 position = np.array(position) for i in range(len(mass)): sumM += mass[i] sumMR += mass[i] * position[i] return(sumMR / sumM) def calc_total_mass2(mass): total_mass = 0.0 print((mass[0])) for i in range(len(mass)): total_mass += mass[i] return(total_mass) def calc_total_mass(mass): total_mass = sum(mass) return(total_mass) def calc_CoM_seperation(position, mass, i): new_mass = np.array(mass) new_pos = np.array(position) new_mass[i] = 0.0 new_pos[i] = 0.0 position = np.array(position) r = np.linalg.norm(calc_CoM(new_pos, new_mass) - position[i]) return(r) def calc_seperation(p1, p2): return np.linalg.norm(p1-p2)
Adding and printing items, using lists using python
So my problem seems quite trivial, but I'm new to python and am writing a simple program that calculates the reactions of a beam. My program does that successfully, but now I want to expand the capabilities to being able to plot the shear and bending moment diagrams along each beam. My thought process is to use a list and add the shear values (for now) to that list, in increments that divides the beam into 100 segments. Afterwards I want to be able to retrieve them and use these values to plot them. class beam: def __init__(self, emod, i, length): self.emod = emod self.i = i self.length = length def A(self, a, p): # Calculate reaction at A return p * (self.length - a) / self.length def B(self, a, p): # Calculate reaction at B return p * a / self.length def Mc(self, a, p): # Calculate moment at C return p * a * (self.length - a) / self.length def delc(self, a, p): return p * a * a * (self.length - a) ** 2 / 3 / self.emod / self.i / self.length def delx(self, x, a, p): beta = (self.length - a) / self.length delta = x / self.length return p * self.length * self.length * (self.length - a) * delta * ( 1 - beta * beta - delta * delta) / 6 / self.emod / self.i def delx1(self, x, a, p): alpha = a / self.length delta = x / self.length return p * self.length * self.length * a * delta * ( 1 - alpha * alpha - delta * delta) / 6 / self.emod / self.i def maxDisplacementCoords(self, a): return a * (1.0 / 3 + 2 * (self.length - a) / 3 / a) ** 0.5 class shearValues: # This is the class that adds the shear values to a list def __init__(self): self.values = [] def add_values(self, beam, a_val, p): j = float(0) v = beam.A(a_val, p) while j < beam.length: if j < a_val: continue elif j > a_val: continue elif j == a_val: v -= p self.values.append(v) j += beam.length / float(100) v += beam.B(a_val, p) self.values.append(v) if __name__ == '__main__': def inertia_x(h, w, t): iy1 = w * h * h * h / 12 iy2 = (w - t) * (h - 2 * t) ** 3 / 12 return iy1 - 2 * iy2 beam_list = [] beam1 = beam(200000000000, inertia_x(0.203, 0.133, 0.025), 5) beam2 = beam(200000000000, inertia_x(0.254, 0.146, 0.031), 5) beam3 = beam(200000000000, inertia_x(0.305, 0.102, 0.025), 5) beam_list.append(beam1) beam_list.append(beam2) beam_list.append(beam3) while True: my_beam = beam_list[1] beam_choice = input("Which beam would you like to evaluate? 1, 2 or 3 ") if beam_choice == '1': my_beam = beam_list[0] elif beam_choice == '2': my_beam = beam_list[1] elif beam_choice == '3': my_beam = beam_list[2] p = float(input("Enter the required load ")) a_val = float(input("Enter displacement of point load (origin at LHS) ")) print("Ay = {}".format(my_beam.A(a_val, p))) print("By = {}".format(my_beam.B(a_val, p))) print("Mc = {}".format(my_beam.Mc(a_val, p))) print("Displacement at C = {}".format(my_beam.delc(a_val, p))) displacement = input("Do you want to calculate a specific displacement? [Y]es or [N]o ").upper() if displacement not in 'YN' or len(displacement) != 1: print("Not a valid option") continue if displacement == 'Y': x = float(input("Enter location on beam to calculate displacement (origin on LHS) ")) if x < a_val: print("Displacement at {} = {}".format(x, my_beam.delx(x, a_val, p))) elif x > a_val: print("Displacement at {} = {}".format(x, my_beam.delx1(my_beam.length - x, a_val, p))) elif x == displacement: print("Displacement at {} = {}".format(x, my_beam.delc(a_val, p))) elif displacement == 'N': continue print("Max displacement is at {} and is = {}".format(my_beam.maxDisplacementCoords(a_val), my_beam.delx(my_beam.maxDisplacementCoords(a_val), a_val, p))) # The code doesn't execute the way it is intended from here sv = shearValues() sv.add_values(my_beam,a_val,p) Currently it seems as if I have created an infinite loop. As you can see, the code is not optimized at all but any help would be appreciated. And the calculations are correct.
NoneType error with Python class and function
Despite my function returning an array, I get an TypeError: 'NoneType' object is not callable error. I first define classes, and then insert the function. I'm relatively new to Python, and would appreciate any help/comments. The Classes are: from scipy import array, dot, zeros, empty from scipy.optimize import brentq from numpy import * from numpy.random import uniform from time import time # from mpi4py import MPI class UtilTheory: """ """ def utility(self, other): raise NotImplementedError("You need to implement method 'utility' " "in the child class.") def demand(self, p): raise NotImplementedError("You need to implement method 'demand' " "in the child class.") def excessDemand(self, p): p = array(p) return self.demand(p) - self.endowment def indUtility(self, p): x = self.demand(p) return self.utility(x) def __add__(self, other): economy = Economy([self, other]) return economy def __radd__(self, other): economy = Economy([self] + other) def __rmul__(self, other): economy = Economy(other * [self]) return economy class Consumer(UtilTheory, object): """ Defines general features of a consumer """ def __init__(self, endowment=array([1,1]), alpha=0.5, rho=0.0): self.endowment = array(endowment) self.alpha = float(alpha) self.rho = rho self.sigma = 1.0 / (1.0 - rho) def __str__(self): return ('e=' + str(self.endowment) + ', alpha=' + str(self.alpha) + ', rho=' + str(self.rho)) def demand(self, p): endowment = self.endowment alpha = self.alpha sigma = self.sigma p = array(p) m = dot(endowment, p) x1 = ((alpha / p[0]) ** sigma * m / (alpha ** sigma * p[0] ** (1 - sigma) + (1 - alpha) ** sigma * p[1] ** (1 - sigma))) x2 = (((1.0 - alpha) / p[1]) ** sigma * m / (alpha ** sigma * p[0] ** (1 - sigma) + (1 - alpha) ** sigma * p[1] ** (1 - sigma))) return array([x1, x2]) def utility(self, x): if self.rho != 0: return ((self.alpha * x[0] ** self.rho + (1.0 - self.alpha) * x[1] ** self.rho) ** (1.0 / self.rho)) return x[0] ** self.alpha * x[1] ** (1.0 - self.alpha) class Economy: """ Consists of consumers """ def __init__(self, consumers): """ Consumers should be a list of consumers """ self.consumers = consumers def excessDemand(self, p): result = zeros(2) for consumer in self.consumers: result = result + consumer.excessDemand(p) return result def demand(self, p): result = zeros(2) for consumer in self.consumers: result = result + consumer.demand(p) return result def excessDemandGood0(self, p0): p = array([p0, 1.0 - p0]) result = 0 for consumer in self.consumers: result = result + consumer.excessDemand(p)[0] return result def __add__(self,other): try: return Economy(self.consumers + other.consumers) except: return Economy(self.consumers + [other]) def numEquilibria(self, n=100): # p = array([p0, 1 - p0]) q = linspace(0, 1, n) result = empty(len(q)) #print result for i, p0 in enumerate(q): a = self.excessDemandGood0(p0) #print a result[i] = a index = zeros(len(q)) for i in range(1, 2): if result[i] <= 0: index[i - 1] = 1 else: index[i - 1] = 0 for i in range(2, n - 1): test=result[i - 1] * result[i] #print test if test <= 0: index[i - 1] = 1 else: index[i - 1] = 0 for i in range(n - 2, n - 1): if result[i] > 0: index[i - 1] = 1 else: index[i - 1] = 0 count = sum(index) # print "The number of equilibria is" return count # print "Excess Demand funciton on the grid:" # print result # print "Index when excess demand goes from possitive to negative" # print index def __rmul__(self, other): economy = Economy(other * self.consumers) return economy def equilibrium(self, startbracket=None): def g(x): return self.excessDemandGood0(x) if startbracket == None: startbracket = [1e-10, 1-1e-10] eqPrice1 = brentq(g, startbracket[0], startbracket[1]) return array([eqPrice1, 1 - eqPrice1]) def __len__(self): return len(self.consumers) def __str__(self): resultString = 'Economy with ' + str(len(self)) + ' consumers.\n' for consumer in self.consumers: resultString = resultString + str(consumer) + '\n' return resultString I get the error when implementing the following stats() function which calls on randomEconEq(): def randomEcon(e1=[1, 0], e2=[0, 1], iterate_max=100): rho1 = random.uniform(-8, -1) rho2 = random.uniform(-8, -1) alpha1 = random.uniform(0, 1) alpha2 = random.uniform(0, 1) x = Consumer(endowment=e1, alpha=alpha1, rho=rho1) y = Consumer(endowment=e2, alpha=alpha2, rho=rho2) econ = Economy([x, y]) return econ def randomEconEq(iterate_max=100): iterate = 0 eq_vec = [] start = time() while iterate < iterate_max: iterate += 1 econ = randomEcon() equilibria = econ.numEquilibria() eq_vec.append(equilibria) # print eq_vec if (econ.numEquilibria() > 1): print "Number of multiple equilibria is " + \ str(econ.numEquilibria()) print str(econ) print str(eq_vec) end = time() totaltime = end - start #print('Total Time is ' + str(totaltime)) return eq_vec def stats(eq_vec, iterate_max): one_eq = zeros(len(eq_vec)) three_eq = zeros(len(eq_vec)) five_eq = zeros(len(eq_vec)) more_eq = zeros(len(eq_vec)) # print (eq_vec) for i in range(len(eq_vec)): if eq_vec[i] == 1: one_eq[i] = 1 if eq_vec[i] == 3: three_eq[i] = 1 if eq_vec[i] == 5: five_eq[i] = 1 if eq_vec[i] > 5: more_eq[i] = 1 Eq1 = sum(one_eq) Eq3 = sum(three_eq) Eq5 = sum(five_eq) EqMore = sum(more_eq) prob1 = float((Eq1 / iterate_max) * 100) prob3 = float((Eq3 / iterate_max) * 100) prob5 = float((Eq5 / iterate_max) * 100) probMore = float((EqMore/iterate_max) * 100) print ('The Vector of the number of equililbria is:' + str(eq_vec)) print ('Probability of 1 equilibrium is (percent) ' + str(prob1)) print ('Probability of 3 equilibria is (percent) ' + str(prob3)) print ('Probability of 5 equilibria is (percent) ' + str(prob5)) print ('Probability of 1 equilibria is (percent) ' + str(probMore)) eq_vec = randomEconEq(100) stats(eq_vec, 100) The error appears in the last two lines of code when implementing the function stats(). An example which creates the error is: stats(randomEconEq(100), 100) and the complete traceback is: >>> stats(randomEconEq(100), 100) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'NoneType' object is not callable