How can I fix an invalid syntax error in my code? - python

so I've been trying to run this code but I keep getting a syntax error. It's on the part where I try to use previous variables to convert them into another coordinate system. Any help would be greatly appreciated, thank you!
import time as t
import datetime
import math as m
start_time = datetime.datetime(2020, 7, 13, 0, 0).timestamp()
print("This code gives the coordinates in xyz and Latitude and Longitude")
time_now = t.time()
time_between = time_now - start_time
x = 5978.43 * m.cos(0.00129 * (time_between - 24066))
y = 4134.68 * m.cos(0.00129 * (time_between - 20190))
z = -4836.3 * m.cos(0.00129 * (time_between - 20581))
r = m.sqrt(pow(x, 2) + pow(y, 2) + pow(z, 2) #I get the error here
theta = m.acos(z/r)
phi = m.atan(y/x)
latitude = (theta*180/m.pi - 90)* -1
print("The coordinates are:\n", "x = ", round(x, 2),"\n", "y = ", round(y, 2),"\n", "z = ", round(z, 2))
print("The latitude is: ", latitude, "and the Longitude is: ", phi)

You forgot to close m.sqrt as below:
import time as t
import datetime
import math as m
start_time = datetime.datetime(2020, 7, 13, 0, 0).timestamp()
print("This code gives the coordinates in xyz and Latitude and Longitude")
time_now = t.time()
time_between = time_now - start_time
x = 5978.43 * m.cos(0.00129 * (time_between - 24066))
y = 4134.68 * m.cos(0.00129 * (time_between - 20190))
z = -4836.3 * m.cos(0.00129 * (time_between - 20581))
r = m.sqrt(pow(x, 2) + pow(y, 2) + pow(z, 2)) #I get the error here
theta = m.acos(z/r)
phi = m.atan(y/x)
latitude = (theta*180/m.pi - 90)* -1
print("The coordinates are:\n", "x = ", round(x, 2),"\n", "y = ", round(y, 2),"\n", "z = ", round(z, 2))
print("The latitude is: ", latitude, "and the Longitude is: ", phi)

Related

Invalid index to scalar variable error when trying to use scipy.optimize.curve_fit

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

how to select from sqlite3.db where i compare a result of equation that has variables from the db?

if i have a table like this:
("CREATE TABLE table (name text,x real, y real, state text) ")
[('name_1' ,x, y, 'active'), ('name_2' ,x, y, 'active')]
And two variable ref_1 = math.cos(some_input), ref_2 = math.cos(some_input)
and i want to SELECT only state = 'active' that their math.cos(x) < ref_1 and math.cos(y) < ref_2
what can i add to this line: curs.execute("SELECT * FROM table WHERE state = 'active #### code' to endup with what i want. m not used to work a lot around databases
This is the original line in my Code
only lat and lon are variables inside the db
active = 'active'
curs.execute(f"SELECT * FROM drivers WHERE state = {active} and radius >= {math.sqrt( (lat - float(user_lat) )**2 + (lon - float(user_lon) )**2)} and min_radius =< {-math.sqrt( (lat - float(user_lat) )**2 + (lon - float(user_lon) )**2)} ")
i get this output:
curs.execute(f"SELECT * FROM drivers WHERE state = {active} and radius >= {math.sqrt( (lat - float(user_lat) )**2 + (lon - float(user_lon) )**2)} and min_radius =< {-math.sqrt( (lat - float(user_lat) )**2 + (lon - float(user_lon) )**2)} ")
NameError: name 'lat' is not defined
You can use a f string to input different variables
curs.execute(f"SELECT * FROM table WHERE state = 'active and ref_1 < {math.cos(x)} code and ref_2 > {math.cos(y)}")
import sqlite3
import math
user_lat = #
user_lon = #
radius_length = #
state = 'active'
linktoauth = sqlite3.connect('DRIVERS.db')
curs = linktoauth.cursor()
def _radius_len(x, a, y, b):
result = math.sqrt((x - a)**2 + (y - b)**2)
return result
linktoauth.create_function('rad', 4, _radius_len)
curs.execute(f"SELECT * FROM drivers WHERE state = ? and rad(lat, ?, lon, ?) <= ? ",(state, user_lat, user_lon, radius_length,))

Scipy pythonoptimization error:ValueError: operands could not be broadcast together with shapes (9,) (6,) (6,)

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)

offset a parallel line to a given line python

I want to draw parallel line to given X,Y coordinate below code helps to draw ,
import numpy as np
import matplotlib.pyplot as plt
x = [187, 879, 722, 322]
y = [341, 344, 112, 112]
newX = []
newY = []
def findIntesection(p1x, p1y, p2x, p2y, p3x,p3y, p4x, p4y):
dx12 = p2x - p1x
dy12 = p2y - p1y
dx34 = p4x - p3x
dy34 = p4y - p3y
denominator = (dy12*dx34-dx12*dy34)
t1 = ((p1x - p3x) * dy34 + (p3y - p1y) * dx34)/ denominator
t2 = ((p3x - p1x) * dy12 + (p1y - p3y) * dx12)/ -denominator;
intersectX = p1x + dx12 * t1
intersectY = p1y + dy12 * t1
if (t1 < 0): t1 = 0
elif (t1 > 1): t1 = 1
if (t2 < 0): t2 = 0
elif (t2 > 1): t2 = 1
return intersectX,intersectY
def normalizeVec(x,y):
distance = np.sqrt(x*x+y*y)
return x/distance, y/distance
def getEnlarged(oldX, oldY, offset):
num_points = len(oldX)
for j in range(num_points):
i = j - 1
if i < 0:
i += num_points
k = (j + 1) % num_points
vec1X = oldX[j] - oldX[i]
vec1Y = oldY[j] - oldY[i]
v1normX, v1normY = normalizeVec(vec1X,vec1Y)
v1normX *= offset
v1normY *= offset
n1X = -v1normY
n1Y = v1normX
pij1X = oldX[i] + n1X
pij1Y = oldY[i] + n1Y
pij2X = oldX[j] + n1X
pij2Y = oldY[j] + n1Y
vec2X = oldX[k] - oldX[j]
vec2Y = oldY[k] - oldY[j]
v2normX, v2normY = normalizeVec(vec2X,vec2Y)
v2normX *= offset
v2normY *= offset
n2X = -v2normY
n2Y = v2normX
pjk1X = oldX[j] + n2X
pjk1Y = oldY[j] + n2Y
pjk2X = oldX[k] + n2X
pjk2Y = oldY[k] + n2Y
intersectX,intersetY = findIntesection(pij1X,pij1Y,pij2X,pij2Y,pjk1X,pjk1Y,pjk2X,pjk2Y)
#print(intersectX,intersetY)
newX.append(intersectX)
newY.append(intersetY)
getEnlarged(x, y, 20)
plt.plot(x, y)
plt.plot(newX, newY)
plt.show()
This gives result as below
Here it is giving good result by drawing parallel line to each line of our trapezoidal shaped , but i want it to be a closed shape in place of open shape
i want to join the 1st and last coordinate so that it should form a closed shape. Any help will be appreciated .
Using approach from here
outer_ccw parameters combines vertex order and desired offset direction. For CCW order and outer polygon it is 1, for inner polygon it should be -1.
def makeOffsetPoly(oldX, oldY, offset, outer_ccw = 1):
num_points = len(oldX)
for curr in range(num_points):
prev = (curr + num_points - 1) % num_points
next = (curr + 1) % num_points
vnX = oldX[next] - oldX[curr]
vnY = oldY[next] - oldY[curr]
vnnX, vnnY = normalizeVec(vnX,vnY)
nnnX = vnnY
nnnY = -vnnX
vpX = oldX[curr] - oldX[prev]
vpY = oldY[curr] - oldY[prev]
vpnX, vpnY = normalizeVec(vpX,vpY)
npnX = vpnY * outer_ccw
npnY = -vpnX * outer_ccw
bisX = (nnnX + npnX) * outer_ccw
bisY = (nnnY + npnY) * outer_ccw
bisnX, bisnY = normalizeVec(bisX, bisY)
bislen = offset / np.sqrt((1 + nnnX*npnX + nnnY*npnY)/2)
newX.append(oldX[curr] + bislen * bisnX)
newY.append(oldY[curr] + bislen * bisnY)
x = [0, 100, 60, 40]
y = [0, 0, 50, 50]
makeOffsetPoly(x, y, 20)
print(newX, newY)
>>>[-29.424478775259594, 129.4244787752596, 66.79706177729007, 33.202938222709925]
[-14.14213562373095, -14.14213562373095, 64.14213562373095, 64.14213562373095]
Just append the first coordinates to the end of your lists.
x.append(x[0])
y.append(y[0])
newX.append(newX[0])
newY.append(newY[0])
Place this right before you plot. Here's my output

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