Using a input function to calculate alpha from a input - python

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

Related

getting wrong results from a loop calculation and invalid syntax error

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

How to evaluate sympy piecewise-like expressions so it's easy to obtain numerical only output?

I have the following code which is part of a practice I'm working on:
Here is a function that obtains 2*N+1 coefficients of the Fourier series for the input function "ft" written in terms of sym.Heaviside(t), the goal is to get from this function only the numerical values so it is possible to perform operations with the obtained Power Spectral Density (PSD):
def ck_power(ft,f,N=5):
c_k_coeff=f*sym.integrate(ft*sym.exp(-2*j*np.pi*t*k*f),(t,-1/(2*f),1/(2*f)))
#C_k_coeff=sym.lambdify(k,c_k_coeff,modules=['numpy'])
#PSD=[abs((c_k_coeff(i)))**2 for i in range(-N,N+1)]
##PSD=[(c_k_coeff.subs(k,i))*(c_k_coeff.subs(k,-i)) for i in range(-N,N+1)]
### "worked" but keeps the same behavior. PSD=[(c_k_coeff.evalf(subs={k:i}))*(c_k_coeff.evalf(subs={k:-i})) for i in range(-N,N+1)]
PSD=[(c_k_coeff.evalf(subs={k:i}))*(c_k_coeff.evalf(subs={k:-i})) for i in range(-N,N+1)]
PSD=[sym.N(abs(i.subs({u(0):0.5})).evalf(3)) for i in PSD]
positive_PSD=PSD[len(PSD)//2:]
# because the k=0 c_k isn't twice in the k axis apporting power:
positive_PSD[1:]=[2*i for i in positive_PSD[1:]]
PSD=np.array(PSD)
positive_PSD=np.array(positive_PSD)
return PSD,positive_PSD
The problem is that when I use the function with the code below the figures I'm still having a weird piecewise function as the output (especially with the sawtooth wave)
The other functions don't have the same problem
But the sawtooth shows directly the piecewise output
these are the output expressions for k=0:
#vertical
type_hash=("Frequency","Power")
frequency_hash=("100KHz","1MHz","100MHz")
frequency=(100e+3,1e+6,100e+6)
waveform_hash=("Pulsetrain","Sawtooth","Triangle")
#horizontal
armonic=list(range(6))
signal={
"Pulsetrain":my.pulsetrain,
"Sawtooth":my.sawtooth,
"Triangle":my.triangle
}
t1={"waveform":[],"frequency":[],"type\\armonic":[]}
for i in armonic:
t1[str(i)]=[]
(A,D,Aoff,toff)=(1,0.5,0,0)
for iwav in waveform_hash:
for ifreq in range(len(frequency)):
ftemp=frequency[ifreq]
for itype in range(len(type_hash)):
f_now=signal[iwav](A,1/ftemp,D,Aoff,toff)
PSD,pPSD=my.ck_power(f_now,ftemp,N=5) #<<--right here is where the functions is called
for i in armonic:
if not itype:
t1[str(i)].append(f"{ftemp*i:.2e}")
else:
t1[str(i)].append(pPSD[i])# add here Power
t1["type\\armonic"].append(type_hash[itype])
t1["frequency"].append(frequency_hash[ifreq])
t1["waveform"].append(iwav)
d1=pd.DataFrame(t1)
d1
these are my imports:
import numpy as np
import matplotlib.pyplot as plt
from scipy.io.wavfile import read
from scipy import signal
import sympy as sym
import sigplot as my
import pandas as pd
Lastly, this is part of my sigplot.py file
import numpy as np
import matplotlib.pyplot as plt
from scipy.io.wavfile import read
from scipy import signal
import sympy as sym
from sympy import Heaviside as u
from IPython.display import display, Math
import pandas as pd
t=sym.symbols('t')
k=sym.symbols('k', integer=True)
j=sym.I
#Fourier
def ck(ft,T):
c_k=1/T*sym.integrate(ft*sym.exp(-j*k*(2*np.pi/T)*t),(t,-T/2,T/2))
c_0=c_k.subs(k,0)
#c_k_mag =[sym.simplify((abs(c_n_coeff.subs(n,i)))) for i in range (-N,N+1)]
return (c_k,c_0)
def espectral(c_k,f,N):
PSD=[abs((c_k.subs(k,i)))**2 for i in range(-N,N+1)]
positive_PSD=[2*abs((c_k.subs(k,i)))**2 if i!=0 else (c_k.subs(k,0))**2 for i in range(N+1)]
return PSD,positive_PSD
def ck_power(ft,f,N=5):
c_k_coeff=f*sym.integrate(ft*sym.exp(-2*j*np.pi*t*k*f),(t,-1/(2*f),1/(2*f)))
#C_k_coeff=sym.lambdify(k,c_k_coeff,modules=['numpy'])
#PSD=[abs((c_k_coeff(i)))**2 for i in range(-N,N+1)]
##PSD=[(c_k_coeff.subs(k,i))*(c_k_coeff.subs(k,-i)) for i in range(-N,N+1)]
### worked. PSD=[(c_k_coeff.evalf(subs={k:i}))*(c_k_coeff.evalf(subs={k:-i})) for i in range(-N,N+1)]
PSD=[(c_k_coeff.evalf(subs={k:i}))*(c_k_coeff.evalf(subs={k:-i})) for i in range(-N,N+1)]
PSD=[sym.N(abs(i.subs({u(0):0.5})).evalf(3)) for i in PSD]
positive_PSD=PSD[len(PSD)//2:]
# because the k=0 c_k isn't twice in the k axis apporting power.
positive_PSD[1:]=[2*i for i in positive_PSD[1:]]
PSD=np.array(PSD)
positive_PSD=np.array(positive_PSD)
return PSD,positive_PSD
def espectrump(c_k,f,N):
# this function should not be used for performance purposes
PSD=[abs((c_k.subs(k,i)))**2 for i in range(-N,N+1)]
positive_PSD=[2*abs((c_k.subs(k,i)))**2 if i!=0 else (c_k.subs(k,0))**2 for i in range(N+1)]
plt.stem(list(range(-N,N+1)),PSD,markerfmt='^',use_line_collection=True)
plt.xlabel("$k$")
plt.grid()
plt.show()
return positive_PSD
def psdplot(N,PSD):
plt.stem(list(range(-N,N+1)),PSD,markerfmt='^',use_line_collection=True)
plt.xlabel("$k$")
plt.ylabel("$y=10{log()}$")
plt.grid()
plt.show()
return None #excuse me, I can't hide it. Is that simple
#waveforms
def pulsetrain(A,T,D,off=0,toff=0):
f=A*(-u(t+T/2)+2*(u(t+D*T/2)-u(t-D*T/2))+u(t-T/2))
foff=f+off*(u(t+T/2)-u(t-T/2))
foff=foff.subs(t,t-toff)
return foff
def triangle(A,T,D=None,off=0,toff=0):
m = (2*A)/T
toff_temp=0.5
tri=m*t*u(t+T/2)-2*m*t*u(t)+m*t*u(t-T/2)
foff = tri+(off+toff_temp)*(u(t+T/2)-u(t-T/2))
foff = foff.subs(t,t-toff)
return foff
def sawtooth(A,T,D=None,off=0,toff=0):
m = A/T
saw =m*t*u(t+T/2)-m*t*u(t-T/2)-(m/2)*u(t-T/2)
foff = saw+off*(u(t+T/2)-u(t-T/2))
foff = foff.subs(t,t-toff)
return foff
Thanks in advance!

Creating a vector of values based off a test using a for loop

This feels like it should be a simple problem but I am newer to python, in R i would use a foreach loop that gave me an option to combine.
I have tried a for loop that lets me print out all the values i need but i want them collected into a vector of values that i can use later.
from scipy.stats import gamma
import scipy.stats as stats
import numpy as np
import random
data2 = np.random.gamma(1,2, size = 500)
gammT = np.log(data2 + 1)
mean = np.mean(gammT)
sd = np.std(gammT)
a = (mean/ sd)**2
b = (sd**2)/ mean
for i in range(1,100):
gammT = random.sample(list(gammT), 500)
gamm = np.random.gamma(a,b, size = len(gammT))
s = stats.anderson_ksamp([gammT,gamm])
s = s[2]
print(s)
So i am able to print all the values i want but i want them all to be gathered together in a vector of values. I have tried to append and make lists but am not able to get them together.
from scipy.stats import gamma
import scipy.stats as stats
import numpy as np
import random
gammT = np.log(data2.iScore + 1)
mean = np.mean(gammT)
sd = np.std(gammT)
a = (mean/ sd)**2
b = (sd**2)/ mean
#initialize empty list
result=[]
for i in range(100):
# removed (1,100) you only need range(100) for 100 elements
gammT = random.sample(list(gammT), 500)
gamm = np.random.gamma(a,b, size = len(gammT))
s = stats.anderson_ksamp([gammT,gamm])
s = s[2]
#append calculation to list
result.append(s)
print(s)
print(result)

Python - How to plot argument in integral that is not the value being integrated

I want to integrate a function that has no closed form solution with an unknown variable and then plot vs the unknown variable. To try a simpler test, I tried to use the integral of f(x,c) = (x^2+c), integrated with respect to x and plot with different values of c. However, the code below gets the error
only size-1 arrays can be converted to Python scalars
even though the integral of a number, e.g. integral(5), seems to return the correct scalar value.
import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate
def f(x,c):
return x**2+c
def integral(c):
return integrate.quad(f,0,10, args = (c,))[0]
y = np.linspace(0,20,200)
plt.plot(y, integral(y))
You pass a numpy array as the argument c while you wanted to integrate over x for all the items of c. Therefore you can use this:
def f(x,c):
return x**2+c
def integrate_f(c):
result = np.zeros(len(c))
counter = 0
for item in c:
result[counter] = integrate.quad(f,0,10, args = (item))[0]
counter +=1
return result
c_array = np.linspace(0,1,200)
plt.plot(c_array, integrate_f(c_array))
onno was a bit faster. But here is my similar solution. You need to loop over all the different c:
import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate
def f(x,c):
return x**2+c
def getIntegral(c_list):
result = []
for c in c_list:
integral = integrate.quad(f,0,10,args = c)[0]
result.append(integral)
return result
if __name__ == "__main__":
c_list = np.linspace(0,20,200)
plt.plot(c_list, getIntegral(c_list))
plt.show()

Use savefig in Python with string and iterative index in the name

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

Categories