MatPlotLib Graphs not showing - python

I am a begginer programmer and I'm trying to plot some graphs in python with math libraries and But I have some trouble.
I have to find some coordinates on the graph, sequentially, but the line simply doesnt appear on the screen, just the grid.
import math
import cmath
import numpy as np
from sympy import symbols, Eq, solve
import matplotlib.pyplot as plt
pi = 3.14159265
eps_r = 1.14
f = 27e6
Zo = 50
ZL = 50+75j
#começa a função
c = 299792458
vp = c / math.sqrt(eps_r)
Lambda = vp / f # comprimento de onda
Beta = 2 * pi / Lambda
d = np.arange(0, 1e-4, Lambda/4) # Distância da Impedância na linhaà carga
Z_d = (Zo * ((ZL + 1j * Zo * math.tan(Beta * d)) / (Zo + 1j * ZL * math.tan(Beta * d)))) / Zo # impendandia na linha a distancia d
Y_d = 1 / Z_d # Y_d = Admitância
Re_Y = np.real(Y_d)
Im_Y = np.imag(Y_d)
fig, ax = plt.subplots()
ax.plot(d, Re_Y)
ax.set(xlabel='d (m)', ylabel='Y(d) (1/Ohm)',
title='Real da Admitância vs distância à carga (1/Ohm)')
ax.grid()
plt.show()
plt.plot(d, Im_Y)
plt.grid(True, which="both")
plt.title('Imaginário da Admitância vs distância à carga (1/Ohm)')
plt.xlabel('d (m)')
plt.ylabel('jY(d) (1/Ohm)')
plt.show()
Zin_Y = 1 / (-1j * Im_Y) * Zo
lstubv = (cmath.atan (Zin_Y / (1j*Zo)) ) / Beta
lstubv = abs(lstubv)
plt.plot(Im_Y, lstubv)
plt.grid(True, which="both")
plt.title('módulo do Comprimento do STUB vs Y (1/Ohm)')
plt.xlabel('Yin (1/Ohm')
plt.ylabel('l (m))')
plt.show()
K = np.zeros(np.size(d))
for ct in range(1, 1, np.size(d, 2)):
if .9999 <= Re_Y(ct) and Re_Y(ct) <= 1.0001:
K = ct
k = np.mean(K)
if k == 0:
k = np.find(abs(Re_Y - 1) < 1e-6)
k = np.mean(k)
x = (math.ceil(np.mean(k)))
dstub = x * 1e-4
print('Distância do stub à carga (m)'), print(dstub)
Imstub = Im_Y(x)
Zin = 1 / (-1j * Imstub) * Zo
lstub = symbols('l')
lstub = abs((solve(Zin - 1j * Zo * math.tan(Beta * lstub), lstub)))
xLam_Stub = (lstub / Lambda)
print('Comprimento do stub em curto (m)'), print(lstub)
print('Distância do stub à carga (m)'), print(dstub)
this is my code. When I run it, the graphs appear, but...
Graph1 Graph2 Graph3
Also, I received this error after closing the graphs windows
error message

Related

How do I create a lowpass feedback loop for an allpass reverberator?

