Romberg doesn't work with my function i python - 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.

Related

real gas, 1D pipe flow in Pyomo + SCIP failing through energy equation?

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()

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.

def __rmul__ -> TypeError: can't multiply sequence by non-int of type 'float'

Hi guys I'm new to python and I have an assignment based on Classes and I am getting an error with my code while I try to def__rmul__ . TypeError: can't multiply sequence by non-int of type 'float'. I would appreciate if someone can explain the error to this code. Thanks a lot ! I also cant upload the entire code for some reason it says : I need to write more ...
def cg(A, b, epsilon=1e-4):
# k = 0, kk = k + 1
xk = Vector([0.] * b.rows)
rk = b - A * xk
pk = 1. * rk
for k in range(b.rows):
alpha = (rk * rk) / (pk * (A * pk))
xkk = xk + alpha * pk
rkk = rk - alpha * (A * pk)
if rkk.norm() < epsilon:
break
beta = (rkk * rkk) / (rk * rk)
pkk = rkk + beta * pk
rk = rkk
pk = pkk
xk = xkk
return xkk
A = np.array([
[2., 3.],
[4., 5.],
])
b = np.array([1., 2.])
x = np.zeros(2)
for i in range(2):
for j in range(2):
x[i] += A[i][j] * b[j]
print(x)
x = np.dot(A, b)
print(x)
A = np.array([2., 3., 4., 5.])
b = np.array([1., 2.])
x = np.zeros(2)
for i in range(2):
for j in range(2):
x[i] += A[i * 2 + j] * b[j]
print(x)
A = np.array([2., 4., 3., 5.])
b = np.array([1., 2.])
x = np.zeros(2)
for i in range(2):
for j in range(2):
x[i] += A[j * 2 + i] * b[j]
print(x)
A = [
(0, 0, 2.),
(0, 1, 3.),
(1, 0, 4.),
(1, 1, 5.),
]
b = np.array([1., 2.])
x = np.zeros(2)
for i, j, aij in A:
x[i] += aij * b[j]
print(x)
class Vector(object):
def __init__(self, data):
self.data = data
self.rows = len(data)
def __mul__(self, other):
assert self.rows == other.rows
return sum([vi * vj for vi, vj in zip(self.data, other.data)])
def __rmul__(self, a):
data = [a * d for d in self.data]
return Vector(data)
def __add__(self, other):
assert self.rows == other.rows
return Vector([i + j for (i, j) in zip(self.data, other.data)])
def __sub__(self, other):
assert self.rows == other.rows
return Vector([i - j for (i, j) in zip(self.data, other.data)])
def norm(self):
return math.sqrt(self * self)
def __str__(self):
return '{0}'.format(self.data)
class Matrix(object):
def __init__(self, rows, cols):
self.rows = rows
self.cols = cols
def cg(self, b, epsilon=1e-4):
... # [1]
self.data = data
xk = Vector([0.] * b.rows)
rk = b - A * xk
pk = 1. * rk
for k in range(b.rows):
alpha = (rk * rk) / (pk * (A * pk))
xkk = xk + alpha * pk
rkk = rk - alpha * (A * pk)
if rkk.norm() < epsilon:
break
beta = (rkk * rkk) / (rk * rk)
pkk = rkk + beta * pk
rk = rkk
pk = pkk
xk = xkk
return xkk
#exit()
class FullMatrix(Matrix):
def __init__(self, rows, cols, data):
super().__init__(rows, cols)
self.data = data
def __mul__(self, v):
assert self.cols == v.rows
data = [0.] * self.rows
... # [2]
for i in range(self.rows):
for j in range(self.cols):
data[i] += self.data[i+j*self.rows]*v.data[j]
return Vector(data)
class SparseMatrix(Matrix):
def __init__(self, rows, cols, triplets):
super().__init__(rows, cols)
self.triplets = triplets
def __mul__(self, v):
assert self.cols == v.rows
data = [0.] * self.rows
... # [3]
for (i,j,d) in self.triplets:
data[i] += d*v.data[j]
return Vector(data)
if __name__ == "__main__":
sizes = [2 ** i for i in (2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)]
t_full = []
t_sparse = []
for N in sizes:
print('_' * 80)
print("size : {0}".format(N))
# b - vector
data = [0. for i in range(N)]
data[-1] = 10
b = Vector(data)
# Af - full matrix
data = [0.] * (N * N)
for i in range(N - 1):
data[i + N * i ] = 10.
data[i + 1 + N * i ] = -0.1
data[i + N * (i + 1)] = -0.1
data[N - 1 + N * (N - 1)] = 10.
Af = FullMatrix(N, N, data)
# solve
t0 = time.time()
#~ xf = cg(Af, b)
xf = Af.cg(b)
tf = time.time() - t0
t_full.append(tf)
print("full : time: {0:6.2f}s (x[-1] = {1:12.10g})".format(tf, xf.data[-1]))
# As - sparse
triplets = []
for i in range(N - 1):
triplets.append((i, i, 10.))
triplets.append((i + 1, i, -0.1))
triplets.append((i, i + 1, -0.1))
triplets.append((N - 1, N - 1, 10.))
As = SparseMatrix(N, N, triplets)
# solve
t0 = time.time()
#~ xs = cg(As, b)
xs = As.cg(b)
ts = time.time() - t0
t_sparse.append(ts)
print("sparse : time: {0:6.2f}s (x[-1] = {1:12.10g})".format(ts, xs.data[-1]))
# An - numpy
An = np.zeros((N, N))
for i in range(N - 1):
An[i, i] = 10
An[i + 1, i] = -0.1
An[i, i + 1] = -0.1
# solve
An[N - 1, N - 1] = 10.
t0 = time.time()
xn = np.linalg.solve(An, b.data)
tn = time.time() - t0
print("numpy : time: {0:6.2f}s (x[-1] = {1:12.10g})".format(tn, xn[-1]))
print()
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(sizes, t_full, 'b-o', label='full')
ax.plot(sizes, t_sparse, 'r-o', label='sparse')
ax.set_xlabel('size')
ax.set_ylabel('times [s]')
ax.grid()
ax.legend()
plt.show()

