TypeError: '_SumExpression' object is not iterable - pyomo

Please I am new to Pyomo. I have tried to run the following codes:
from pyutilib.misc import import_file
from pyomo.environ import *
model = ConcreteModel()
model.name = "Transmission Investment planning problem_"
#Sets
#Epoch
model.E = RangeSet(0,3) #No. of Epochs
#System nodes
model.N = ['N1', 'N2', 'N3'] #Names of Bus nodes
#model.n_name= Param(model.N)
model.G = ['G1', 'G2', 'G3'] #Names of generators
model.LI = ['L1', 'L2', 'L3'] #Nnames of Transmission lines
#Scalar Parameters
model.int_rate = 0.05 #interest rate
model.vll = 3000 #value of loss load(£/MWh)
model.tau_period = 8760 #Time duration of demand period (hours)
model.base = 100 #MVA base
model.ref = {'N3'} #reference node
model.vadegree = 0 #phase angle of reference node
#Discount factors
L = 5
Y= len(model.E)*L
irate = range(0,(Y-1))
def disc_factor(i):
disc = [1/((1 + model.int_rate)**i) for i in irate]
return disc
model.cum_disc_inv_cost = [sum(disc_factor(i)[(i*L):]) for i in model.E] #investment discount factor
model.cum_disc_op_cost = [sum(disc_factor(i)[(i*L):((i+1)*L)]) for i in model.E] #operation discount factor
#Demand Periods
model.t_demand = {'N1': 105, 'N2': 210, 'N3': 735} #demand at nodes (MW)
model.demand_curtailed = Var(model.E, model.N, initialize = 0) #curtailed demand (MW)
#Generation Units
model.ge_max = {'G1': 200, 'G2': 200, 'G3': 1000} #maximum stable power generation(MW)
model.ge_marginal_cost = {'G1': 30, 'G2': 35, 'G3': 40} #marginal cost of generation units (£/MWh)
#Bus to generation incidence matrix
model.B = {('N1','G1'): 1, ('N1','G2'): 0, ('N1','G3'): 0, ('N2','G1'): 0, ('N2','G2'): 1, ('N2','G3'): 0, ('N3','G1'): 0, ('N3','G2'): 0, ('N3','G3'): 1,}
#Transmission lines
model.li_x = {'L1': 0.2, 'L2': 0.2, 'L3': 0.2} #reactance of transmission line(p.u)
model.li_max_f = 150 #maximum capaciy provided for line expansion (MW)
model.li_f = {'L1': 100, 'L2': 100, 'L3': 100} #initial capacity for line l (MW)
model.li_sending_bus = {'L1': 'N1', 'L2': 'N1', 'L3': 'N2'} #sending bus for line l
model.li_receiving_bus = {'L1': 'N2', 'L2': 'N3', 'L3': 'N3'} #receiving bus for line l
model.li_length = {'L1': 100, 'L2': 100, 'L3': 100} #length of line l (km)
#Expansion Options
model.inv_cost_var = 4000000 #Annuitized variable investment cost for line l (£/MW.km.yr)
#Bus to line incidence matrix
model.I = {('N1','L1'): 1, ('N1','L2'): 1, ('N1','L3'): 0, ('N2','L1'): -1, ('N2','L2'): 0, ('N2','L3'): 1, ('N3','L1'): 0, ('N3','L2'): -1, ('N3','L3'): -1,}
#Variables
#Transmission line power flow limits
def fl_inv(model, i, l):
return (0, model.li_max_f)
model.li_f_inv = Var(model.E, model.LI, bounds = fl_inv) #transmission capacity to be built for line l (MW)
#Transmission line investment and operation contraints
model.f = Var(model.LI, model.E, initialize=0)
def fl_rule(model, l, j, i):
if i:
return model.f[l,j] >= -(model.li_f_inv[j,l] + model.li_f[l])
else:
return model.f[l,j] <= (model.li_f_inv[j,l] + model.li_f[l])
model.bound_f = Constraint(model.LI, model.E, [0,1], rule=fl_rule)
##generation limit
def fg(model, i, g):
return (0, model.ge_max[g])
model.ge_output = Var(model.E, model.G, initialize = 0, bounds = fg)
#phase angles for the nodes
def theta(model, e, n):
for n in model.N:
if n == model.ref:
model.theta[e, n].fixed = True
return model.vadegree
else: return 0
model.theta = Var(model.E, model.N, initialize = theta)
def line_equation(model, l, e):
return model.f[l, e] == model.base/model.li_x[l] *(sum(model.theta[e, n] for n in model.N if n == model.li_sending_bus[l]) - sum(model.theta[e, n] for n in model.N if n == model.li_receiving_bus[l]))
model.line_equation = Constraint(model.LI, model.E, rule = line_equation)
def system_balance(model, e, n):
return sum(model.B[n, g] * model.ge_output[e, g] for g in model.G) \
+ sum(model.I[n, l] * model.f[l, e] for l in model.LI) \
- model.t_demand[n] + model.demand_curtailed[e, n] == 0
model.SystemBalance = Constraint(model.E, model.N, rule=system_balance)
#OBJECTIVE FUNCTION
def objective_mincost(model):
for i in model.E:
return sum(model.cum_disc_inv_cost[i] * sum(model.li_f_inv[i, l] * model.inv_cost_var * model.li_length[l] for l in model.LI) + model.cum_disc_op_cost[i] * (model.tau_period * (sum(model.ge_max[g] * (model.ge_marginal_cost[g]) for g in model.G) + sum(model.demand_curtailed[i, n] for n in model.N * model.vll))))
model.objective = Objective(rule = objective_mincost, sense = minimize)
opt = SolverFactory('gurobi')
results = opt.solve(model) # solves and updates instance
model.display()
I got the following errorcodes:
ERROR: Rule failed when generating expression for objective objective:
TypeError: '_SumExpression' object is not iterable ERROR: Constructing component 'objective' from data=None failed:
TypeError: '_SumExpression' object is not iterable
Please any suggestions on where the problem might be and possible solution?
Thank you.

