Python vestigial parameter and uncallable function - python

import numpy as np
from scipy.optimize import fsolve
from scipy.integrate import quad
import matplotlib.pyplot as plt
Rgas = 8.31446261815324 #Pa*m**3/mol*K
def Peng_Robinson_EOS(P,V,T,Tc,Pc,ω):
a = (1+(0.37464+1.54226*ω-0.26992*ω**2)*(1-(T/Tc)**(1/2)))**2*Rgas**2*Tc**2/Pc #Pa*m**3
b = 0.07780 * Rgas*Tc/Pc
return P + a/((V+(1-np.sqrt(2))*b)*(V+(1+np.sqrt(2)))) - Rgas*T/(V-b)
def PR_Psat(T,Tc,Pc,ω,V,Pguess = 100000):
def integral_diff (Pguess,T,Tc,Pc,ω,V):
def Psat_integrand (V,Pguess,T,Tc,Pc,ω):
integrand1 = fsolve(Peng_Robinson_EOS(Pguess,V,T,Tc,Pc,ω),Pguess)
integrand2 = Pguess
integrand = integrand1-integrand2
return integrand
Vl = fsolve(Psat_integrand(V,Pguess,T,Tc,Pc,ω),0)
Vv_guess = Rgas*T/Pguess
Vv = fsolve(Psat_integrand(V,Pguess,T,Tc,Pc,ω),Vv_guess)
Vinf_guess = (Vl + Vv)/2
Vinf = fsolve(Psat_integrand(V,Pguess,T,Tc,Pc,ω),Vinf_guess)
left = quad(Psat_integrand(V,Pguess,T,Tc,Pc,ω),Vl,Vinf)[0]
right = quad(Psat_integrand(V,Pguess,T,Tc,Pc,ω),Vinf,Vv)[0]
diff = left + right
return diff
Psat = fsolve(integral_diff(Pguess,T,Tc,Pc,ω,V),Pguess)
return Psat
There are two issues with this code.
1: in theory, PR_Psat should not depend on V, since all values of V used in calculation are found via fsolve. However, because Peng_Robinson_EOS depends on V, it Python won't let it be ignored in enclosing functions. Is there a way to eliminate the need to "specify" V?
from an earlier version (before V was a parameter of all functions), to demonstrate:
runfile('...', wdir='...')
Traceback (most recent call last):
File "<ipython-input-4-0875bc6411e8>", line 1, in <module>
runfile('...', wdir='...')
File "...\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
execfile(filename, namespace)
File "...\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "...", line 40, in <module>
print(PR_Psat(300,647.1,22055000,0.345))
File "...", line 37, in PR_Psat
Psat = fsolve(integral_diff(Pguess,T,Tc,Pc,ω),Pguess)
File "...", line 25, in integral_diff
Vl = fsolve(Psat_integrand(V,Pguess,T,Tc,Pc,ω),0)
NameError: name 'V' is not defined
2: It seems that Peng_Robinson is not being treated as a callable function, but rather as a float. I'm not sure what is causing this.
runfile('...', wdir='...')
Traceback (most recent call last):
File "<ipython-input-13-0875bc6411e8>", line 1, in <module>
runfile('...', wdir='...')
File "C:\Users\Spencer\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
execfile(filename, namespace)
File "...\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "...", line 42, in <module>
print(PR_Psat(300,647.1,22055000,0.345,1))
File "...", line 39, in PR_Psat
Psat = fsolve(integral_diff(Pguess,T,Tc,Pc,ω,V),Pguess)
File "...", line 27, in integral_diff
Vl = fsolve(Psat_integrand(V,Pguess,T,Tc,Pc,ω),0)
File "...", line 23, in Psat_integrand
integrand1 = fsolve(Peng_Robinson_EOS(Pguess,V,T,Tc,Pc,ω),Pguess)
File "...\lib\site-packages\scipy\optimize\minpack.py", line 148, in fsolve
res = _root_hybr(func, x0, args, jac=fprime, **options)
File "...\lib\site-packages\scipy\optimize\minpack.py", line 214, in _root_hybr
shape, dtype = _check_func('fsolve', 'func', func, x0, args, n, (n,))
File "...\lib\site-packages\scipy\optimize\minpack.py", line 27, in _check_func
res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
TypeError: 'numpy.float64' object is not callable
In theory, Peng_Robinson_EOS should, if plotted as P(V) with constant T, produce a cubic regression. The goal of PR_Psat is to find the value of P for which the integrals between P and the cubic regression cancel. (Hence, integral_diff being plugged into fsolve)
To summarize the questions,
1) Is there a way to eliminate the need for V in PR_Psat?
2) Why is Peng_Robinson_EOS being flagged as an un-callable numpy.float64 object?