I'm trying to develop an AllPass Reverberator, but I got stuck when I have to create a loop on the lowpass filter (as in the image below). I understood the three cascade allpass filters, but in the code I don't know how to create the loop. The last process is to create the last image.
The code that I created is this (and stops at the end of the three allpass):
def allpassfb(DataIn, sr, Mix, Spread, Diffusion = 0.7):
delayAllPassMs = [23.8, 7.6, 2.6]
print('lista delay AllPass ms', delayAllPassMs)
# valore massimo della perturbazione in % rispetto ai delayMs(10%)
SpreadPerc = 0.1
# inizializzo come delay massimo l'ultimo valore della lista (+ eventuale Spread)
delayMaxMs = delayAllPassMs[-3] * (1 + Spread * SpreadPerc)
# inizializzo i vettori dei delay con degli 0
pAllPass = np.zeros(len(delayAllPassMs))
# creo la perturbazione sui delay degli allpass
for i in range(len(delayAllPassMs)):
pAllPass[i] = delayAllPassMs[i] * Spread * SpreadPerc
# loop dell'elaborazione dei delay sugli allpass
for i in range(len(delayAllPassMs)):
# lascio invariati i delay del canale opposto ai comb
delayAllPassL = delayAllPassMs[i]
# calcolo i nuovi delay derivati dalla perturbazione degli allpass
delayAllPassR = delayAllPassMs[i] + pAllPass[i]
if isStereo:
InL = DataIn[:, 0]
InR = DataIn[:, 1]
# inizializzo i vettori d'uscita
Y0 = np.zeros(len(InL))
Y1 = np.zeros(len(InR))
# filtro il segnale con gli allpass (perturbazione sull'altro canale)
Y0 = allpassSch2(InL, sr, delayAllPassL, Diffusion, delayMaxMs)
Y1 = allpassSch2(InR, sr, delayAllPassR, Diffusion, delayMaxMs)
else:
In = DataIn
Y0 = np.zeros(len(In))
Y1 = np.zeros(len(In))
Y0 = allpassSch2(In, sr, delayAllPassL, Diffusion, delayMaxMs)
Y1 = allpassSch2(In, sr, delayAllPassR, Diffusion, delayMaxMs)
# processo l'uscita stereo con il valore Mix (da 0 a 1)
if isStereo:
DataOut0 = Y0 * Mix + InL * (1.0 - Mix)
DataOut1 = Y1 * Mix + InR * (1.0 - Mix)
else:
DataOut0 = Y0 * Mix + In * (1.0 - Mix)
DataOut1 = Y1 * Mix + In * (1.0 - Mix)
# ricostruisco il vettore multidimensionale in uscita
return(np.column_stack((DataOut0, DataOut1)))

AttributeError: 'list' object has no attribute 'ndim'

I am trying to make a 3d plot using frames and an array. In this code you can see that I have a system of equations that needs to be solved in order to get the "Z" value for my points. Each time through the for loop, I call in 2 values that are needed to solve the system and those 2 values are ultimately my "X" and "Y" values. Upon solving the system I pull one of the values and use it to find my "Z" value.
Running the code gives me
AttributeError: 'list' object has no attribute 'ndim'
on line
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap = 'plasma')
What is the fix for this problem?
from pylab import *
from random import *
from mpl_toolkits import mplot3d
import pandas as pd
from scipy.optimize import fsolve
mdoth = 0.004916
Tinfhin = 334.75
cph = 1008
nsh = .598
hh= 86.68
Ash = .02
n=127
alpha = .00041427
rho = .002129
k=3.041
Le = .0025
Ae = .000001
re = rho * Le/Ae
Ke = k * Ae/Le
nsc = .674
hc = 87.68
Asc = .016
Tinfcin = 295.75
rL = re
mdotc = .004542
cpc = 1007
dframe = pd.read_csv("file name here")
plot(dframe['Sec'], dframe['TC (C)'], 'b-')
#annotate(xy=[818,72.25], s=&apos;First Entry&apos;)
xlabel('Time (s)')
ylabel('Temperature (C)')
title("Exhaust")
show()
plot(dframe['Sec'], dframe['Amb (C)'], 'r-')
xlabel('Time (s)')
ylabel('Temperature (C)')
title("Ambient")
show()
plot(dframe['Sec'], dframe['TC (C)'], 'b-', label = "Exhaust")
plot(dframe['Sec'], dframe['Amb (C)'], 'r-', label = "Ambient")
xlabel('Time (s)')
ylabel('Temperature (C)')
legend()
show()
Tinfhin = dframe['TC (C)']
Tinfcin = dframe['Amb (C)']
X, Y = meshgrid(Tinfhin,Tinfcin)
powerArray = []
for index, row in dframe.iterrows():
Tinfhin = row['TC (C)']
Tinfcin = row['Amb (C)']
def function(z):
II = z[0]
Qc = z[1]
Qh = z[2]
Tc = z[3]
Th = z[4]
Tinfcout = z[5]
Tinfhout = z[6]
F = np.empty((7))
F[0] = mdoth * cph * (Tinfhin - Tinfhout) - Qh
F[1] = nsh * hh * Ash * ((Tinfhin + Tinfhout)/2 - Th) - Qh
F[2] = n * (alpha * II * Th - 1/2 * (II**2) * re + (Ke * (Th-Tc))) - Qh
F[3] = n * (alpha * II * Tc + 1/2 * (II**2) * re + (Ke * (Th-Tc))) - Qc
F[4] = nsc * hc * Asc * (Tc - (Tinfcin + Tinfcout)/2) - Qc
F[5] = mdotc * cpc * (Tinfcin - Tinfcout) - Qc
F[6] = (alpha * (Th - Tc))/(rL/n + re) - II
return F
guess = np.array([1,1,1,1,1,1,1])
z = fsolve(function, guess)
power = n * z[0]**2 * rL
powerArray.append(power)
Z = powerArray
ax = axes(projection='3d')
ax.set_xlabel("TC")
ax.set_ylabel("Ambient")
ax.set_zlabel("Voltage")
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap = 'plasma')
ax.view_init(0, 180)