You have two places where model.E is multiplied by something that is not a set. You probably meant to parenthesize your sums differently (i.e., this is mostly a problem with how your sums are organized)

Related

Pyomo KeyError: "Error accessing indexed component: Index '0' is not valid for array component 'li_f_inv'"

I was trying to run the following code on Pyomo. It is a simple Transmission Expansion problem using a concrete model.
Thanks jsiirola. I am actually just learning Pyomo, thats why I might be making silly mistakes. I implemented all you suggested as shown below:
from pyutilib.misc import import_file
from pyomo.environ import *
import networkx as nx
model = ConcreteModel()
model.name = "DTEPM_trial_concrete"
#Sets
#Epoch
model.E = Set(initialize = [0, 1, 2, 3])
model.E_n = Set(model.E, initialize = {0:[1,2,3,4,5], 1:[6,7,8,9,10], 2:[11,12,13,14,15], 3:[16,17,18,19,20]})
#System nodes
model.N = ['N1', 'N2', 'N3']
model.n_name= Param(model.N, within = Integers)
#T = Set()
model.G = ['G1', 'G2', 'G3']
model.LI = ['L1', 'L2', 'L3']
#Scalar Parameters
model.int_rate = 0.05
model.vll = 3000
model.tau_period = 8760
def R_discount_inv_init(model, i):
return sum(1 / (1 + model.int_rate)**(i - 1) for i in model.E)
model.cum_disc_inv_cost = Param(model.E, initialize = R_discount_inv_init)
def R_discount_op_init(model, i):
for index in model.E_n:
return sum(1 / (1 + model.int_rate)**(i - 1) for i in model.E_n[index])
model.cum_disc_op_cost = Param(model.E, initialize = R_discount_op_init)
#Demand Periods
model.t_demand = {'N1': 1.05, 'N2': 2.10, 'N3': 7.35}
model.demand_curtailed = Var(model.E, model.N, within = NonNegativeReals)
#Generation Units
model.ge_max = {'G1': 2.00, 'G2': 2.00, 'G3': 7.35}
model.ge_marginal_cost = {'G1': 30, 'G2': 35, 'G3': 40}
model.B = {('N1','G1'): 1, ('N1','G2'): 0, ('N1','G3'): 0, ('N2','G1'): 0, ('N2','G2'): 1, ('N2','G3'): 0, ('N3','G1'): 0, ('N3','G2'): 0, ('N3','G3'): 1,}
#Transmission lines
model.li_x = {'L1': 0.2, 'L2': 0.2, 'L3': 0.2}
model.li_max_f = 1.50
model.li_f = {'L1': 1.00, 'L2': 1.00, 'L3': 1.00}
model.li_sending_bus = {'L1': 'N1', 'L2': 'N1', 'L3': 'N2'}
model.li_receiving_bus = {'L1': 'N2', 'L2': 'N3', 'L3': 'N3'}
model.li_length = {'L1': 100, 'L2': 100, 'L3': 100}
#Expansion Options
model.inv_cost_var = 4000000
nodes = ['N1', 'N2', 'N3']
edges = [['N1', 'N2'], ['N1', 'N3'], ['N2', 'N3']]
I = nx.DiGraph()
I.add_nodes_from(nodes)
I.add_edges_from(edges)
model.I = -nx.incidence_matrix(I, oriented=True) # this returns a scipy sparse matrix
#Variables
#Transmission line power flow limits
def fl_inv(model, i, l):
return (0, model.li_max_f)
model.li_f_inv = Var(model.E, model.LI, bounds = fl_inv)
#Transmission line investment and operation contraints
model.f = Var(model.LI, model.E, initialize=0)
def fl_rule(model, l, j, i):
if i:
return model.f[l,j] >= -(model.li_f_inv[j,l] + model.li_f[l])
else:
return model.f[l,j] <= (model.li_f_inv[j,l] + model.li_f[l])
model.bound_f = Constraint(model.LI, model.E, [0,1], rule=fl_rule)
#generation limit
def fg(model, i, g):
return (0, model.ge_max[g])
model.ge_output = Var(model.G, model.E, initialize = 0, bounds = fg)
#phase angles for the nodes
model.theta = Var(model.E, model.N, within = NonNegativeReals)
def line_equation(model, e, l):
return model.bound_f[l] == (1/model.li_x(l) for l in model.LI) *(sum(model.theta[n] for n in model.N if model.n_name[n] == model.li_sending_bus[l]) - sum(model.theta[n] for n in model.N if model.n_name[n] == model.li_receiving_bus[l]))
model.line_equation = Constraint(model.LI, model.E, rule = line_equation)
def system_balance(model, e, n):
return sum(model.b[n, g] * model.ge_output[g] for g in model.G) \
+ sum(model.I[n, l] * model.f[l] for l in model.LI) \
- sum(model.t_demand[n] - model.demand_curtailed[n]) == 0
model.SystemBalance = Constraint(model.E, model.N, rule=system_balance)
#OBJECTIVE FUNCTION
def objective_mincost(model):
return sum( model.cum_disc_inv_cost[e] for e in model.E * sum (model.li_f_inv[l] * model.inv_cost_var[l] * model.li_length[l]) + model.cum_disc_op_cost[e] * (model.tau_period * (sum(model.ge_max[g] * (model.ge_marginal_cost[g])) + sum(model.demand_curtailed[n] * model.vll))))
model.objective = Objective(rule = objective_mincost, sense = minimize)
opt = SolverFactory('gurobi')
results = opt.solve(model) # solves and updates instance
model.display()
But received the following new error message:
ERROR: Rule failed when generating expression for constraint line_equation with index ('L3', 0):
KeyError: "Error accessing indexed component: Index 'L3' is not valid for array component 'bound_f'"
ERROR: Constructing component 'line_equation' from data=None failed:
KeyError: "Error accessing indexed component: Index 'L3' is not valid for array component 'bound_f'"
Please what do you think might be wrong?
Thank you
As the error indicates, you are not passing valid indices to model.li_f_inv in the rule for model.f. Your Var model.li_f_inv is declared as:
model.li_f_inv = Var(model.E, model.LI, bounds = fl_inv)
Your current rule for model.f is only passing a single index to model.li_f_inv, which is invalid. That means your rule for model.f needs to be updated to pass the correct indices:
#Transmission line investment and operation contraints
model.f = Var(model.LI, model.E, initialize=0)
def fl_rule(model, l, j, i):
if i:
return model.f[l,j] >= -(model.li_f_inv[j,l] + model.li_f[l])
else:
return model.f[l,j] <= (model.li_f_inv[j,l] + model.li_f[l])
model.bound_f = Constraint(model.LI, model.E, [0,1], rule=fl_rule)
Also note that you are transposing the indexing sets between the definition of model.f and the sets implied by the fl_rule function.
EDIT: I failed to notice that in your original post, you were attempting to use variables (li_f_inv) in the bounds of another variable (f). This isn't a valid math program (not to mention, not valid Pyomo). You need to express the variable bounds as a Constraint. Also, while Pyomo allows you to express range constraints (lb <= body <= ub), both lb and ub must not be potentially variable. Since that is not the case here, you must express the two bounds constraints separately.

