I am working on an optimizatiom model which is set to maximize NPV. I am getting some results, however my cap_ele should represent the max value in the el_to_ele_t series. However after running the code both int cap_ele and series el_to_ele_t reamin at 0.
Below are my variables:
prod_hpp_grid_t = mdl.continuous_var_dict(time, lb=0, ub=cap_grid, name='Power sold to grid')
prod_h2_t = mdl.continuous_var_dict(time, lb=0, name='Hydrogen output')
P_curt = mdl.continuous_var_dict(time, lb=0, name='Curtailment')
el_to_ele_t = mdl.continuous_var_dict(time, lb=0, name='El consumption from Electrolyser')
cap_wtg = mdl.integer_var(lb=0, name='Wind capacity')
cap_pv = mdl.integer_var(lb=0, name='Solar capacity')
cap_ele = mdl.integer_var(lb=0, name= "Electrolysis capacity")
And here is the objective function:
mdl.maximize(
-(cost_invest_wtg * cap_wtg + \
cost_invest_pv * cap_pv + \
cost_invest_ele * cap_ele + \
mdl.sum(
(mdl.sum(
price_spot[t] * prod_hpp_grid_t[t] + \
price_h2s[t] * prod_h2_t[t] for t in time) -\
(cost_onm_wtg * cap_wtg + \
cost_onm_pv * cap_pv + \
cost_onm_ele * cap_ele)
) / np.power(1 + discount_f, i)
for i in range(1, life_t_hpp + 1)
)
)
And those are contraints and the solver:
for t in time:
mdl.add_constraint(prod_hpp_grid_t[t] == prod_wtg_t[t] * cap_wtg + prod_pv_t[t] * cap_pv - P_curt[t] - el_to_ele_t[t] )
mdl.add_constraint(prod_h2_t[t] == el_to_ele_t[t] * cons_el_kg_ele)
mdl.add_constraint(cap_ele >= el_to_ele_t[t])
######### Solving the problem
sol = mdl.solve(log_output=False)
prod_hpp_grid_ts = pd.DataFrame.from_dict(sol.get_value_dict(prod_hpp_grid_t), orient='index')
prod_hpp_grid_ts = prod_hpp_grid_ts.reset_index()
P_curt = pd.DataFrame.from_dict(sol.get_value_dict(P_curt), orient='index')
P_curt = P_curt.reset_index()
prod_h2_ts = pd.DataFrame.from_dict(sol.get_value_dict(prod_h2_t), orient='index')
prod_h2_ts = prod_h2_ts.reset_index()
el_to_ele_ts = pd.DataFrame.from_dict(sol.get_value_dict(el_to_ele_t), orient='index')
el_to_ele_ts = el_to_ele_ts.reset_index()
Could there be any reson for why im not getting the desired answer?
Related
I have a function with different parameters that I want to optimize to fit some existing data.
The function runs fine on its own, but when I try to pass it through the scipy.optimize.curve_fit function, I get this error :
IndexError: invalid index to scalar variable.
I don't understand why the function would work on its own, and I would not get any errors.
What can I do ?
The original function used dictionnaries and I thought that might be the problem but I modified it and it still doesn't work.
This is the function I'm using :
def function_test(xy,X1,X2,X3,X4):
precip = xy\[0\]
potential_evap = xy\[1\]
nUH1 = int(math.ceil(X4))
nUH2 = int(math.ceil(2.0*X4))
uh1_ordinates = [0] * nUH1
uh2_ordinates = [0] * nUH2
UH1 = [0] * nUH1
UH2 = [0] * nUH2
for t in range(1, nUH1 + 1):
uh1_ordinates[t - 1] = s_curves1(t, X4) - s_curves1(t-1, X4)
for t in range(1, nUH2 + 1):
uh2_ordinates[t - 1] = s_curves2(t, X4) - s_curves2(t-1, X4)
production_store = X1*0.60# S
routing_store = X3*0.70# R
qsim = []
for j in range(2191):
if precip[j] > potential_evap[j]:
net_evap = 0
scaled_net_precip = (precip[j] - potential_evap[j])/X1
if scaled_net_precip > 13:
scaled_net_precip = 13.
tanh_scaled_net_precip = tanh(scaled_net_precip)
reservoir_production = (X1 * (1 - (production_store/X1)**2) * tanh_scaled_net_precip) / (1 + production_store/X1 * tanh_scaled_net_precip)
routing_pattern = precip[j]-potential_evap[j]-reservoir_production
else:
scaled_net_evap = (potential_evap[j] - precip[j])/X1
if scaled_net_evap > 13:
scaled_net_evap = 13.
tanh_scaled_net_evap = tanh(scaled_net_evap)
ps_div_x1 = (2 - production_store/X1) * tanh_scaled_net_evap
net_evap = production_store * (ps_div_x1) / \
(1 + (1 - production_store/X1) * tanh_scaled_net_evap)
reservoir_production = 0
routing_pattern = 0
production_store = production_store - net_evap + reservoir_production
percolation = production_store / (1 + (production_store/2.25/X1)**4)**0.25
routing_pattern = routing_pattern + (production_store-percolation)
production_store = percolation
for i in range(0, len(UH1) - 1):
UH1[i] = UH1[i+1] + uh1_ordinates[i]*routing_pattern
UH1[-1] = uh1_ordinates[-1] * routing_pattern
for j in range(0, len(UH2) - 1):
UH2[j] = UH2[j+1] + uh2_ordinates[j]*routing_pattern
UH2[-1] = uh2_ordinates[-1] * routing_pattern
groundwater_exchange = X2 * (routing_store / X3)**3.5
routing_store = max(0, routing_store + UH1[0] * 0.9 + groundwater_exchange)
R2 = routing_store / (1 + (routing_store / X3)**4)**0.25
QR = routing_store - R2
routing_store = R2
QD = max(0, UH2[0]*0.1+groundwater_exchange)
Q = QR + QD
qsim.append(Q)
return qsim
I am try to solve maximization problem using python library called SciPy.I am very need to python and SCipy. I code the given problem using looking at the youtube video at urlhttps://www.youtube.com/watch?v=M7ZA9fq2zCE&t=191s. I am solving price optimization problem. I took our product should be at the margin of the competitor price range.Manufacturing cost is added to cost function.Shipping cost was also added to cost function defined as "objective_fcn".Shipping cost is consist of serveral values.Packing costs,Delivary to port cost,tax,terminal cost and carriage cost.(see picture .And finally I add customer discount cost to the cost function.SO cost function has main three costs; manufacturing cost, customer discounts and shipping cost.My problem is I coded my optimization problem as it is in the given youtube video.But I got error saying "ValueError: operands could not be broadcast together with shapes (9,) (6,) (6,)".I don't know what is means and I don't know how to solve this issue. Please help me.
Code is there.I comment importnat details in there.
import numpy as np
from scipy.optimize import minimize
import math
# company descitions and inputs
Newyorkquantity = 60 / 100;
Felixstorequantity = 40 / 100;
DelivaryToPortLowerBoundry = 4 / 100;
DelivaryToPortHigherBoundry = 5 / 100;
PackingCostLowerBoundry = 1 / 10;
PackingCostHigheBoundry = 12 / 10;
Bronze_DiscountUpperBound = 20;
Bronze_DiscountLowerBound = 0;
Silver_DiscountUpperBound = 30;
Silver_DiscountLowerBound = 21;
Gold_DiscountUpperBound = 50;
Gold_DiscountLowerBound = 35;
Platinum_DiscountUpperBound = 71;
Platinum_DiscountLowerBound = 51;
NumberofchocolatesContainsInaContainer = 1000000;
# constant values
taxeForAcontainer = 30000;
terminalchargesForAcontainer = 40500;
STORAGEMAXIMUMCHOCOLATE=850000000;
# model predicted values
BronzeCustomers = 2500;
SilverCustomers = 1800;
GoldCustomers = 700;
PlatinumCustomers = 350;
ShippingrOneUnitContainerCost_NY = 80000;
ShippingrOneUnitContainerCost_Felixtow = 70000;
Manufacturing = 25;
CompetitorLowerBoundryprice = 250;
CompetitorHigherBoundryprice = 340;
def objective_fcn(x):
price = x[0]
quantity = x[1]
bronze_Discount = x[2]
silver_Discount = x[3]
Gold_Discount = x[4]
Platinum_Discount = x[5]
DelivaryToPort = x[6]
PackingCostOneUnit = x[7]
transporttcircles = x[8]
bronzecost = BronzeCustomers * (price - price * bronze_Discount)
Silvercost = SilverCustomers * (price - price * silver_Discount)
Goldcost = GoldCustomers * (price - price * Gold_Discount)
Platinumcost = PlatinumCustomers * (price - price * Platinum_Discount)
customercost = bronzecost + Silvercost + Goldcost + Platinumcost
print("hello")
packigcostAllunits = PackingCostOneUnit * quantity;
delivarytoporCosttAll = DelivaryToPort * transporttcircles;
ShippingCarringcharge_NewYK = (math.ceil((quantity * Newyorkquantity / NumberofchocolatesContainsInaContainer))) * ShippingrOneUnitContainerCost_NY;
ShippingCarringcharge_FelixStore = (math.ceil((quantity * Felixstorequantity / NumberofchocolatesContainsInaContainer))) * ShippingrOneUnitContainerCost_Felixtow;
Total_containers = (math.ceil((quantity * Newyorkquantity / NumberofchocolatesContainsInaContainer))) + (math.ceil((quantity * Felixstorequantity / NumberofchocolatesContainsInaContainer)));
shippingTotalCost = packigcostAllunits + delivarytoporCosttAll + ShippingCarringcharge_NewYK + ShippingCarringcharge_FelixStore + taxeForAcontainer*Total_containers +terminalchargesForAcontainer;
return -(price * quantity - (customercost + Manufacturing * quantity + shippingTotalCost))
bounds_price = (CompetitorLowerBoundryprice, CompetitorHigherBoundryprice)
bound_quantity = (10000,STORAGEMAXIMUMCHOCOLATE)
bounds_bronze_DS = (Bronze_DiscountLowerBound, Bronze_DiscountUpperBound)
bounds_silver_DS = (Silver_DiscountLowerBound, Silver_DiscountUpperBound)
bounds_Gold_DS = (Gold_DiscountLowerBound, Gold_DiscountUpperBound)
bounds_Platinum_DS = (Platinum_DiscountLowerBound, Platinum_DiscountUpperBound)
bounds_DelivaryToPor = (DelivaryToPortLowerBoundry,DelivaryToPortHigherBoundry)
bounds_PackingCostLowerBoundry = (PackingCostLowerBoundry,PackingCostHigheBoundry)
boundsss = [bounds_price, bound_quantity, bounds_bronze_DS, bounds_silver_DS, bounds_Gold_DS, bounds_Platinum_DS]
x0 = [251, 100000, 1, 22, 36, 52,DelivaryToPortLowerBoundry,PackingCostLowerBoundry,3]
result = minimize(fun=objective_fcn, x0=x0, bounds=boundsss, method='SLSQP')
if result.success:
fitted_params = result.x
print(fitted_params)
else:
raise ValueError(result.message)
Error is caused by the fact you provided 9 dimensions in x0 and 6 dimensions in bounds parameters. I made-up some bounds and fixed your problem:
import numpy as np
from scipy.optimize import minimize
import math
# company descitions and inputs
Newyorkquantity = 60 / 100;
Felixstorequantity = 40 / 100;
DelivaryToPortLowerBoundry = 4 / 100;
DelivaryToPortHigherBoundry = 5 / 100;
PackingCostLowerBoundry = 1 / 10;
PackingCostHigheBoundry = 12 / 10;
Bronze_DiscountUpperBound = 20;
Bronze_DiscountLowerBound = 0;
Silver_DiscountUpperBound = 30;
Silver_DiscountLowerBound = 21;
Gold_DiscountUpperBound = 50;
Gold_DiscountLowerBound = 35;
Platinum_DiscountUpperBound = 71;
Platinum_DiscountLowerBound = 51;
NumberofchocolatesContainsInaContainer = 1000000;
# constant values
taxeForAcontainer = 30000;
terminalchargesForAcontainer = 40500;
STORAGEMAXIMUMCHOCOLATE=850000000;
# model predicted values
BronzeCustomers = 2500;
SilverCustomers = 1800;
GoldCustomers = 700;
PlatinumCustomers = 350;
ShippingrOneUnitContainerCost_NY = 80000;
ShippingrOneUnitContainerCost_Felixtow = 70000;
Manufacturing = 25;
CompetitorLowerBoundryprice = 250;
CompetitorHigherBoundryprice = 340;
def objective_fcn(x):
price = x[0]
quantity = x[1]
bronze_Discount = x[2]
silver_Discount = x[3]
Gold_Discount = x[4]
Platinum_Discount = x[5]
DelivaryToPort = x[6]
PackingCostOneUnit = x[7]
transporttcircles = x[8]
bronzecost = BronzeCustomers * (price - price * bronze_Discount)
Silvercost = SilverCustomers * (price - price * silver_Discount)
Goldcost = GoldCustomers * (price - price * Gold_Discount)
Platinumcost = PlatinumCustomers * (price - price * Platinum_Discount)
customercost = bronzecost + Silvercost + Goldcost + Platinumcost
print("hello")
packigcostAllunits = PackingCostOneUnit * quantity;
delivarytoporCosttAll = DelivaryToPort * transporttcircles;
ShippingCarringcharge_NewYK = (math.ceil((quantity * Newyorkquantity / NumberofchocolatesContainsInaContainer))) * ShippingrOneUnitContainerCost_NY;
ShippingCarringcharge_FelixStore = (math.ceil((quantity * Felixstorequantity / NumberofchocolatesContainsInaContainer))) * ShippingrOneUnitContainerCost_Felixtow;
Total_containers = (math.ceil((quantity * Newyorkquantity / NumberofchocolatesContainsInaContainer))) + (math.ceil((quantity * Felixstorequantity / NumberofchocolatesContainsInaContainer)));
shippingTotalCost = packigcostAllunits + delivarytoporCosttAll + ShippingCarringcharge_NewYK + ShippingCarringcharge_FelixStore + taxeForAcontainer*Total_containers +terminalchargesForAcontainer;
return -(price * quantity - (customercost + Manufacturing * quantity + shippingTotalCost))
bounds_price = (CompetitorLowerBoundryprice, CompetitorHigherBoundryprice)
bound_quantity = (10000,STORAGEMAXIMUMCHOCOLATE)
bounds_bronze_DS = (Bronze_DiscountLowerBound, Bronze_DiscountUpperBound)
bounds_silver_DS = (Silver_DiscountLowerBound, Silver_DiscountUpperBound)
bounds_Gold_DS = (Gold_DiscountLowerBound, Gold_DiscountUpperBound)
bounds_Platinum_DS = (Platinum_DiscountLowerBound, Platinum_DiscountUpperBound)
bounds_DelivaryToPor = (DelivaryToPortLowerBoundry,DelivaryToPortHigherBoundry)
bounds_PackingCostLowerBoundry = (PackingCostLowerBoundry,PackingCostHigheBoundry)
##### FIX HERE #####
fake_bound1 = [DelivaryToPortLowerBoundry - 1, DelivaryToPortLowerBoundry + 1]
fake_bound2 = [PackingCostLowerBoundry - 1, PackingCostLowerBoundry + 1]
fake_bound3 = (2, 4)
boundsss = [bounds_price, bound_quantity, bounds_bronze_DS, bounds_silver_DS, bounds_Gold_DS, bounds_Platinum_DS,
fake_bound1, fake_bound2, fake_bound3]
#### END OF FIX ####
x0 = [251, 100000, 1, 22, 36, 52, DelivaryToPortLowerBoundry,PackingCostLowerBoundry,3]
result = minimize(fun=objective_fcn, x0=x0, bounds=boundsss, method='SLSQP')
if result.success:
fitted_params = result.x
print(fitted_params)
else:
raise ValueError(result.message)
In the tensorflow implementation of convLSTM cell the following lines of code are written as:
x_i = self.input_conv(inputs_i, kernel_i, bias_i, padding=self.padding)
x_f = self.input_conv(inputs_f, kernel_f, bias_f, padding=self.padding)
x_c = self.input_conv(inputs_c, kernel_c, bias_c, padding=self.padding)
x_o = self.input_conv(inputs_o, kernel_o, bias_o, padding=self.padding)
h_i = self.recurrent_conv(h_tm1_i, recurrent_kernel_i)
h_f = self.recurrent_conv(h_tm1_f, recurrent_kernel_f)
h_c = self.recurrent_conv(h_tm1_c, recurrent_kernel_c)
h_o = self.recurrent_conv(h_tm1_o, recurrent_kernel_o)
i = self.recurrent_activation(x_i + h_i)
f = self.recurrent_activation(x_f + h_f)
c = f * c_tm1 + i * self.activation(x_c + h_c)
o = self.recurrent_activation(x_o + h_o)
h = o * self.activation(c)
The corresponding equations as described in the paper are:
I am not able to see how W_ci, W_cf, W_co C_{t-1}, C_t is used in the input, forget and output gates. Where does it being used in computing the 4 gates?
Of course you cannot find those in that implementation of ConvLSTM cell, because it not using peephole:
Peephole connections allow the gates to utilize the previous internal
state as well as the previous hidden state (which is what LSTMCell is
limited to)
The tf.keras.experimental.PeepholeLSTMCell follow the equations you post above, as you can see in it source code:
x_i, x_f, x_c, x_o = x
h_tm1_i, h_tm1_f, h_tm1_c, h_tm1_o = h_tm1
i = self.recurrent_activation(
x_i + K.dot(h_tm1_i, self.recurrent_kernel[:, :self.units]) +
self.input_gate_peephole_weights * c_tm1)
f = self.recurrent_activation(x_f + K.dot(
h_tm1_f, self.recurrent_kernel[:, self.units:self.units * 2]) +
self.forget_gate_peephole_weights * c_tm1)
c = f * c_tm1 + i * self.activation(x_c + K.dot(
h_tm1_c, self.recurrent_kernel[:, self.units * 2:self.units * 3]))
o = self.recurrent_activation(
x_o + K.dot(h_tm1_o, self.recurrent_kernel[:, self.units * 3:]) +
self.output_gate_peephole_weights * c)
Or more clear, if you look at source code of tf.compat.v1.nn.rnn_cell.LSTMCell:
if self._use_peepholes:
c = (
sigmoid(f + self._forget_bias + self._w_f_diag * c_prev) * c_prev +
sigmoid(i + self._w_i_diag * c_prev) * self._activation(j))
else:
c = (
sigmoid(f + self._forget_bias) * c_prev +
sigmoid(i) * self._activation(j))
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 !
I am getting an error that says I am not accounting for obscured light and that my specular is getting added when the light is obscured. This is what the specular part that is being added onto is with x representing r, g, orb of my Color class: light.color.x * s.finish.specular * specIntense
def in_shadow (sphere_list, sphere, ray_to_light, light):
new_list = list()
for s in sphere_list:
if sphere != s:
new_list.append(s)
for s in new_list:
if sphere_intersection_point(ray_to_light, s):
x1 = ray_to_light.pt.x - light.pt.x
y1 = ray_to_light.pt.y - light.pt.y
z1 = ray_to_light.pt.z - light.pt.z
dist1 = math.sqrt(x1 + y1 + z1)
x2 = ray_to_light.pt.x - s.center.x
y2 = ray_to_light.pt.y - s.center.y
z2 = ray_to_light.pt.z - s.center.z
dist2 = math.sqrt(x2 + y2 + z2)
# distance to light, distance to sphere
# check if distance to sphere < distance to light
# if so return 0
if dist2 < dist1:
return 0
return 1
def cast_ray(ray, sphere_list, color, light, point):
# count = 0
dist = -1
cp = Color(1.0, 1.0, 1.0)
for s in sphere_list:
if sphere_intersection_point(ray, s):
# count += 1
p = sphere_intersection_point(ray, s)
vec = vector_from_to(s.center, p)
N = normalize_vector(vec)
norm_scaled = scale_vector(N, 0.01)
pe = translate_point(p, norm_scaled)
l = vector_from_to(pe, light.pt)
l_dir = normalize_vector(l)
dot = dot_vector(N, l_dir)
r = Ray(pe, l_dir)
dotNScaled = dot * 2
reflecVec = difference_vector(l_dir, scale_vector(N, dotNScaled))
V = vector_from_to(point, pe)
Vdir = normalize_vector(V)
spec = dot_vector(reflecVec, Vdir)
m = in_shadow(sphere_list, s, r, light)
if (dot <= 0):
m = 0
x = (ray.pt.x - p.x) ** 2
y = (ray.pt.y - p.y) ** 2
z = (ray.pt.z - p.z) ** 2
curdist = math.sqrt(x + y + z)
# print curdist
if (dist < 0) or (dist > curdist):
dist = curdist
if (spec <= 0 ):
r = ( s.color.r * s.finish.ambient * color.r ) \
+ ( light.color.r * s.finish.diffuse * dot * s.color.r * m )
g = ( s.color.g * s.finish.ambient * color.g ) \
+ (light.color.g * s.finish.diffuse * dot * s.color.g * m )
b = ( s.color.b * s.finish.ambient * color.b ) \
+ (light.color.b * s.finish.diffuse * dot * s.color.b * m )
cp = Color(r, g, b)
if ( spec >= 0 ):
specIntense = spec ** (1/s.finish.roughness)
print type(s.finish.diffuse)
r = (s.color.r * s.finish.ambient * color.r) \
+ (light.color.r * s.finish.diffuse * dot * s.color.r * m) \
+ (light.color.r * s.finish.specular * specIntense)
g = (s.color.g * s.finish.ambient * color.g) \
+ (light.color.g * s.finish.diffuse * dot * s.color.g * m) \
+ (light.color.g * s.finish.specular * specIntense)
b = (s.color.b * s.finish.ambient * color.b) \
+ (light.color.b * s.finish.diffuse * dot * s.color.b * m) \
+ (light.color.b * s.finish.specular * specIntense)
cp = Color(r, g, b)
# if count > 1:
# print 'intersects two!'
return cp
I think somewhere I am not accounting for the case where the sphere has another one in front of it therefore the specular part is being added to it when it shouldn't, creating this weird white light behind the first sphere that isn't supposed to be there. I'm sure there is a bug in this code somewhere but I cannot find it.