Why does execution time of the same algorithm changes so much when it is coded inside a module in numpy

In my learning process, I am writing a value function iteration problem in two different ways.
All code inside a python file
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import fsolve
import rutinas as rt
# Tenemos que definir lo parametros
alpha = .33
delta = .07
sigma = 1.5
gamma = 0 # Vamos a considerar que los hogares no valoran el ocio
beta = .97
tfp = 1.0
# Definicion de estados estaionarios
sss = alpha*delta/(1.0/beta-1.0+delta)
lss = (1.0-alpha)/(1.0-alpha+gamma*(1-sss))
kss = (alpha*tfp/(1.0/beta-1.0+delta))**(alpha/(1.0-alpha))
yss = tfp*kss**alpha*lss**(1.0-alpha)
css = (1.0-sss)*yss
# Definimos un grid para la variable de estado de la economía
nk = 500
kmin = 1.0e-5
kmax = 4*kss
kgrid = np.linspace(kmin, kmax, nk)
# Definimos una matriz de consumos. Esto puede hacerse de dos formas:
# 1. Preasignando y llenado espacios
matrizC = np.empty((nk, nk))
matrizU = np.empty((nk, nk))
for i1 in range(0,nk):
for i2 in range(0,nk):
matrizC[i1, i2] = tfp*kgrid[i1]**alpha\
+ (1.0-delta)*kgrid[i1]\
- kgrid[i2]
# Un indicador de posiciones de consumo positivas
indC = matrizC <= 0
matrizU = matrizC**(1.0-sigma)/(1.0-sigma)
matrizU[indC] = -1.e+6
# A partir de aquí podemos inicializar el algoritmo de programacion dinamica
valorInit = np.zeros(nk)
valorObj = np.zeros((nk, nk))
# Criterio de convergencia del algoritmo
tol = 1e-6
# Inicializamos el bucle while y un error arbitrario inicial
cont = 0
error = 10
while error > tol:
for i2 in range(0, nk):
valorObj[:, i2] = matrizU[:, i2] + beta*valorInit[i2]
pos = valorObj.argmax(axis = 1)
valor = valorObj.max(axis = 1)
error = np.max(np.abs(valor-valorInit))
valorInit = valor
cont += 1
print(error)
Inside a module with other routines
The algorithm inside the routine is a copy-paste of the previous file
def mnc_bellman(param):
import numpy as np
# Declaramos los argumentos del problema de programacion dinamica
# tol, kmin, kmax, tam, valorInit = args
alpha, delta, sigma, gamma, beta, tfp = param
kss = (alpha * tfp / (1.0 / beta - 1.0 + delta))**(alpha / (1.0 - alpha))
tol = 1.0e-6
kmin = 1.0e-4
kmax = 4*kss
tam = 500
valorInit = np.zeros((tam))
# Inicializamos objetos que vamos a necesitar
matrizC = np.empty((tam, tam))
valorObj = np.zeros((tam, tam))
kgrid = np.linspace(kmin, kmax, tam)
for i1 in range(0, tam):
for i2 in range(0, tam):
matrizC[i1, i2] = tfp * kgrid[i1] ** alpha \
+ (1.0 - delta) * kgrid[i1] \
- kgrid[i2]
# Un indicador de posiciones de consumo positivas
indC = matrizC <= 0
matrizU = matrizC ** (1.0 - sigma) / (1.0 - sigma)
matrizU[indC] = -1.e+6
# A partir de aqui podemos inicializar el algoritmo ITERACION de la
# funcion de VALOR
# Esta variable va a guardar cuantas veces iteramos hasta cumplir con los
# criterios de convergencia
cont = 0
# Tambien tenemos que establecer un error inicial que no se satisfaga
# trivialmente en el primer paso del bucle
error = 10
while error > tol:
for i2 in range(0, tam):
valorObj[:, i2] = matrizU[:, i2] + beta * valorInit[i2]
pos = valorObj.argmax(axis=1)
valor = valorObj.max(axis=1)
error = np.max(np.abs(valor - valorInit))
valorInit = valor
cont += 1
print(error)
# Ahora reconstruimos las reglas de decision
reglaK = kgrid[pos]
reglaC = tfp * kgrid ** alpha + (1.0 - delta) * kgrid - reglaK
return valor, reglaK, reglaC
That I later call from a main program
import numpy as np
import numpy.matlib
#import matplotlib.pyplot as plt
#from scipy.optimize import fsolve
import rutinas as rt
# Definicion de parametros del modelo (posteriormente intentare meterlos en un
# diccionario)
alpha = .36
delta = .08
sigma = 1.5
gamma = 0.5
beta = .97
tfp = 1.0
# Definicion de estado estacionario correspondiente a los parametros del
# modelo
sss = alpha * delta / (1.0 / beta - 1.0 + delta)
lss = (1.0 - alpha) / (1.0 - alpha + gamma * (1.0 - sss))
kss = (alpha * tfp / (1.0 / beta - 1.0 + delta))**(alpha / (1.0 - alpha))
yss = tfp * kss**alpha * lss**(1.0 - alpha)
css = (1.0 - sss) * yss
# Parametros relacionados con el algoritmo de iteracion de la funcion de valor
tol = 1.0e-6
kmin = 1.0e-4
kmax = 3.0*kss
tam = 500
valorInit = np.zeros((tam))
param = [alpha, delta, sigma, gamma, beta, tfp]
valor, reglaK, reglaC = rt.mnc_bellman(param)
Both codes run and spit the same output. However, the second option is orders of magnitude slower.
I hope somebody could point me into how to solve this discrepancy. I was thinking about using Jit but I want to understand the problem first.
Thank you

