Here is my code:
def twomasses(M1,M2,x1,x2,p,h,n):
global gamma
global m1
global m2
gamma = 1
m1 = M1
m2 = M2
x0_1 = [1, 2]
x0_2 = [4, 5]
p = 3
v1 = [0, p/m1]
v2 = [0, -p/m2]
def F(x1, x2):
Fa = ((gamma*m1*m2)/(la.norm((x2 - x1),2) ** 3))*(x2 - x1)
return Fa
def a1(f, m1):
a1 = f/m1
return a1
def a2(f, m2):
a2 = f/m2
return a2
def ruku_step(F, y, h): #first ruku step
k1 = F(y)
k2 = F(y + (h/2)*k1)
k3 = F(y + (h/2)*k2)
k4 = F(y + h*k3)
y = y + (h/6)*(k1 + 2*k2 + 2*k3 + k4)
return y
f = lambda y: np.array([y[2],y[3],a1(F(y[0],y[1]),m1),a2(F(y[0],y[1]),m2)])
y = list()
y.append(np.array([x0_1,x0_2, v1, v2]))
for i in range(0,n):
y.append(ruku_step(f, np.array(y[i]), h))
return y
y = twomasses(1,2,-1,2,5,.1, 50)
maxy = np.max([e[0:2,1] for e in y])
maxx = np.max([e[0:2,0] for e in y])
minx = np.min([e[0:2,0] for e in y])
miny = np.min([e[0:2,1] for e in y])
fig, ax = plt.subplots()
def animate(t):
plt.clf()
plt.scatter(y[t][0:2,0],y[t][0:2,1])
anim = FuncAnimation(fig, animate, interval=100, frames=100)
plt.show()
I want to animate the graph so that you can see the movement of the masses. I tried following How to animate a scatter plot? but it is quite complex and wouldnt run for me. This will refresh the graph each time new points are introduced, but I want them all within one graph.
lots of problems here: bad indent, linspace feeds floats and some parts of your code seem useless. but hey, it moves
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
from numpy import linalg as la
def twomasses(M1,M2,x1,x2,p,h,n):
global gamma
global m1
global m2
gamma = 1
m1 = M1
m2 = M2
x0_1 = [1, 2]
x0_2 = [4, 5]
p = 3
v1 = [0, p/m1]
v2 = [0, -p/m2]
def F(x1, x2):
Fa = ((gamma*m1*m2)/(la.norm((x2 - x1),2) ** 3))*(x2 - x1)
return Fa
def a1(f, m1):
a1 = f/m1
return a1
def a2(f, m2):
a2 = f/m2
return a2
def ruku_step(F, y, h): #first ruku step
k1 = F(y)
k2 = F(y + (h/2)*k1)
k3 = F(y + (h/2)*k2)
k4 = F(y + h*k3)
y = y + (h/6)*(k1 + 2*k2 + 2*k3 + k4)
return y
f = lambda y: np.array([y[2],y[3],a1(F(y[0],y[1]),m1),a2(F(y[0],y[1]),m2)])
y = list()
y.append(np.array([x0_1,x0_2, v1, v2]))
for i in range(0,n):
y.append(ruku_step(f, np.array(y[i]), h))
return y
y = twomasses(1,2,-1,2,5,.1, 50)
#~ print(y)
fig, ax = plt.subplots()
def animate(t):
xdata = y[t][0:2,0]
ydata = y[t][0:2,1]
#~ def update(frame):
#~ xdata.append(frame)
#~ ydata.append(frame)
ln.set_data(xdata, ydata)
return ln,
ln, = plt.plot([], [], 'bs', animated=True)
maxy = np.max([e[0:2,1] for e in y])
maxx = np.max([e[0:2,0] for e in y])
minx = np.min([e[0:2,0] for e in y])
miny = np.min([e[0:2,1] for e in y])
def init():
ax.set_xlim(minx-1, maxx+1)
ax.set_ylim(miny-1, maxy+1)
return ln,
ani =FuncAnimation(fig, animate, frames=np.arange(len(y)),
init_func=init, blit=True)
plt.show()
Related
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)
I created an algorithm to solve the TSP problem. I want to present the result in the form of a GIF that shows the distance traveled. I use line2d from the Matplotlib library for this purpose. Every time the car reaches the starting point, I want to change the color of the line. I am currently using the line2d.set_color () functions for this. Unfortunately, it causes a color change of the entire road. My goal is to change the color at any given moment while keeping the previous colors. Can you help me with this problem?
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import random
from gurobipy import Model, GRB, quicksum
from matplotlib import collections as mc
rnd = np.random
rnd.seed()
n = 20 # numbre of clients
xc = rnd.rand(n + 1) * 200
yc = rnd.rand(n + 1) * 100
xc[0] = 100
yc[0] = 50
N = [i for i in range(1, n + 1)]
V = [0] + N
A = [(i, j) for i in V for j in V if i != j]
c = {(i, j): np.hypot(xc[i] - xc[j], yc[i] - yc[j]) for i, j in A}
Q = 30
# q = {i: random.choice([-5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) for i in N}
# q = {i: random.choice([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) for i in N}
q = {i: rnd.randint(1, 10) for i in N}
# a = [['x', xc], ['y', yc], ['Capacity', q]]
# for i in range(len(a)) :
# for j in range(len(a[i])):
# print(a[i][j], end=" ")
# print()
mdl = Model('CVRP')
x = mdl.addVars(A, vtype=GRB.BINARY)
u = mdl.addVars(N, vtype=GRB.CONTINUOUS)
mdl.modelSense = GRB.MINIMIZE
mdl.setObjective(quicksum(x[i, j] * c[i, j] for i, j in A))
mdl.addConstrs(quicksum(x[i, j] for j in V if j != i) == 1 for i in N)
mdl.addConstrs(quicksum(x[i, j] for i in V if i != j) == 1 for j in N)
mdl.addConstrs((x[i, j] == 1) >> (u[i] + q[j] == u[j])
for i, j in A if i != 0 and j != 0)
mdl.addConstrs(u[i] >= q[i] for i in N)
mdl.addConstrs(u[i] <= Q for i in N)
mdl.Params.MIPGap = 0.1
mdl.Params.TimeLimit = 30 # seconds
mdl.optimize()
active_arcs = [a for a in A if x[a].x > 0.99]
final_arcs = []
roads = 0
while len(active_arcs) != 0:
temp_arcs = [active_arcs[0]]
for i, j in temp_arcs:
temp_j = j
i2 = 0
while temp_j != 0:
for i, j in active_arcs:
if temp_j == i and temp_j != 0:
temp_arcs.append(active_arcs[i2])
temp_j = j
i2 += 1
i2 = 0
i = 0
i2 = 0
while i < len(temp_arcs):
while i2 < len(active_arcs):
if temp_arcs[i] == active_arcs[i2]:
active_arcs.pop(i2)
i2 += 1
i += 1
i2 = 0
final_i = 0
while final_i < len(temp_arcs):
final_arcs.append(temp_arcs[final_i])
final_i += 1
temp_arcs.clear()
roads += 1
plt.plot(xc[0], yc[0], c='r', marker='s')
for i in N:
if q[i] > 0:
plt.scatter(xc[i], yc[i], c='b')
else:
plt.scatter(xc[i], yc[i], c='y')
plt.show()
print('Liczba wykonanych tras: ', roads)
# for i, j in final_arcs:
# plt.plot([xc[i], xc[j]], [yc[i], yc[j]], color, zorder=0)
# if j == 0:
# if len(colors_base) != 0:
# c = random.randint(0, len(colors_base) - 1)
# color = colors_base[c]
# colors_base.pop(c)
#
# plt.show()
fig, ax = plt.subplots()
ax.set_xlim(0, 200)
ax.set_ylim(0, 100)
x_data, y_data = [], []
ln1, ln2 = [], []
ln, = plt.plot([], [], zorder=0)
colors_base = ['r', 'cyan', 'black', 'orange', 'm', 'darkorchid', 'dimgray', 'indigo', 'lawngreen', 'darkred']
ln.set_color('g')
plt.plot(xc[0], yc[0], 'r', marker='s')
for i in N:
if q[i] > 0:
plt.scatter(xc[i], yc[i], c='b')
else:
plt.scatter(xc[i], yc[i], c='y')
tmp = 0
for i, j in final_arcs:
x_data_tmp = [xc[i], xc[j]]
y_data_tmp = [yc[i], yc[j]]
x_data.append(x_data_tmp)
y_data.append(y_data_tmp)
def update(p):
ln1.append(x_data[p])
ln2.append(y_data[p])
ln.set_data(ln1, ln2)
for i, j in final_arcs:
if yc[i] == 50 and y_data[p] == [yc[i], yc[j]] and p != 0:
if len(colors_base) != 0:
color = colors_base[0]
ln.set_color(color)
colors_base.pop(0)
return ln,
ani = FuncAnimation(fig, update, frames=len(final_arcs), interval=1000)
ani.save('animation.gif', fps=3)
# ani.save('animation.mp4', fps=3)
plt.show()
This is how the received gif looks like:
enter image description here
One possible solution:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import random
from gurobipy import Model, GRB, quicksum
from matplotlib import collections as mc
rnd = np.random
rnd.seed()
n = 20 # numbre of clients
xc = rnd.rand(n + 1) * 200
yc = rnd.rand(n + 1) * 100
xc[0] = 100
yc[0] = 50
N = [i for i in range(1, n + 1)]
V = [0] + N
A = [(i, j) for i in V for j in V if i != j]
c = {(i, j): np.hypot(xc[i] - xc[j], yc[i] - yc[j]) for i, j in A}
Q = 30
# q = {i: random.choice([-5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) for i in N}
# q = {i: random.choice([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) for i in N}
q = {i: rnd.randint(1, 10) for i in N}
mdl = Model('CVRP')
x = mdl.addVars(A, vtype=GRB.BINARY)
u = mdl.addVars(N, vtype=GRB.CONTINUOUS)
mdl.modelSense = GRB.MINIMIZE
mdl.setObjective(quicksum(x[i, j] * c[i, j] for i, j in A))
mdl.addConstrs(quicksum(x[i, j] for j in V if j != i) == 1 for i in N)
mdl.addConstrs(quicksum(x[i, j] for i in V if i != j) == 1 for j in N)
mdl.addConstrs((x[i, j] == 1) >> (u[i] + q[j] == u[j])
for i, j in A if i != 0 and j != 0)
mdl.addConstrs(u[i] >= q[i] for i in N)
mdl.addConstrs(u[i] <= Q for i in N)
mdl.Params.MIPGap = 0.1
mdl.Params.TimeLimit = 30 # seconds
mdl.optimize()
active_arcs = [a for a in A if x[a].x > 0.99]
final_arcs = []
roads = 0
while len(active_arcs) != 0:
temp_arcs = [active_arcs[0]]
for i, j in temp_arcs:
temp_j = j
i2 = 0
while temp_j != 0:
for i, j in active_arcs:
if temp_j == i and temp_j != 0:
temp_arcs.append(active_arcs[i2])
temp_j = j
i2 += 1
i2 = 0
i = 0
i2 = 0
while i < len(temp_arcs):
while i2 < len(active_arcs):
if temp_arcs[i] == active_arcs[i2]:
active_arcs.pop(i2)
i2 += 1
i += 1
i2 = 0
final_i = 0
while final_i < len(temp_arcs):
final_arcs.append(temp_arcs[final_i])
final_i += 1
temp_arcs.clear()
roads += 1
fig, ax = plt.subplots()
ax.set_xlim(0, 200)
ax.set_ylim(0, 100)
x_data, y_data = [], []
ln1, ln2 = [], []
ln, = ax.plot([], [], zorder=0)
colors_base = ['r', 'cyan', 'black', 'orange', 'm', 'darkorchid', 'dimgray', 'indigo', 'lawngreen', 'darkred']
ln.set_color('g')
plt.plot(xc[0], yc[0], 'r', marker='s')
for i in N:
if q[i] > 0:
plt.scatter(xc[i], yc[i], c='b')
else:
plt.scatter(xc[i], yc[i], c='y')
# precompute each line coordinates
lines_data = []
xd, yd = [], []
for i, j in final_arcs:
xd.append(xc[i])
yd.append(yc[i])
if j == 0:
xd.append(xc[0])
yd.append(yc[0])
lines_data.append([xd, yd])
xd, yd = [], []
# add empty lines with the specified colors
lines = []
for i in range(len(lines_data)):
lines.append(ax.plot([], [], color=colors_base[i])[0])
def update(p):
global current_line, up_to_point
# reset after each animation cycle is complete
if current_line > len(lines_data) - 1:
current_line = 0
for l in lines:
l.set_data([], [])
up_to_point += 1
xd, yd = lines_data[current_line]
lines[current_line].set_data(xd[:up_to_point], yd[:up_to_point])
if len(xd[:up_to_point]) == len(xd):
current_line += 1
up_to_point = 1
# index of the line to animate
current_line = 0
# draw the current line up to the point of this index
up_to_point = 1
ani = FuncAnimation(fig, update, frames=len(final_arcs), interval=1000)
ani.save('animation.gif', fps=3)
# ani.save('animation.mp4', fps=3)
plt.show()
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()
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.
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()