TypeError( "Cannot convert object of type '%s' (value = %s) to a numeric value."

I am new to Pyomo and using it to practice some optimisation problems in Transmission Expansion Planning. I tried solving the model below:
from pyutilib.misc import import_file
from pyomo.environ import *
import networkx as nx
model = ConcreteModel()
model.name = "DTEPM_trial_concrete"
#Sets
#Epoch
model.E = Set(initialize = [0, 1, 2, 3])
model.E_n = Set(model.E, initialize = {0:[1,2,3,4,5], 1:[6,7,8,9,10], 2:[11,12,13,14,15], 3:[16,17,18,19,20]})
#System nodes
model.N = ['N1', 'N2', 'N3']
#model.n_name= Param(model.N)
#T = Set()
model.G = ['G1', 'G2', 'G3']
model.LI = ['L1', 'L2', 'L3']
#Scalar Parameters
model.int_rate = 0.05
model.vll = 3000
model.tau_period = 8760
model.base = 100
model.ref = ['N3']
model.vadegree = 0
def R_discount_inv_init(model, i):
return sum(1 / (1 + model.int_rate)**(i - 1) for i in model.E)
model.cum_disc_inv_cost = Param(model.E, initialize = R_discount_inv_init)
def R_discount_op_init(model, i):
for index in model.E_n:
return sum(1 / (1 + model.int_rate)**(i - 1) for i in model.E_n[index])
model.cum_disc_op_cost = Param(model.E, initialize = R_discount_op_init)
#Demand Periods
model.t_demand = {'N1': 105, 'N2': 210, 'N3': 735}
model.demand_curtailed = Var(model.E, model.N, within = NonNegativeReals)
#Generation Units
model.ge_max = {'G1': 200, 'G2': 200, 'G3': 1000}
model.ge_marginal_cost = {'G1': 30, 'G2': 35, 'G3': 40}
model.B = {('N1','G1'): 1, ('N1','G2'): 0, ('N1','G3'): 0, ('N2','G1'): 0, ('N2','G2'): 1, ('N2','G3'): 0, ('N3','G1'): 0, ('N3','G2'): 0, ('N3','G3'): 1,}
#Transmission lines
model.li_x = {'L1': 0.2, 'L2': 0.2, 'L3': 0.2}
model.li_max_f = 150
model.li_f = {'L1': 100, 'L2': 100, 'L3': 100}
model.li_sending_bus = {'L1': 'N1', 'L2': 'N1', 'L3': 'N2'}
model.li_receiving_bus = {'L1': 'N2', 'L2': 'N3', 'L3': 'N3'}
model.li_length = {'L1': 100, 'L2': 100, 'L3': 100}
#Expansion Options
model.inv_cost_var = 4000000
nodes = ['N1', 'N2', 'N3']
edges = [['N1', 'N2'], ['N1', 'N3'], ['N2', 'N3']]
I = nx.DiGraph()
I.add_nodes_from(nodes)
I.add_edges_from(edges)
model.I = -nx.incidence_matrix(I, oriented=True) # this returns a scipy sparse matrix
#Variables
#Transmission line power flow limits
def fl_inv(model, i, l):
return (0, model.li_max_f)
model.li_f_inv = Var(model.E, model.LI, bounds = fl_inv)
#Transmission line investment and operation contraints
model.f = Var(model.LI, model.E, initialize=0)
def fl_rule(model, l, j, i):
if i:
return model.f[l,j] >= -(model.li_f_inv[j,l] + model.li_f[l])
else:
return model.f[l,j] <= (model.li_f_inv[j,l] + model.li_f[l])
model.bound_f = Constraint(model.LI, model.E, [0,1], rule=fl_rule)
##generation limit
def fg(model, i, g):
return (0, model.ge_max[g])
model.ge_output = Var(model.E, model.G, initialize = 0, bounds = fg)
#phase angles for the nodes
def theta(model, e, n):
for n in model.N:
if n == model.ref:
model.theta[e, n].fixed = True
return model.vadegree
else: return 0
model.theta = Var(model.E, model.N, initialize = theta)
def line_equation(model, l, e):
return model.f[l, e] == model.base/model.li_x[l] *(sum(model.theta[e, n] for n in model.N if n == model.li_sending_bus[l]) - sum(model.theta[e, n] for n in model.N if n == model.li_receiving_bus[l]))
model.line_equation = Constraint(model.LI, model.E, rule = line_equation)
def system_balance(model, e, n):
return sum(model.b[n, g] * model.ge_output[g] for g in model.G) \
+ sum(model.I[n, l] * model.f[l, e] for l in model.LI) \
- sum(model.t_demand[n] - model.demand_curtailed[n]) == 0
model.SystemBalance = Constraint(model.E, model.N, rule=system_balance)
#OBJECTIVE FUNCTION
def objective_mincost(model):
return sum( model.cum_disc_inv_cost[e] for e in model.E * sum (model.li_f_inv[e, l] * model.inv_cost_var[l] * model.li_length[l]) + model.cum_disc_op_cost[e] * (model.tau_period * (sum(model.ge_max[g] * (model.ge_marginal_cost[g])) + sum(model.demand_curtailed[n] * model.vll))))
model.objective = Objective(rule = objective_mincost, sense = minimize)
opt = SolverFactory('gurobi')
results = opt.solve(model) # solves and updates instance
model.display()
I got the following error messages from running the codes:
ERROR: Rule failed when generating expression for constraint line_equation with index ('L2', 0):
TypeError: Cannot convert object of type 'generator' (value = . at 0x000001B6F840E360>) to a numeric value.
ERROR: Constructing component 'line_equation' from data=None failed:
TypeError: Cannot convert object of type 'generator' (value = . at 0x000001B6F840E360>) to a numeric value.
Please how do you suggest I solve it?
Thank you.
It looks like you are missing a sum() in your line equation definition.
'(model.base/model.li_x(l) for l in model.LI)' is a generator not a numeric value, it's a grammar error.
You could check your DC power flow equations carefully.

Why I'm getting "TypeError: Failed to convert object of type <type 'dict'> to Tensor."?

I'm new to TF and ML.
Details about data: Features(x) - (70 x 70 x 70) tensor for each sample, y - a float for each sample.
TFRecords created with the following code:
def convert_to_tf_records():
def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _float64_feature(value):
return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))
tfrecords_filename = 'A-100-h2-h2o.tfrecords'
writer = tf.python_io.TFRecordWriter(tfrecords_filename)
# Get data from db for now.
db = connect('results-60-70.db')
data = db.select(selection='Ti')
i = 0
for row in data:
desc = np.array(json.loads(row.descriptor), dtype=np.float32)
print(desc.shape)
be = float(row.binding_energy) * 23 # Convert to Kcal/mol ?
desc = desc.flatten()
desc = desc.tostring()
example = tf.train.Example(features=tf.train.Features(feature={'voxel_grid': _bytes_feature(desc), 'binding_energy': _float64_feature(be)}))
writer.write(example.SerializeToString())
i += 1
if i >= 10:
break
Input function:
def my_input_function(fname, perform_shuffle=False, repeat_count=None):
def _parse_elements(example):
features = tf.parse_single_example(example, features={'voxel_grid': tf.FixedLenFeature([], tf.string), 'binding_energy': tf.FixedLenFeature([], tf.float32)})
vg = tf.decode_raw(features['voxel_grid'], tf.float32)
vg = tf.reshape(vg, [70, 70, 70])
vg = tf.convert_to_tensor(vg, dtype=tf.float32)
vg = {'voxel_grid': vg}
e = tf.cast(features['binding_energy'], tf.float32)
return vg, e
def input_function():
dataset = tf.data.TFRecordDataset(fname).map(_parse_elements)
dataset = dataset.repeat(repeat_count)
dataset = dataset.batch(5)
dataset = dataset.prefetch(1)
if perform_shuffle:
dataset.shuffle(20)
iterator = dataset.make_one_shot_iterator()
batch_features, batch_labels = iterator.get_next()
return batch_features, batch_labels
return input_function
Model function:
def my_model_function(features, labels, mode):
if mode == tf.estimator.ModeKeys.PREDICT:
tf.logging.info("my_model_fn: PREDICT, {}".format(mode))
elif mode == tf.estimator.ModeKeys.EVAL:
tf.logging.info("my_model_fn: EVAL, {}".format(mode))
elif mode == tf.estimator.ModeKeys.TRAIN:
tf.logging.info("my_model_fn: TRAIN, {}".format(mode))
feature_columns = [tf.feature_column.numeric_column('voxel_grid', shape=(70, 70, 70), dtype=tf.float32)]
# Create the layer of input
input_layer = tf.feature_column.input_layer(features, feature_columns)
input_layer = tf.reshape(input_layer, [-1, 70, 70, 70, 1])
# Convolution layers
conv1 = tf.layers.conv3d(inputs=input_layer, strides=(2, 2, 2), filters=32, kernel_size=(7, 7, 7))
conv2 = tf.layers.conv3d(inputs=conv1, strides=(2, 2, 2), filters=32, kernel_size=(7, 7, 7))
pool3 = tf.layers.max_pooling3d(inputs=conv2, pool_size=[2, 2, 2], strides=2)
flat = tf.layers.flatten(pool3)
dense1 = tf.layers.dense(inputs=flat, units=10, activation=tf.nn.relu)
dense2 = tf.layers.dense(inputs=dense1, units=10, activation=tf.nn.relu)
output = tf.layers.dense(inputs=dense2, units=1)
predictions = {'binding_energy': output}
if mode == tf.estimator.ModeKeys.PREDICT:
return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)
# Calculate loss
loss = tf.losses.mean_squared_error(labels=labels, predictions=predictions)
if mode == tf.estimator.ModeKeys.TRAIN:
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
train_op = optimizer.minimize(loss=loss, global_step=tf.train.get_global_step())
return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)
# Add evaluation metrics
eval_metric_ops = {"mse": tf.metrics.mean_squared_error(labels=labels, predictions=predictions['binding_energy'])}
if mode == tf.estimator.ModeKeys.EVAL:
return tf.estimator.EstimatorSpec(mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)
When calling model.train using
model = tf.estimator.Estimator(model_fn=my_model_function, model_dir='./model_dir')
model.train(input_fn=my_input_function('A-100-h2-h2o.tfrecords'), steps=100)
I get the following error.
TypeError: Failed to convert object of type to Tensor.
Found it!
changing
# Calculate loss
loss = tf.losses.mean_squared_error(labels=labels, predictions=predictions)
to
# Calculate loss
loss = tf.losses.mean_squared_error(labels=labels, predictions=predictions['binding_energy'])
solves the issue.