How to Draw an 2d Array

How could I graph this array u,
import math
import numpy as np
import matplotlib.pyplot as plt
pi=np.arccos(-1)
#Parameters En la ecuación del calor 1D
L = 1.;
T =1.;
#Parámetros del método
maxk = 2500; # Divisiones temporales
dt = T/maxk;
n = 50; # Divisiones espaciales
dx = L/n;
cond = 1/4; # Conductividad
b = 2.*cond*dt/(dx*dx); # Alpha
u=[[None]*maxk]*n
x=[None]*n
time=[None]*maxk
# Suponga temperatura distribuida de forma senoidal en la varilla para t=0
for i in range(0,n):
x[i] =i*dx;
u[i][0] =np.sin( pi*x[i] );
# Suponga una frontera a temperatura cero
for k in range(0,maxk):
u[0][k] = 0.;
u[n-1][k] = 0.;
time[k] = k*dt;
#Metodo explicito de solucion
for k in range(0,maxk-1):
for i in range(1, n-2):
u[i][k+1] =u[i][k] + 0.5*b*u[i-1][k]+u[i+1][k]-2.*u[i][k];
fig = plt.figure(figsize=(16, 13.2))
ax = fig.add_subplot(111)
ax.set_title('colorMap')
plt.imshow(u)
ax.set_aspect('equal')
cax = fig.add_axes([0.12, 0.1, 0.78, 0.8])
cax.get_xaxis().set_visible(False)
cax.get_yaxis().set_visible(False)
cax.patch.set_alpha(0)
cax.set_frame_on(False)
plt.colorbar(orientation='vertical')
plt.show()
I would expect a result like this
but I get something like this

How can I know the dimension of my variable?