The problem was a syntax error. Arguments for fsolve and quad were placed wrong. To fix both problems, I moved the args to the back. For example,
incorrect:
Vv = fsolve(Psat_integrand(V,Pguess,T,Tc,Pc,ω),Vv_guess)
correct:
Vv = fsolve(Psat_integrand,Vv_guess,args=(Pguess,T,Tc,Pc,ω))
The reason Peng_Robinson_EOS is being called a numpy.float64 is because with the syntax of the code in the question the program is evaluated before being passed to the solver.
Also, with proper syntax, V is no longer an issue.
def PR_Psat(T,Tc,Pc,ω,Pguess = 1000):
def integral_diff (Pguess,T,Tc,Pc,ω):
def Psat_integrand (V,Pguess,T,Tc,Pc,ω):
integrand1 = fsolve(Peng_Robinson_EOS,Pguess,args=(V,T,Tc,Pc,ω))
integrand2 = Pguess
integrand = integrand1-integrand2
return integrand
Vl = fsolve(Psat_integrand,0,args=(Pguess,T,Tc,Pc,ω))
Vv_guess = Rgas*T/Pguess
Vv = fsolve(Psat_integrand,Vv_guess,args=(Pguess,T,Tc,Pc,ω))
Vinf_guess = (Vl + Vv)/2
Vinf = fsolve(Psat_integrand,Vinf_guess,args=(Pguess,T,Tc,Pc,ω))
left = quad(Psat_integrand,Vl,Vinf,args=(Pguess,T,Tc,Pc,ω))[0]
right = quad(Psat_integrand,Vinf,Vv,args=(Pguess,T,Tc,Pc,ω))[0]
diff = left + right
return diff
Psat = fsolve(integral_diff,Pguess,args=(T,Tc,Pc,ω))
return Psat

Related

Problem using writer.add_graph() on model class with multiple networks and methods which takes different inputs