Modify fibonacci python in order to print f(0),f(1),.....f(n)

Here is my original function.
def f(n):
if n<0:
print("Error.Bad input")
elif n==0:
return 1
elif n==1:
return 1
else:
return f(n-1)+f(n-2)
Is it possible to modify Fibonacci Python function so that not only does it have to calculate f(n) but also it prints f(0), f(1), f(2),....,f(n) in the function?
Instead of using a recursive function you could do this:
def f(n):
if n < 0:
print("Error.Bad input")
elif n <= 1:
return 1
else:
result = [1, 2]
print(1)
print(2)
for i in range(n - 2):
result = [result[1], result[0] + result[1]]
print(result[1])
return result[1]
def fib(n):
pred, curr = 0, 1
k = 1
while (k<n):
pred, curr = curr, curr + pred
print(curr)
k = k + 1
Probably the optimal "pythonic" way to create a sequence (a list) of fibonacci numbers of arbitraly size n is to define a function which does so, than to call that function with size as an input argument. For example:
def fibonacci_sequence(n):
x = [0, 1]
[x.append(x[-1] + x[-2]) for i in range(n - len(x))]
return x
fibonacci_sequence(15)
The result is:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
Bottom-up approach. Complexity is O(n):
def fib(n):
if n in (1, 2):
return 1
i = z = 1
for _ in range(3, n+1):
z, i = i + z, z
return z

