I have the below arrays and I need to calculate req[i] and JJ[i]. I'm getting allow the values zeros expect req[2] and req[8] but with wrong values. why that's happening?
the second issue is with the second line of JJ calculation ( JJ[i]= 0.00633*(2np.pimath.sqrt(kz[i]*ky[i])dx[i])/(pvt['muo'](np.log(req/well['rw']) + PP['s_h']))), it says invalid syntax. what wrong there?
these are the arrays I'm using:
and this is the code:
import numpy as np
#%% Importing modules Loading .yml/.yaml file
import yaml
import numpy as np
import matplotlib.pyplot as plt
import math
import scipy.special as sc
import pandas as pd
# Productivity index:
# i=len(n)
# req=np.zeros((n))
# JJ=np.zeros((n))
def Prod_index(res, pvt,num,well, PP, w, well_drc,i):
for i in range(n):
if well_drc== 'v':
req[i]= 0.28*math.sqrt(math.sqrt(ky[i]/kx[i])*dx[i]**2 + math.sqrt(kx[i]/ky[i])*dy[i]**2)/((ky[i]/kx[i])**0.25 + (kx[i]/ky[i])**0.25)
JJ[i]= 0.00633*(2*np.pi*math.sqrt(kx[i]*kz[i])*res['h'])/(pvt['muo']*(np.log(req[i]/well['rw']))+ PP['s_v'])
elif well_drc=='h' :
req[i]=0.28*math.sqrt(math.sqrt(kx[i]*ky[i])*dz[i]**2 + math.sqrt(kz[i]/ky[i]*dy[i]**2)/((ky[i]/kz[i])**0.25 + (kz[i]/ky[i])**0.25)
JJ[i]= 0.00633*(2*np.pi*math.sqrt(kz[i]*ky[i])*dx[i])/(pvt['muo']*(np.log(req/well['rw']) + PP['s_h']))
return req, JJ
Related
I am very new to programming, I am trying to code a function that prints the variance and mean based on a alpha I type in, or if I am not typing anything it defaults to 1.96. When I don't type anything it works fine, but when I type for example 1.625, it returns "TypeError: can't multiply sequence by non-int of type 'numpy.float64'"
Here is my code:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy import stats
def estimat(data):
var = np.var(data, ddof = 1)
forv = np.mean(data)
z = a*np.sqrt(var/len(data))
konf = {forv+z,forv-z}
return {"varians": var, "forventning,":forv, "konfidensintervall":konf}
x = stats.norm.rvs(0,1,100)
a = input("Enter your alpha: ") or 1.96
print (estimat(x))
You were almost there but had to change how your alpha is entered a little bit:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy import stats
def estimat(data):
var = np.var(data, ddof = 1)
forv = np.mean(data)
z = float(a)*np.sqrt(var/len(data))
konf = {forv+z,forv-z}
return {"varians": var, "forventning,":forv, "konfidensintervall":konf}
x = stats.norm.rvs(0,1,100)
print("Enter your alpha: ")
a = input()
if(a == ''):
a = 1.96
print (estimat(x))
# print (a)
The text should not be inside an input() so I placed above it with a print().
The # print(a) was there to check if the right entered/automated number was taken, I left it in the code so you can always check what happens if you alter your code.
edit
#Ignatius Reilly comment under the uestion is cleaner and more efficient
I have looked up questions with similar errors and thought I had followed the steps to initialize LinearRegression with the lines
linreg_mean_dif = LinearRegression().fit(X_train_dif, y_train_dif)
and
linreg_lag1 = LinearRegression().fit(X_train_lag1, y_train_lag1)
however, I am still being told LinearRegression is not callable. What seems to be the problem with my code?
import pandas as pd
import numpy as np
import math
from scipy.stats import binom
import timeit
import pandas_market_calendars as mcal
from datetime import datetime
from dateutil import parser as datetime_parser
from dateutil.tz import tzutc,gettz
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import tree_model as tree
Code here that imports data from tree_model and constructs the reversion_df dataframe
X_var1 = reversion_df['Difference from Mean'].values
y_var1 = reversion_df['Daily % Change'].values
X_var2 = reversion_df['Daily % Change Lag 1'][:len(reversion_df['Daily % Change Lag 1'])-1].values
y_var2 = reversion_df['Daily % Change'][:len(reversion_df['Daily % Change Lag 1'])-1].values
X_train_dif, X_test_dif, y_train_dif, y_test_dif = train_test_split(X_var1, y_var1, random_state = 0)
X_train_lag1, X_test_lag1, y_train_lag1, y_test_lag1 = train_test_split(X_var2, y_var2, random_state = 0)
X_train_dif = X_train_dif.reshape(-1, 1)
X_test_dif = X_test_dif.reshape(-1 , 1)
X_train_lag1 = X_train_lag1.reshape(-1, 1)
X_test_lag1 = X_test_lag1.reshape(-1 , 1)
linreg_mean_dif = LinearRegression().fit(X_train_dif, y_train_dif)
linreg_lag1 = LinearRegression().fit(X_train_lag1, y_train_lag1)
scores_train = (linreg_mean_dif.score(X_train_dif, y_train_dif), linreg_lag1(X_train_lag1, y_train_lag1))
print(scores_train)
You left a typo in the last line (right before the final print), where you wrote linreg_lag1(X_train_lag1, y_train_lag1). Replacing it with linreg_lag1.score(X_train_lag1, y_train_lag1) (which is probably what you meant) you should be fine
When I run my code sentence by sentence, no errors exist. However, when I check out the results of AA (bvp solution in my code), it displays that I solve this ODE group falsely.
How can I run this code correctly?
import numpy as np
import scipy.integrate
from scipy.integrate import solve_bvp
import matplotlib.pyplot as plt
k=0.06
Theta=20
p=0.4 #porosity of the electrode
pi=3.14
L=4 #cm
R=8.314
F=96485
t2=0.78
C0=1
T=298.15
vs=1
aa=0.5
ac=0.5
a=23300
i0=2e-2
Dad=0.5
I=2
Da=900
B=(1/k*(p**(1.5)))+1/Theta
C=I/(2*pi*L*Theta)
D=2*R*T/F
E=Da*p**(1.5)
def battery(r,y):
A=np.exp((aa*F*y[0])/(R*T))-np.exp((-ac*F*y[0])/(R*T))
return np.vstack((y[1]*B-C/r+(D*y[3]/y[2])*(0.22+y[2]),
A/((1/a*i0)+A/Dad),
y[3],
((1-E)/E)*y[3]+(0.22/(E*F))*(A/((1/a*i0)+A/Dad))))
def boundary(ya,yb):
return [ya[1]-2/(2*3.14*4*10*4.2),yb[1],ya[2]-9,yb[3]]
n = 25
r = np.linspace(4.2, 6.9, n)
y = np.ones((4,r.size))
AA=solve_bvp(battery,boundary,r,y)
The results are below:
sol: <scipy.interpolate.interpolate.PPoly object at 0x11303f728>
status: 2
success: False
I'm trying to get my head around how to implement a Monte Carlo function in python using pymc to replicate a spreadsheet by Douglas Hubbard in his book How to Measure Anything
My attempt was:
import numpy as np
import pandas as pd
from pymc import DiscreteUniform, Exponential, deterministic, Poisson, Uniform, Normal, Stochastic, MCMC, Model
maintenance_saving_range = DiscreteUniform('maintenance_saving_range', lower=10, upper=21)
labour_saving_range = DiscreteUniform('labour_saving_range', lower=-2, upper=9)
raw_material_range = DiscreteUniform('maintenance_saving_range', lower=3, upper=10)
production_level_range = DiscreteUniform('maintenance_saving_range', lower=15000, upper=35000)
#deterministic(plot=False)
def rate(m = maintenance_saving_range, l = labour_saving_range, r=raw_material_range, p=production_level_range):
return (m + l + r) * p
model = Model([rate, maintenance_saving_range, labour_saving_range, raw_material_range, production_level_range])
mc = MCMC(model)
Unfortunately, I'm getting an error: ValueError: A tallyable PyMC object called maintenance_saving_range already exists. This will cause problems for some database backends.
What have I got wrong?
Ah, it was a copy and paste error.
I'd called three distributions by the same name.
Here's the code that works.
import numpy as np
import pandas as pd
from pymc import DiscreteUniform, Exponential, deterministic, Poisson, Uniform, Normal, Stochastic, MCMC, Model
%matplotlib inline
import matplotlib.pyplot as plt
maintenance_saving_range = DiscreteUniform('maintenance_saving_range', lower=10, upper=21)
labour_saving_range = DiscreteUniform('labour_saving_range', lower=-2, upper=9)
raw_material_range = DiscreteUniform('raw_material_range', lower=3, upper=10)
production_level_range = DiscreteUniform('production_level_range', lower=15000, upper=35000)
#deterministic(plot=False, name="rate")
def rate(m = maintenance_saving_range, l = labour_saving_range, r=raw_material_range, p=production_level_range):
#out = np.empty(10000)
out = (m + l + r) * p
return out
model = Model([rate, maintenance_saving_range, labour_saving_range, raw_material_range])
mc = MCMC(model)
mc.sample(iter=10000)
I need to use the "savefig" in Python to save the plot of each iteration of a while loop, and I want that the name i give to the figure contains a literal part and a numerical part. This one comes out from an array or is the number associated to the index of iteration. I make a simple example:
# index.py
from numpy import *
from pylab import *
from matplotlib import *
from matplotlib.pyplot import *
import os
x=arange(0.12,60,0.12).reshape(100,5)
y=sin(x)
i=0
while i<99
figure()
a=x[:,i]
b=y[:,i]
c=a[0]
plot(x,y,label='%s%d'%('x=',c))
savefig(#???#) #I want the name is: x='a[0]'.png
#where 'a[0]' is the value of a[0]
thanks a lot.
Well, it should be simply this:
savefig(str(a[0]))
This is a toy example. Works for me.
import pylab as pl
import numpy as np
# some data
x = np.arange(10)
pl.figure()
pl.plot(x)
pl.savefig('x=' + str(10) + '.png')
I had the same demand recently and figured out the solution. I modify the given code and correct several explicit errors.
from pylab import *
import matplotlib.pyplot as plt
x = arange(0.12, 60, 0.12).reshape(100, 5)
y = sin(x)
i = 0
while i < 99:
figure()
a = x[i, :] # change each row instead of column
b = y[i, :]
i += 1 # make sure to exit the while loop
flag = 'x=%s' % str(a[0]) # use the first element of list a as the name
plot(a, b, label=flag)
plt.savefig("%s.png" % flag)
Hope it helps.
Since python 3.6 you can use f-strings to format strings dynamically:
import matplotlib.pyplot as plt
for i in range(99):
plt.figure()
a = x[:, i]
b = y[:, i]
c = a[0]
plt.plot(a, b, label=f'x={c}')
plt.savefig(f'x={c}.png')