I was trying to visualize a model, implemented as a Class, with several networks and methods, and each with different input. When I use writer.add_graph(), it returns NotImplementedError.
My model is for reinforcement learning, and it is something similar to the following pseudocode:
class MyModel():
init
self.network1 = torch.nn.DataParallel(some nn.Sequential)
self.network2 = torch.nn.DataParallel(some nn.Sequential)
self.network3 = torch.nn.DataParallel(some nn.Sequential)
(... and more networks)
def method1(self, x):
v, r, p, e = self.network1(x)
return v, r, p, e
def method2(self, e):
v, r, p, next_e = self.network2(e, a)
return v, r, p, next_e
def method3(self, x, y):
pa = self.network3(x, y)
return pa
# FYI: In training, loss = calculate_loss(array_of_vs, array_of_rs, array_of_ps, e, next_e, pa, a)
# but as far as I understand, the train part is independent of the writer.add_graph()
model_to_visualize = MyModel()
writer = SummaryWriter('some_dir')
dummyx = torch.ones(some_dims)
dummyy = torch.ones(some_dims)
dummye = torch.ones(some_dims)
dummya = torch.ones(some_dims)
dummydata = (dummyx, dummyy, dummye, dummya)
writer.add_graph(model_to_visualize, dummydata)
writer.close()
The question I wanted to ask is, is it actually not supported by writer.add_graph() to visualize these kind of structures?
If not, any recommendation on how I can do this?
For your information:
There is no error when I tried writer.add_graph(MyModel().network1, dummyx), but this is not the thing I planned. I wanted to visualize the overall flow of all data.
ray and DataParallel are used in the implementation. Not sure if it is related. I tried writer.add_graph in a separate script and the same error occurred.
Details of the error message:
Error occurs, No graph saved
Traceback (most recent call last):
File "<ipython-input-35-d95ce6585e68>", line 1, in <module>
runfile('/home/username/PybulletTest/auxs/testAddGraph/testAddGraph.py', wdir='/home/username/PybulletTest/auxs/testAddGraph')
File "/usr/lib/python3/dist-packages/spyder_kernels/customize/spydercustomize.py", line 827, in runfile
execfile(filename, namespace)
File "/usr/lib/python3/dist-packages/spyder_kernels/customize/spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/home/username/PybulletTest/auxs/testAddGraph/testAddGraph.py", line 196, in <module>
writer.add_graph(model_to_visualize, dummydata)
File "/usr/local/lib/python3.8/dist-packages/torch/utils/tensorboard/writer.py", line 724, in add_graph
self._get_file_writer().add_graph(graph(model, input_to_model, verbose))
File "/usr/local/lib/python3.8/dist-packages/torch/utils/tensorboard/_pytorch_graph.py", line 292, in graph
raise e
File "/usr/local/lib/python3.8/dist-packages/torch/utils/tensorboard/_pytorch_graph.py", line 286, in graph
trace = torch.jit.trace(model, args)
File "/usr/local/lib/python3.8/dist-packages/torch/jit/_trace.py", line 733, in trace
return trace_module(
File "/usr/local/lib/python3.8/dist-packages/torch/jit/_trace.py", line 934, in trace_module
module._c._create_method_from_trace(
File "/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py", line 725, in _call_impl
result = self._slow_forward(*input, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py", line 709, in _slow_forward
result = self.forward(*input, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py", line 175, in _forward_unimplemented
raise NotImplementedError

Is there any solution to "Result too large" in python?

This is a programm in python, using the libray pandas, to assign different values to a new column depending on the values of the rest of the data. It works with small data but for some reason, when i try to use the programm with big data, it fails with an error. I tried the library decimal but it does not work. I think the error is related with the size of the float, but I can't find a way to fix it. Thanks
Error:
runfile('C:/Users/Usuario/Documents/DOCUMENTOS Y DATOS/ESTUDIO/4. TFM/Task 1/TASK SIN FILTRADO/TASK 3.4 sf.py', wdir='C:/Users/Usuario/Documents/DOCUMENTOS Y DATOS/ESTUDIO/4. TFM/Task 1/TASK SIN FILTRADO')
Traceback (most recent call last):
File "<ipython-input-34-37348501d189>", line 1, in <module>
runfile('C:/Users/Usuario/Documents/DOCUMENTOS Y DATOS/ESTUDIO/4. TFM/Task 1/TASK SIN FILTRADO/TASK 3.4 sf.py', wdir='C:/Users/Usuario/Documents/DOCUMENTOS Y DATOS/ESTUDIO/4. TFM/Task 1/TASK SIN FILTRADO')
File "C:\Users\Usuario\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
execfile(filename, namespace)
File "C:\Users\Usuario\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/Usuario/Documents/DOCUMENTOS Y DATOS/ESTUDIO/4. TFM/Task 1/TASK SIN FILTRADO/TASK 3.4 sf.py", line 76, in <module>
table["Flow_pattern"] = table.apply(lambda x: flow_pattern(x["Fcoef"], x["Vcoef"]), axis=1)
File "C:\Users\Usuario\Anaconda3\lib\site-packages\pandas\core\frame.py", line 6913, in apply
return op.get_result()
File "C:\Users\Usuario\Anaconda3\lib\site-packages\pandas\core\apply.py", line 186, in get_result
return self.apply_standard()
File "C:\Users\Usuario\Anaconda3\lib\site-packages\pandas\core\apply.py", line 292, in apply_standard
self.apply_series_generator()
File "C:\Users\Usuario\Anaconda3\lib\site-packages\pandas\core\apply.py", line 321, in apply_series_generator
results[i] = self.f(v)
File "C:/Users/Usuario/Documents/DOCUMENTOS Y DATOS/ESTUDIO/4. TFM/Task 1/TASK SIN FILTRADO/TASK 3.4 sf.py", line 76, in <lambda>
table["Flow_pattern"] = table.apply(lambda x: flow_pattern(x["Fcoef"], x["Vcoef"]), axis=1)
File "C:/Users/Usuario/Documents/DOCUMENTOS Y DATOS/ESTUDIO/4. TFM/Task 1/TASK SIN FILTRADO/TASK 3.4 sf.py", line 35, in flow_pattern
fun=e**((Vcoef+59627)/8432.5)
OverflowError: (34, 'Result too large', 'occurred at index 206')
CODE:
import pandas as pd
e=2.71828182845904523536
table = pd.read_csv('Coef_Data_sf.csv', sep = ',', header = 0)
flowmap = pd.read_csv('flow_map.csv', sep = ',', header = 1)
flowmaptag = pd.read_csv('flow_map.csv', sep = ',', header = 0)
986
# X - F COEF Y - V COEF
# ANNU WISPY y = 8432,5*ln(x) - 59627
# CHURN SLUG y = 9,604ln(x) - 29,739
# BUbblY SLUG y = 462514x-1,29
def flow_pattern(Fcoef, Vcoef):
if Vcoef>100:
fun=e**((Vcoef+59627)/8432.5)
if Fcoef<fun:
return "Annular"
elif Fcoef>fun:
return "Wispy_annular"
else:
return "error1"
elif 48<Vcoef<100:
if Fcoef<5070:
return "Churn"
elif Fcoef>5070:
return "Bubbly"
elif 10<Vcoef<48:
fun1=e**((Vcoef+29.739)/9.604)
if Fcoef<fun1:
return "Churn"
elif fun1<Fcoef<5070:
return "Slug"
elif 5070<Fcoef:
return "Bubbly"
else:
return "error2"
elif Vcoef<10:
fun1=e**((Vcoef+29.739)/9.604)
fun2=e**((Vcoef+1.29)/462514)
if Fcoef<fun1:
return "Churn"
elif fun1<Fcoef<fun2:
return "Slug"
elif fun2<Fcoef:
return "Bubbly"
else:
return "error3"
else:
return "errorfin"
table["Flow_pattern"] = table.apply(lambda x: flow_pattern(x["Fcoef"], x["Vcoef"]), axis=1)
table.to_csv('Data_with_flowpattern_sf.csv')

why does this error happens:"Sliced assignment is only supported for variables"

I have a deep network using Keras and I need to apply cropping on the output of one layer and then send to the next layer. for this aim, I write the following code as a lambda layer:
def cropping_fillzero(img, rate=0.6): # Q = percentage
residual_shape = img.get_shape().as_list()
h, w = residual_shape[1:3]
blacked_pixels = int((rate) * (h*w))
ratio = int(np.floor(np.sqrt(blacked_pixels)))
# width = int(np.ceil(np.sqrt(blacked_pixels)))
x = np.random.randint(0, w - ratio)
y = np.random.randint(0, h - ratio)
cropingImg = img[y:y+ratio, x:x+ratio].assign(tf.zeros([ratio, ratio]))
return cropingImg
decoded_noise = layers.Lambda(cropping_fillzero, arguments={'rate':residual_cropRate}, name='residual_cropout_attack')(bncv11)
but it produces the following error and I do not know why?!
Traceback (most recent call last):
File "", line 1, in
runfile('E:/code_v28-7-19/CIFAR_los4x4convolvedw_5_cropAttack_RandomSize_Pad.py',
wdir='E:/code_v28-7-19')
File
"D:\software\Anaconda3\envs\py36\lib\site-packages\spyder_kernels\customize\spydercustomize.py",
line 704, in runfile
execfile(filename, namespace)
File
"D:\software\Anaconda3\envs\py36\lib\site-packages\spyder_kernels\customize\spydercustomize.py",
line 108, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File
"E:/code_v28-7-19/CIFAR_los4x4convolvedw_5_cropAttack_RandomSize_Pad.py",
line 143, in
decoded_noise = layers.Lambda(cropping_fillzero, arguments={'rate':residual_cropRate},
name='residual_cropout_attack')(bncv11)
File
"D:\software\Anaconda3\envs\py36\lib\site-packages\keras\engine\base_layer.py",
line 457, in call
output = self.call(inputs, **kwargs)
File
"D:\software\Anaconda3\envs\py36\lib\site-packages\keras\layers\core.py",
line 687, in call
return self.function(inputs, **arguments)
File
"E:/code_v28-7-19/CIFAR_los4x4convolvedw_5_cropAttack_RandomSize_Pad.py",
line 48, in cropping_fillzero
cropingImg = img[y:y+ratio, x:x+ratio].assign(tf.zeros([ratio, ratio]))
File
"D:\software\Anaconda3\envs\py36\lib\site-packages\tensorflow\python\ops\array_ops.py",
line 700, in assign
raise ValueError("Sliced assignment is only supported for variables")
ValueError: Sliced assignment is only supported for variables
could you please tell me how can I solve this error?
Thank you
h, w = residual_shape[1:3]
I'm not entirely sure what you're trying to do here, but Python interprets this as 'return between the 2nd element and the 4th'. Maybe you mean residual_shape[1], residual_shape[3]?
cropingImg = img[y:y+ratio, x:x+ratio].assign(tf.zeros([ratio, ratio]))
You are trying to use slice notation on a tensor. Slice notation may only be used on variables, as the error message says. In order to get the actual variable, try loading the previous layer output using tf.identity():
self.output = your_layer
self.output = tf.identity(self.output, name='output')
output = graph.get_tensor_by_name('output:0')

Bayesian analysis of chemical network

I am trying to do a simple reaction network and see the sensitivity of reaction rates k1 and k2. So my reaction goes A --> B --> C with k1 and k2, respectively.
import numpy as np
import pymc3 as pm
from matplotlib.pyplot import figure, scatter, legend, plot
from scipy.integrate import solve_ivp
from sys import exit
Nt = 11
time = 10
tt = np.linspace(0,time,Nt+1)
y0 = [1,0,0]
k1_0, k2_0 = 1, 0.5
def equat(t,c):
da_dt = -k1_0*c[0]
db_dt = k1_0*c[0] - k2_0*c[1]
dc_dt = k2_0*c[1]
return da_dt, db_dt, dc_dt
c_est = solve_ivp(equat, t_span = [0,time], t_eval = tt, y0 = y0)
niter = 10
with pm.Model() as reak_model:
k1 = pm.Normal('k1', mu = 0, sd = 100)
k2 = pm.Normal('k2', mu=0, sd=100, shape = 1)
sigma = pm.HalfNormal('sigma', sd=1)
def equat_2(t,c):
da_dt = -k1*c[0]
db_dt = k1*c[0] - k1*c[1]
dc_dt = k1*c[1]
return da_dt, db_dt, dc_dt
c = solve_ivp(equat_2, t_span = [0,time], t_eval = tt, y0 = y0)
likelihood = pm.Normal('y', mu=c.y, sd=sigma, observed=c_est.y)
trace = pm.sample(niter, chains = 1)
pm.traceplot(trace, varnames=['k1','k2'])
ValueError: setting an array element with a sequence.
Im getting this error. Since I am new to Bayesian, I am wondering if its something with the distributions?
Traceback (most recent call last):
File "<ipython-input-95-26ff8f25faea>", line 1, in <module>
runfile('/Daft regresion.py', wdir='/Final code')
File "/python3.7/site-packages/spyder_kernels/customize/spydercustomize.py", line 786, in runfile
execfile(filename, namespace)
File "python3.7/site-packages/spyder_kernels/customize/spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "Daft regression.py", line 53, in <module>
c = solve_ivp(equat_2, t_span = [0,time], t_eval = tt, y0 = y0)
File "/python3.7/site-packages/scipy/integrate/_ivp/ivp.py", line 454, in solve_ivp
solver = method(fun, t0, y0, tf, vectorized=vectorized, **options)
File "/python3.7/site-packages/scipy/integrate/_ivp/rk.py", line 99, in __init__
self.f = self.fun(self.t, self.y)
File "/python3.7/site-packages/scipy/integrate/_ivp/base.py", line 139, in fun
return self.fun_single(t, y)
File "/python3.7/site-packages/scipy/integrate/_ivp/base.py", line 21, in fun_wrapped
return np.asarray(fun(t, y), dtype=dtype)
File "/python3.7/site-packages/numpy/core/numeric.py", line 501, in asarray
return array(a, dtype, copy=False, order=order)
ValueError: setting an array element with a sequence.
Edit: Apparently I need to implement Theano package instead of solve_ivp. Still help appreciated.

How to implement div and grad in sympy?

Playing around a lot with sympy lately, I came up with the problem of calculating divergence and gradient for scalar and vector fields. What I want to do for now is solving the heat equation, i.e.
d/dt u(x,t) - a * lap(u(x,t)) = 0, with lap(x) = (div(grad(x))
on a scalar field. Since I could not find lap, div and grad in sympy.physics.mechanics, I tried to implement them by myself
from sympy import *
from sympy.physics.mechanics import *
o = ReferenceFrame('o')
x,y,z = symbols('x y z')
class div(Function):
#classmethod
def eval(cls, F):
return F.diff(x, o).dot(o.x)+F.diff(y, o).dot(o.y)+F.diff(z, o).dot(o.z)
class grad(Function):
#classmethod
def eval(cls, F):
return o.x * F.diff(x) + o.y * F.diff(y) + o.z * F.diff(z)
f = x**2 + y**3 + z*0.5
print grad(f)
print type(grad(f))
print div(grad(f))
unluckily, this gives
2*x*o.x + 3*y**2*o.y + 0.500000000000000*o.z
Traceback (most recent call last):
File "/home/fortmeier/Desktop/autokernel/autokernel/tools/GenerateCode.py", line 24, in <module>
print div(grad(f))
File "/usr/local/lib/python2.7/dist-packages/sympy/core/cache.py", line 93, in wrapper
r = func(*args, **kw_args)
File "/usr/local/lib/python2.7/dist-packages/sympy/core/function.py", line 368, in __new__
result = super(Function, cls).__new__(cls, *args, **options)
File "/usr/local/lib/python2.7/dist-packages/sympy/core/cache.py", line 93, in wrapper
r = func(*args, **kw_args)
File "/usr/local/lib/python2.7/dist-packages/sympy/core/function.py", line 188, in __new__
args = list(map(sympify, args))
File "/usr/local/lib/python2.7/dist-packages/sympy/core/sympify.py", line 313, in sympify
expr = parse_expr(a, local_dict=locals, transformations=transformations, evaluate=evaluate)
File "/usr/local/lib/python2.7/dist-packages/sympy/parsing/sympy_parser.py", line 757, in parse_expr
return eval_expr(code, local_dict, global_dict)
File "/usr/local/lib/python2.7/dist-packages/sympy/parsing/sympy_parser.py", line 691, in eval_expr
code, global_dict, local_dict) # take local objects in preference
File "<string>", line 1, in <module>
AttributeError: 'Symbol' object has no attribute 'x'
[Finished in 0.3s with exit code 1]
I know that I could do something with the galgebra module, but first I'd like to understand more whats going on here. The question thus is what am I missing?
This looks like a bug in SymPy. sympify(ReferenceFrame('o').x) does not work.

Categories