I have a function where I need to minimize c_init to make totalF output zero. the problem is that I have some constants over this function which are Es, f_slong and f_c. I need to repeat this whole minimization for 30 different cases meaning that I have 30 different constant variables and 30 different c_init initial values. Then, my aim is to obtain what the values for c_init will be at the end of the algorithm. However, those constant variables give me trouble. I do not have any inequality (I am not sure if I have to define it anyway), I strongly feel that my problem is to define the location and inputs of *args, I've tested out many different scenarios but they all failed. Could anyone help me out? Those constant variables should be coming from their list of array in every iteration and sending through the minimization function.
def c_neutral_un(c_init, Es, f_slong, f_c):
eps_s = e_cu_un * (d - c_init) / c_init
eps_s_prime = e_cu_un * (c_init - d_prime) / c_init
if Es * eps_s > f_slong:
f_s = f_slong
else:
f_s = Es * eps_s
if Es * eps_s_prime > f_slong:
f_s_prime = f_slong
else:
f_s_prime = Es * eps_s_prime
T = As * f_s
Cs_prime = As_prime * (f_s_prime - alfa1 * f_c)
Cc_conc = alfa1 * f_c * b * beta1 * c_init
totalF = Cc_conc + Cs_prime - T
return totalF
c = []
for i in range(31)
bnd = ([0, 200])
x0 = c_init[i]
Es = Es[i]
f_slong = f_slong[i]
f_c = f_c[i]
res = minimize(c_neutral_un, x0, args=([Es, f_slong, f_c], True) method = "SLSQP", bounds = bnd)
c.append(res.x)
THere is an error for constant assignment like Es = Es[i]
def c_neutral_un(c_init, Es, f_slong, f_c):
eps_s = e_cu_un * (d - c_init) / c_init
eps_s_prime = e_cu_un * (c_init - d_prime) / c_init
if Es * eps_s > f_slong:
f_s = f_slong
else:
f_s = Es * eps_s
if Es * eps_s_prime > f_slong:
f_s_prime = f_slong
else:
f_s_prime = Es * eps_s_prime
T = As * f_s
Cs_prime = As_prime * (f_s_prime - alfa1 * f_c)
Cc_conc = alfa1 * f_c * b * beta1 * c_init
totalF = Cc_conc + Cs_prime - T
return totalF
c = []
for i in range(31):
bnd = ([0, 200])
x0 = c_init[i]
Es2 = Es[i]
f_slong2 = f_slong[i]
f_c2 = f_c[i]
res = minimize(c_neutral_un, x0, args=([Es2, f_slong2, f_c2], True),method = "SLSQP", bounds = bnd)
c.append(res.x)
Related
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.
I am using ode solver to solve stiff problem (since odeint function could not able to solve it). But by this way also I have some warnings and my plot get saturate at some point. Here is image What should I do? Here is the list of warnings:
DVODE-- Warning..internal T (=R1) and H (=R2) are
such that in the machine, T + H = T on the next step
(H = step size). solver will continue anyway
In above, R1 = 0.3667661010318D+00 R2 = 0.1426374862242D-16
DVODE-- Warning..internal T (=R1) and H (=R2) are
such that in the machine, T + H = T on the next step
(H = step size). solver will continue anyway
In above, R1 = 0.3667661010318D+00 R2 = 0.1426374862242D-16
DVODE-- Above warning has been issued I1 times.
it will not be issued again for this problem
In above message, I1 = 2
DVODE-- At current T (=R1), MXSTEP (=I1) steps
taken on this call before reaching TOUT
In above message, I1 = 500
In above message, R1 = 0.3667661010318D+00
My code:
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as si
def func():
#arguments:::
w = 1./3.
xi = 2.86
phi1 = 1.645
phi2 = 2.* 1.202
gt = 10.**(-60)
Lt = (1.202*gt)/np.pi
Lin = 10.**-5
Lf = 0.49
dt = 0.0001
gin = gt*Lt/Lin
xin = (-np.log((3. - (xi**2)*Lin)/(3. - (xi**2)*Lt)) + np.log(Lin/Lt))/4.0
uin = -(np.log(Lin/Lt))/2.
state0 = [gin,xin,uin]
print state0
def eq(L, state):
g = state[0]
x = state[1]
u = state[2]
N = (-2.*g/(6.*np.pi + 5.*g))*(18./(1. - 2.*L) + 5.*np.log(1.- 2.*L) - phi1 + 6. )
B = (-(2. - N)*L) - ((g/np.pi)* (5.*np.log(1.-2.*L) - phi2 + (5.*N/40.)))
Eqs = np.zeros((3))
gdl = Eqs[0] = ((2.+N)*g)/B
xdl = Eqs[1] = -(2./(3.*(1.+w)))* (1./(1.-(xi**2)*L/3.))*(1./B)
udl = Eqs[2]= 1./B
return Eqs
ode = si.ode(eq)
# BDF method suited to stiff systems of ODEs
ode.set_integrator('vode',nsteps=500,method='bdf')
ode.set_initial_value(state0,Lin)
L = []
G = []
while ode.successful() and ode.t < Lf:
ode.integrate(ode.t + dt)
L.append(ode.t)
G.append(ode.y)
lam = np.vstack(L)
g,x,u = np.vstack(G).T
return g,x,u,lam
r= func()
L = r[3]
g = r[0]
lng = np.log10(g)
x = r[1]
u = r[2]
w = 1./3.
xi = 2.86
O_A = np.zeros(len(L))
q = np.zeros(len(L))
for i in np.arange(len(L)):
O_A[i] = xi**2*L[i]/3.
alpha = 2./ ((3.+3.*w) * (1.- (L[i]*xi**2)/3.) )
q[i] = 1./alpha - 1.
n = np.zeros(len(L)) #eta(n)
b = np.zeros(len(L))
for j in np.arange(len(L)):
n[j] =(-2.*g[j]/(6.*np.pi + 5.*g[j]))*(18./(1. - 2.*L[j]) + 5.*np.log(1.- 2.*L[j]) - 1.645 + 6. )
b[j]= (-(2. - n[j])*L[j]) - ((g[j]/np.pi)* (5.*np.log(1.-2.*L[j]) - 2.* 1.202 + ((5.*n[j])/4.)))
P = np.zeros(len(x))
for k in np.arange(len(x)):
C = (((3. - (xi**2)*L[k])/g[k])**(3./4.)) * (((2.*L[k] + (u[k]*b[k]))*xi**2) + (n[k] * (3.- L[k]*xi**2)) )
P[k] = (np.exp(3.*x[k])) * (np.exp(4.*u[k])) * C
plt.figure()
plt.plot(L,P)
plt.xlabel('Lambda ---->')
plt.ylabel('P ----->')
plt.title('lambda Vs P')
plt.show()