How to draw a contour plot using Python?

https://www.dropbox.com/sh/zeaa8ouwq3oo8c3/AAAgRNJwRL_TGwFWkBD6KFV0a?dl=0
My data: data.csv
I tried to draw a contour plot using Python.
import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate
import time
import datetime
f = open("data.csv","r")
title = f.readline()
lines = f.readlines()
print len(lines)
xlist = []
ylist = []
zlist = []
for line in lines:
titlecells = title.split(',')
linecells = line.split(',')
print len(titlecells)
for i in range(1,len(titlecells)):
items = titlecells[i].split('/')
items = map(int, items)
dt = datetime.datetime(items[0], items[1], items[2])
sdt = datetime.datetime(1900,1,1)
delta = int(str(dt - sdt).split(' ')[0]) / 10
xlist.append(delta)
ylist.append(linecells[0].replace('0~','').replace('m',''))
try:
zlist.append(float(linecells[i]))
except ValueError:
zlist.append(0)
print len(xlist)
print len(ylist)
print len(zlist)
ylist = map(int, ylist)
x = np.array(xlist)
y = np.array(ylist)
z = np.array(zlist)
print z
# Generate data: for N=1e6, the triangulation hogs 1 GB of memory
'''N = 1000000
x, y = 10 * np.random.random((2, N))
rho = np.sin(3*x) + np.cos(7*y)**3
print x.shape,y.shape'''
# Set up a regular grid of interpolation points
xi, yi = np.linspace(x.min(), x.max(), 300), np.linspace(y.min(), y.max(), 300)
xi, yi = np.meshgrid(xi, yi)
print xi,yi
# Interpolate; there's also method='cubic' for 2-D data such as here
zi = scipy.interpolate.griddata((x, y), z, (xi, yi), method='linear')
plt.imshow(zi, vmin=z.min(), vmax=z.max(), origin='lower',
extent=[x.min(), x.max(), y.min(), y.max()])
plt.colorbar()
plt.show()
Output obtained with Matlab:
Input data: TKJS_20150903.xlsx
Matlab Code
clear all; close all;
% read data
list_d2 = dir('C:\\MATLAB_CODE\\Monitoring_well\\TS_Analysis\\MW\\data\\*.xlsx');
for k = 1:length(list_d2)
station = list_d2(k).name(1:13);
filename = sprintf('C:\\MATLAB_CODE\\Monitoring_well\\TS_Analysis\\MW\\data\\%s.xlsx', station);
[MW_data, data_tex, alldata] = xlsread(filename,5);
MW_data = MW_data(2:end,:);
date = datenum(cellfun(#num2str,alldata(3:end,1),'UniformOutput', false),'yyyy/mm/dd');
depth = cell2mat(alldata(2,2:end))';
% MW_data=MW_data';
% compute gap between every rings
for i = 1:length(MW_data(:,1))
for j = 1:length(MW_data(1,:))-1
disp(i,j) = MW_data(i,j)-MW_data(i,j+1);
end
end
vel=disp';
% dlmwrite('displacement.txt', disp, '\t');
for i = 2:length(depth)-1
thick(i) = depth(i+1)-depth(i);
end
thick=thick(1:end);
thick1=repmat(thick,length(disp(:,1)),1);
% dlmwrite('thickness.txt', thick, '\t');
% % check data
% figure(1);
% plot(MW_data,depth*(-1));
% set well depth
yg1 = 0; yg2 = 300;
% make grid
[xgrid,ygrid] = meshgrid(date(1):30:date(end),yg1:1:yg2);
xint=repmat(date',length(thick),1);
yint=repmat(depth(2:end),1,length(date));
xint1 = reshape(xint, numel(xint), 1);
yint1 = reshape(yint, numel(yint), 1);
zint1 = reshape(vel, numel(vel), 1);
% [Xwdp,Ywdp,Zwdp] = griddata(xint1,yint1,zint1,xgrid,ygrid);
[Xwdp,Ywdp,Zwdp] = surfergriddata(xint1, yint1, zint1, xgrid, ygrid, 'kriging');
% save('cresult.mat');
h1 = figure;
set(h1,'paperorientation', 'portrait', 'color', [1 1 1], 'papertype','A4');
set(gcf,'Units','Centimeter','Position', [5 5 18 20]);
set(gcf,'PaperPositionMode','auto');
set(gca, 'FontSize', 12, 'FontWeight','bold');
set(gca, 'FontName', 'Arial')
% box on;
% pcolor(xgrid, ygrid, Zwdp);
surf(xgrid,ygrid,Zwdp);
shading interp;
view(0,90);
colorbar;
z1=round(min(min(vel)));
z2=round(max(max(vel)));
caxis([z1 z2]);
% caxis([-0.5 0.5]);
% caxis([-1.2 1.2]);
% caxis([-1 2]);
% caxis([-1 8]);
% x1=floor(min(min(date)));
% x2=round(max(max(date)));
axis([ min(min(date)), max(max(date)), 0, 300]);
set(gca,'fontsize',5,'xticklabelmode','manual','yticklabelmode','manual');
pa = get(gca,'xlim');
pb = get(gca,'ylim');
pa1 = (pa(1):pa(2));
pa2 = (pb(1):pb(2));
indx = find(mod(pa1-pa1(1),60)==0);
indy = find(mod(pa2,50)==0);
set(gca,'xtick',pa1(indx),'xticklabel',[]);
xrtime=get(gca,'xtick');
xstime=datestr(xrtime,'yyyy/mm');
for n=1:length(xrtime)
text(xrtime(n),308,xstime(n,:),'HorizontalAlignment','center','fontsize',8,'fontweight','bold')
end
set(gca,'ytick',pa2(indy),'yticklabel',pa2(indy),'fontsize',8,'fontweight','bold');
set(gca,'YDir','reverse','tickdir','out'); hold on
% gridnumy = zint1(:,1);
%
% for j = 1:length(gridnumy)
% line(xgrid(1,:)',repmat(gridnumy(j),size(xgrid,2),1),'color','black','linestyle','-');
% end
well=list_d2(k).name(1:4)
title({well 'Monitoring Well'}, 'FontSize', 12, 'FontWeight','bold');
xlabel('Date', 'FontSize', 12, 'FontWeight','bold');
ylabel('Depth (m)', 'Fontsize', 12, 'FontWeight','bold');
% clabel('Compression (cm)', 'Fontsize', 12, 'FontWeight','bold');
list_p4=sprintf('C:\\MATLAB_CODE\\Monitoring_well\\TS_Analysis\\MW\\%s', well);
print('-dpng','-r300', list_p4);
clear MW_data data_tex xint xint1 yint yint1 zint1 thick thick1 vel disp
end
I want to get similar Output using Python.
But, I don't know how to improve my code.