I get this error :
ValueError: operands could not be broadcast together with shapes (365,) (2,)
But I'm surprised by this (2,).
How do I know which variable does this dimension (2,) please?
Because none of my variables should have it.
Thank you for your help !
Here, you can see the first script, where I define my function. It include a loop and also another function so I don't know if I can.
I have a lot of variable with (365, ) for the dimension because, it's function of the time, so for 365 days.
I have some fixed variable like the soil parameter, so the dimension for these is (1,)
But I don't know which variable get (2,) dimension ?
import pandas as pd
import numpy as np
def SA(MO = 0,
ETPr = 0,
SWSa = 0,
pb = 1.70 ):
DB = pd.read_excel("~/Documents/Spider/Data/data_base.xlsx", sheet_name = "DB")
DB1 = pd.read_excel("~/Documents/Spider/Bilan_Courgette.xlsx", sheet_name = "sol")
DB2 = pd.read_excel("~/Documents/Spider/Bilan_Courgette.xlsx", sheet_name = "culture")
#Calculs inter. pour déterminer ET0/day
#Array qui reprend "date" en une série 1 -> 365
JourDeLAnnee = pd.Series(range(1,366))
#Mauves
dist_TS = 1+(0.033*np.cos(0.0172 * JourDeLAnnee))
decli_So = 0.409*np.sin((0.0172 * JourDeLAnnee)-1.39)
lat = 0.87266463
ang_Hor_So =np.arccos(-np.tan(lat)*np.tan(decli_So))
gamma = 0.067
#Jaunes
delta = 2504*np.exp((17.27*DB.tsa_by_day)/(DB.tsa_by_day +237.3))/(DB.tsa_by_day +237.3)**2
rg = DB.ens_by_day / 1000000 * 86400
ra = 37.6 * dist_TS * ((ang_Hor_So * np.sin(lat) * np.sin(decli_So)) + \
(np.cos(lat) * np.cos(decli_So) * np.sin(ang_Hor_So)))
rso = (0.75 + (2*0.00001*120)) * ra
tw =(DB.tsa_by_day * np.arctan(0.151977 * ((DB.hra_by_day + 8.313659)**0.5))) + \
np.arctan(DB.tsa_by_day + DB.hra_by_day) - np.arctan(DB.hra_by_day - 1.676331) + \
(0.00391838 * ((DB.hra_by_day)**1.5) * np.arctan(0.023101 * DB.hra_by_day)) - 4.686035
ed = (0.611 * np.exp((17.27 * tw) / (tw + 237.3))) - (0.0008 *(DB.tsa_by_day-tw) * 101.325)
ea =((0.611 * np.exp((17.27*DB.tsa_max) / (DB.tsa_max + 237.3))) + \
(0.611 * np.exp((17.27 * DB.tsa_min) / (DB.tsa_min +237.3)))) / 2.0
rn = (0.77 * rg) - (((1.35 * (rg / rso)) - 0.35) \
* (0.34 - (0.14 * (ed**0.5))) * (4.9E-9) * ((((273+DB.tsa_max)**4)+((273+DB.tsa_min)**4))/2))
#Calcul de G
from typing import List
def get_g_constant(tsa_by_day: List[float], day: int):
assert day >= 1
return 0.38 * (tsa_by_day[day] - tsa_by_day[day-1])
def get_g_for_year(tsa_by_day: List[int]) -> List[float]:
g_list = []
for i in range(1, len(tsa_by_day)):
g_value = get_g_constant(tsa_by_day, i)
g_list.append(g_value)
return g_list
G = get_g_for_year(DB.tsa_by_day)
G = [DB.tsa_by_day[0]] + G
#Le fameux ET0
ET0 = ((0.408 * delta * (rn - G)) + (gamma * (900 /(DB.tsa_by_day + 273)) * DB.vtt_by_day * (ea - ed))) / \
(delta + (0.067*(1+(0.34 * DB.vtt_by_day))))
# Calcul des paramètres du sol
Profil = 500
pb = 100 / ((MO / 224000) + ((100-MO) / (1.64)))
Os = 0.6355+0.0013* DB1.A -0.1631* pb
Or = 0
lnα = (-4.3003) - (0.0097*DB1.A) + (0.0138* DB1.S ) - (0.0992*MO)
lnn = -1.0846-0.0236 * DB1.A -0.0085 * DB1.S +0.0001 * (DB1.S)**2
nn = np.exp(lnn) + 1
m = 1 - (1/nn)
lnK0 = 1.9582 + 0.0308*DB1.S - 0.6142* pb - 0.1566*MO
λ = -1.8642 - 0.1317*DB1.A + 0.0067*DB1.S
α = np.exp(lnα)
K0 = np.exp(lnK0)
θPf2 =(((1 + ((α*(10**2.5))**nn))**(-m))*( Os - Or)) + Or
θPf4 =(((1 + ((α*(10**4.2))**nn))**(-m))*( Os - Or)) + Or
SWS = θPf2 - θPf4
diff = SWS*SWSa
aj = diff / 2
θPf2New = θPf2 + aj
θPf4New = θPf4 - aj
#Calcul du volume de stock p à atteindre
p = 0.04 *(5 - ET0) + DB2.ptab[0]
θp =(1 - p) * ( θPf2New - θPf4New )+ θPf4New
Vp = θp * Profil
#Le fameux ETP
import datetime
DateS = datetime.datetime.strptime('30/03/2019','%d/%m/%Y').timetuple().tm_yday
DateR = datetime.datetime.strptime('15/09/2019','%d/%m/%Y').timetuple().tm_yday
ETP=ET0.copy()
for n in range(364):
if n >= (DateS - 1) and n <= (DateR - 1) :
ETP[n] = ET0[n] * DB2.Kc[0]
else:
ETP[n] = ET0[n] * DB2.SolNu[0]
ETP[0] = 0
ETPNew = ET0.copy()
ETPNew = ETP - ETP * ETPr
#Le Bilan Hydrique
Stock = ET0.copy()
θ = ET0.copy()
Drainage = ET0.copy()
Irrigation = ET0.copy()
Se = ET0.copy()
SeC = ET0.copy()
θ[0] = θPf2New
Stock[0] = θ[0]*Profil
for i in range(364) :
Se[i] = (θ[i] - Or)/( Os - Or)
if Se[i] > 1 :
SeC[i] = 1
else:
SeC[i] = Se[i]
Drainage[i] = K0 *(((SeC[i])**λ )*(1-(1- SeC[i]**(nn/(nn-1)))**m)**2)*10
if Vp[i] - Stock[i] > 0 : #Ici stock non défini
Irrigation[i] = Vp[i] - Stock[i]
else:
Irrigation[i] = 0
Stock[i+1] = Stock[i] + DB.plu_by_day[i] - ETPNew[i] - Drainage[i] + Irrigation[i]
θ[i+1] = Stock[i+1] / Profil
return (Irrigation.sum())
After, i use a second script to do a sensitivity analysis. And It's here, when I run this script, I get the error 'ValueError: operands could not be broadcast together with shapes (365,) (2,)'
import numpy as np
from SALib.analyze import sobol
from SALib.sample import saltelli
from test import*
import matplotlib.pyplot as plt
# Set up dictionary with system parameters
problem = {
'num_vars': 4,
'names': ['MO', 'ETPr', 'SWSa', 'K0'],
'bounds': [[0, 10],
[0, 0.04135],
[0, 0.2615],
[1.40, 1.70],
]}
# Array with n's to use
nsamples = np.arange(50, 400, 50)
# Arrays to store the index estimates
S1_estimates = np.zeros([problem['num_vars'],len(nsamples)])
ST_estimates = np.zeros([problem['num_vars'],len(nsamples)])
# Loop through all n values, create sample, evaluate model and estimate S1 & ST
for i in range(len(nsamples)):
print('n= '+ str(nsamples[i]))
# Generate samples
sampleset = saltelli.sample(problem, nsamples[i],calc_second_order=False)
# Run model for all samples
output = [SA(*sampleset[j,:]) for j in range(len(sampleset))]
# Perform analysis
results = sobol.analyze(problem, np.asarray(output), calc_second_order=False,print_to_console=False)
# Store estimates
ST_estimates[:,i]=results['ST']
S1_estimates[:,i]=results['S1']
np.save('ST_estimates.npy', ST_estimates)
np.save('S1_estimates.npy', S1_estimates)
S1_estimates = np.load('S1_estimates.npy')
ST_estimates = np.load('ST_estimates.npy')
# Generate figure showing evolution of indices
fig = plt.figure(figsize=(18,9))
ax1 = fig.add_subplot(1,2,1)
handles = []
for j in range(problem['num_vars']):
handles += ax1.plot(nsamples, S1_estimates[j,:], linewidth=5)
ax1.set_title('Evolution of S1 index estimates', fontsize=20)
ax1.set_ylabel('S1', fontsize=18)
ax1.set_xlabel('Number of samples (n)', fontsize=18)
ax1.tick_params(axis='both', which='major', labelsize=14)
ax2 = fig.add_subplot(1,2,2)
for j in range(problem['num_vars']):
ax2.plot(nsamples, ST_estimates[j,:], linewidth=5)
ax2.set_title('Evolution of ST index estimates', fontsize=20)
ax2.set_ylabel('ST', fontsize=18)
ax2.tick_params(axis='both', which='major', labelsize=14)
ax2.set_xlabel('Number of samples (n)', fontsize=18)
fig.legend(handles, problem['names'], loc = 'right', fontsize=11)
plt.savefig('indexevolution.png')
# Calculate parameter rankings
S1_ranks = np.zeros_like(S1_estimates)
ST_ranks = np.zeros_like(ST_estimates)
for i in range(len(nsamples)):
orderS1 = np.argsort(S1_estimates[:,i])
orderST = np.argsort(ST_estimates[:,i])
S1_ranks[:,i] = orderS1.argsort()
ST_ranks[:,i] = orderST.argsort()
Thank you for your help !

Categories