OverFlowError: math range error javaScript to python

I am trying to build an Action potential simulation (a graph of voltage relative to time, where the voltage values are obtained through numerically solving a couple of differential equiations). I have used the code from an online simulation of this in javaScript and am trying to translate it into python. However, due to the different ways in which python and java handle floats, I get an Overflowerror: math range error. Does anyone know how I can circumvent this in this specific situation? I am posting everything i've written and my error output:
import numpy as np
import math
import matplotlib.pyplot as plt
import random
class HH():
def __init__(self):
self.dt = 0.025
self.Capacitance = 1
self.GKMax = 36
self.GNaMax = 120
self.Gm = 0.3
self.EK = 12
self.ENa = 115
self.VRest = 10.613
self.V = 0
self.n = 0.32
self.m = 0.05
self.h = 0.60
self.INa = 0
self.IK = 0
self.Im = 0
self.Iinj = 0
self.tStop = 200
self.tInjStart = 25
self.tInjStop = 175
self.IDC = 0
self.IRand = 35
self.Itau = 1
#classmethod
def alphaN(cls,V):
if(V == 10):
return alphaN(V+0.001)
else:
a = (10-V)/(100 * (math.exp((10-V)/10) -1))
print("alphaN: ", a)
return a
#classmethod
def betaN(cls,V):
a = 0.125*math.exp(-V/80)
print("betaN: ", a)
return a
#classmethod
def alphaM(cls, V):
if (V == 25):
return alphaM(V+0.0001)
else:
a = (25 - V)/10 * (math.exp( (25-V)/10) - 1)
print("alphaM", a)
return (a)
#classmethod
def betaM(cls, V):
return 4 * math.exp(-V/18)
#classmethod
def alphaH(cls, V):
return 0.07 * math.exp(-V/20)
#classmethod
def betaH(cls, V):
return 1/(math.exp((30-V/10)+1))
def iteration(self):
aN = self.alphaN(self.V)
bN = self.betaN(self.V)
aM = self.alphaM(self.V)
bM = self.betaM(self.V)
aH = self.alphaH(self.V)
bH = self.betaH(self.V)
tauN = 1/(aN + bN)
print("tauN: ", tauN)
tauM = 1/(aM + bM)
print("tauM", tauM)
tauH = 1/(aH + bH)
print("tauH: ", tauH)
nInf = aN * tauN
print("nInf: ", nInf)
mInf = aM * tauM
print("mInf: ", mInf)
hInf = aH * tauH
print("hInf: ", hInf)
self.n += self.dt/ tauN * (nInf - self.n)
print("n: ", self.n)
self.m += self.dt/tauM * (mInf - self.m)
print("m: ", self.m)
self.h += self.dt/tauH * (hInf - self.h)
print("h: ", self.h)
self.IK = self.GKMax * self.n * self.n * self.n * self.n * (self.VRest - self.EK)
print("IK: ", self.IK)
self.INa = self.GNaMax * self.m * self.m * self.m * self.h * (self.VRest - self.ENa)
print("INa: ", self.INa)
self.Im = self.Gm * (self.VRest * self.V)
print("Im: ", self.Im)
self.V += self.dt/self.Capacitance * (self.INa + self.IK + self.Im + self.Iinj)
print("V: ", self.V)
print("nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn")
return self.V
if __name__ == '__main__':
hodgkinHuxley = HH()
V_vector = np.zeros(math.floor(hodgkinHuxley.tStop/hodgkinHuxley.dt)) #v_vector
Iinj_vector = np.zeros(math.floor(hodgkinHuxley.tStop/hodgkinHuxley.dt)) #stim_vector
n_vector = np.zeros(math.floor(hodgkinHuxley.tStop/hodgkinHuxley.dt))
m_vector = np.zeros(math.floor(hodgkinHuxley.tStop/hodgkinHuxley.dt))
h_vector = np.zeros(math.floor(hodgkinHuxley.tStop/hodgkinHuxley.dt))
plotSampleRate = math.ceil(hodgkinHuxley.tStop/2000/hodgkinHuxley.dt) #t_vector
print("plotsamplerate: ", plotSampleRate)
i = 0
t_vector = []
for t in range(0, hodgkinHuxley.tStop+1):
t= t+hodgkinHuxley.dt
if(math.floor(t)>hodgkinHuxley.tInjStart & math.ceil(t)<hodgkinHuxley.tInjStop):
rawInj = hodgkinHuxley.IDC + hodgkinHuxley.IRand * 2 * (random.random()-0.5)
else:
rawInj = 0
hodgkinHuxley.Iinj += hodgkinHuxley.dt/hodgkinHuxley.Itau * (rawInj - hodgkinHuxley.Iinj)
hodgkinHuxley.iteration()
counter = 0
if(i == plotSampleRate):
V_vector[counter] = hodgkinHuxley.V
Iinj_vector[counter] = hodgkinHuxley.Iinj
n_vector[counter] = hodgkinHuxley.n
m_vector[counter] = hodgkinHuxley.m
h_vector[counter] = hodgkinHuxley.h
i=0;
counter+=1
i+=1
Error:
plotsamplerate: 4
alphaN: 0.05819767068693265
betaN: 0.125
alphaM 27.956234901758684
tauN: 5.458584687514421
tauM 0.03129279788667988
tauH: 14.285714285707257
nInf: 0.3176769140606974
mInf: 0.8748288084532805
hInf: 0.9999999999995081
n: 0.31998936040167786
m: 0.7089605789167688
h: 0.6006999999999995
IK: -0.5235053389507994
INa: -2681.337959108097
Im: 0.0
V: -67.0465366111762
nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
alphaN: 0.00034742442109860416
betaN: 0.2889909708647963
alphaM 91515.37543280824
tauN: 3.456160731837547
tauM 1.0907358211913938e-05
tauH: 0.5000401950825147
nInf: 0.0012007546414823879
mInf: 0.9981909817434281
hInf: 1.0
n: 0.31768341581102577
m: 663.6339264765652
h: 0.6206633951393696
IK: -0.5085774931025618
INa: -2272320232559.0464
Im: -213.46946791632385
V: -56808005886.37157
nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
Traceback (most recent call last):
File "C:\Users\Huinqk 2.0\Documents\projects\python\tariq_neural networks\plotting function.py", line 131, in <module>
hodgkinHuxley.iteration()
File "C:\Users\Huinqk 2.0\Documents\projects\python\tariq_neural networks\plotting function.py", line 71, in iteration
aN = self.alphaN(self.V)
File "C:\Users\Huinqk 2.0\Documents\projects\python\tariq_neural networks\plotting function.py", line 38, in alphaN
a = (10-V)/(100 * (math.exp((10-V)/10) -1))
OverflowError: math range error
[Finished in 0.8s]
You can write an altered version of math.exp which will behave more like the javascript function.
def safe_exp(n):
try:
return math.exp(n)
except OverflowError:
return float('inf')
OverflowError: math range error mean that's math.exp((10-V)/10) slightly outside of the range of a double, so it causes an overflow...
You may expect that this number is infinite with:
try:
a = (10-V)/(100 * (math.exp((10-V)/10) -1))
except OverflowError:
a = (10-V)/(float('inf'))

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

Categories