def save_solution(pyomo,model,name): labels = generate_cuid_names(model) solution = {} for var in model.component_data_objects(pyomo.Var): solution[labels[var]] = var.value with open('{}.json'.format(name), "w") as f: json.dump(solution, f) del solution print('Valar Morghulis\nVariable Solution Saved!')
def main1(): n = 10 Multi_n_iter = n * 100 PRS_n_iter = Multi_n_iter * n * 60 seed1 = 42 gen_multi = random.Random() # chosing the solver localsolver = create_solver('knitro') #mymodel = Rastrigin(n, -5.12, 5.12) #mymodel = Griewank(n, -600,600) mymodel = CirclePacking(4, 0, 1) #needed to retrieve variable names labels = generate_cuid_names(mymodel) tech_time = time.process_time() logfile = open("mylog.txt", 'w') gen_multi.seed(seed1) # launching multistart FoundSolution = multistart(mymodel, Multi_n_iter, gen_multi, localsolver, labels, logfile) multistart_time = time.process_time() print("-----------------\n\n") #restarting from same seed gen_multi.seed(seed1) purerandomsearch(mymodel, PRS_n_iter, gen_multi, labels, logfile) prs_time = time.process_time() print("\n--------------\nLoading... ", tech_time) print("Multistart ", multistart_time - tech_time) print("PRS ", prs_time - multistart_time) print("Total ", prs_time)
def __init__(self, reference_model): self.reference_model = None self.objective = None self.time_stages = None self.stage_to_variables_map = {} self.variable_to_stage_map = {} # the set of stochastic data objects # (possibly mapped to some distribution) self.stochastic_data = None # maps between variables and objectives self.variable_to_objectives_map = ComponentMap() self.objective_to_variables_map = ComponentMap() # maps between variables and constraints self.variable_to_constraints_map = ComponentMap() self.constraint_to_variables_map = ComponentMap() # maps between stochastic data and objectives self.stochastic_data_to_objectives_map = ComponentMap() self.objective_to_stochastic_data_map = ComponentMap() # maps between stochastic data and constraints self.stochastic_data_to_constraints_map = ComponentMap() self.constraint_to_stochastic_data_map = ComponentMap() # maps between stochastic data and variable lower and upper bounds self.stochastic_data_to_variables_lb_map = ComponentMap() self.variable_to_stochastic_data_lb_map = ComponentMap() self.stochastic_data_to_variables_ub_map = ComponentMap() self.variable_to_stochastic_data_ub_map = ComponentMap() self.variable_symbols = ComponentMap() if not isinstance(reference_model, Block): raise TypeError("reference model input must be a Pyomo model") self.reference_model = reference_model # # Extract stochastic parameters from the # StochasticDataAnnotation object # self.stochastic_data = \ _extract_stochastic_data(self.reference_model) # # Get the variable stages from the # VariableStageAnnotation object # (self.stage_to_variables_map, self.variable_to_stage_map, self._variable_stage_assignments) = \ _map_variable_stages(self.reference_model) self.time_stages = tuple(sorted(self.stage_to_variables_map)) assert self.time_stages[0] == 1 self.variable_symbols = generate_cuid_names(self.reference_model, ctype=Var) # remove the parent blocks from this map keys_to_delete = [] for var in self.variable_symbols: if var.parent_component().ctype is not Var: keys_to_delete.append(var) for key in keys_to_delete: del self.variable_symbols[key] # # Get the stage cost components from the StageCostAnnotation # and generate a dummy single-scenario scenario tree # stage_cost_annotation = locate_annotations(self.reference_model, StageCostAnnotation, max_allowed=1) if len(stage_cost_annotation) == 0: raise ValueError("Reference model is missing stage cost " "annotation: %s" % (StageCostAnnotation.__name__)) else: assert len(stage_cost_annotation) == 1 stage_cost_annotation = stage_cost_annotation[0][1] stage_cost_assignments = ComponentMap( stage_cost_annotation.expand_entries()) stage1_cost = None stage2_cost = None for cdata, stagenum in stage_cost_assignments.items(): if stagenum == 1: stage1_cost = cdata elif stagenum == 2: stage2_cost = cdata if stage1_cost is None: raise ValueError("Missing stage cost annotation " "for time stage: 1") if stage2_cost is None: raise ValueError("Missing stage cost annotation " "for time stage: 2") assert stage1_cost is not stage2_cost self._stage1_cost = stage1_cost self._stage2_cost = stage2_cost # # Extract the locations of variables and stochastic data # within the model # sto_obj = StochasticObjectiveAnnotation() for objcntr, obj in enumerate( self.reference_model.component_data_objects(Objective, active=True, descend_into=True), 1): if objcntr > 1: raise ValueError( "Reference model can not contain more than one " "active objective") self.objective = obj self.objective_sense = obj.sense obj_params = tuple( self._collect_mutable_parameters(obj.expr).values()) self.objective_to_stochastic_data_map[obj] = [] for paramdata in obj_params: if paramdata in self.stochastic_data: self.stochastic_data_to_objectives_map.\ setdefault(paramdata, []).append(obj) self.objective_to_stochastic_data_map[obj].\ append(paramdata) if len(self.objective_to_stochastic_data_map[obj]) == 0: del self.objective_to_stochastic_data_map[obj] else: # TODO: Can we make this declaration sparse # by identifying which variables have # stochastic coefficients? How to handle # non-linear expressions? sto_obj.declare(obj) obj_variables = tuple(self._collect_variables(obj.expr).values()) self.objective_to_variables_map[obj] = [] for var in obj_variables: self.variable_to_objectives_map.\ setdefault(var, []).append(obj) self.objective_to_variables_map[obj].append(var) if len(self.objective_to_variables_map[obj]) == 0: del self.objective_to_variables_map[obj] sto_conbounds = StochasticConstraintBoundsAnnotation() sto_conbody = StochasticConstraintBodyAnnotation() for con in self.reference_model.component_data_objects( Constraint, active=True, descend_into=True): lower_params = tuple( self._collect_mutable_parameters(con.lower).values()) body_params = tuple( self._collect_mutable_parameters(con.body).values()) upper_params = tuple( self._collect_mutable_parameters(con.upper).values()) # TODO: Can we make this declaration sparse # by idenfifying which variables have # stochastic coefficients? How to handle # non-linear expressions? Currently, this # code also fails to detect that mutable # "constant" expressions might fall out # of the body and into the bounds. if len(body_params): sto_conbody.declare(con) if len(body_params) or \ len(lower_params) or \ len(upper_params): sto_conbounds.declare( con, lb=bool(len(lower_params) or len(body_params)), ub=bool(len(upper_params) or len(body_params))) all_stochastic_params = {} for param in itertools.chain(lower_params, body_params, upper_params): if param in self.stochastic_data: all_stochastic_params[id(param)] = param if len(all_stochastic_params) > 0: self.constraint_to_stochastic_data_map[con] = [] # no params will appear twice in this iteration for param in all_stochastic_params.values(): self.stochastic_data_to_constraints_map.\ setdefault(param, []).append(con) self.constraint_to_stochastic_data_map[con].\ append(param) body_variables = tuple(self._collect_variables(con.body).values()) self.constraint_to_variables_map[con] = [] for var in body_variables: self.variable_to_constraints_map.\ setdefault(var, []).append(con) self.constraint_to_variables_map[con].append(var) # For now, it is okay to have SOSConstraints in the # representation of a problem, but the SOS # constraints can't have custom weights that # represent stochastic data for soscon in self.reference_model.component_data_objects( SOSConstraint, active=True, descend_into=True): for var, weight in soscon.get_items(): weight_params = tuple( self._collect_mutable_parameters(weight).values()) if param in self.stochastic_data: raise ValueError( "SOSConstraints with stochastic data are currently" " not supported in embedded stochastic programs. " "The SOSConstraint component '%s' has a weight " "term for variable '%s' that references stochastic" " parameter '%s'" % (soscon.name, var.name, param.name)) self.variable_to_constraints_map.\ setdefault(var, []).append(soscon) self.constraint_to_variables_map.\ setdefault(soscon, []).append(var) sto_varbounds = StochasticVariableBoundsAnnotation() for var in self.reference_model.component_data_objects( Var, descend_into=True): lower_params = tuple( self._collect_mutable_parameters(var.lb).values()) upper_params = tuple( self._collect_mutable_parameters(var.ub).values()) if (len(lower_params) > 0) or \ (len(upper_params) > 0): sto_varbounds.declare(var, lb=bool(len(lower_params) > 0), ub=bool(len(upper_params) > 0)) self.variable_to_stochastic_data_lb_map[var] = [] for param in lower_params: if param in self.stochastic_data: self.stochastic_data_to_variables_lb_map.\ setdefault(param, []).append(var) self.variable_to_stochastic_data_lb_map[var].\ append(param) if len(self.variable_to_stochastic_data_lb_map[var]) == 0: del self.variable_to_stochastic_data_lb_map[var] self.variable_to_stochastic_data_ub_map[var] = [] for param in upper_params: if param in self.stochastic_data: self.stochastic_data_to_variables_ub_map.\ setdefault(param, []).append(var) self.variable_to_stochastic_data_ub_map[var].\ append(param) if len(self.variable_to_stochastic_data_ub_map[var]) == 0: del self.variable_to_stochastic_data_ub_map[var] # # Generate the explicit annotations # # first make sure these annotations do not already exist if len( locate_annotations(self.reference_model, StochasticConstraintBoundsAnnotation)) > 0: raise ValueError( "Reference model can not contain " "a StochasticConstraintBoundsAnnotation declaration.") if len( locate_annotations(self.reference_model, StochasticConstraintBodyAnnotation)) > 0: raise ValueError( "Reference model can not contain " "a StochasticConstraintBodyAnnotation declaration.") if len( locate_annotations(self.reference_model, StochasticObjectiveAnnotation)) > 0: raise ValueError("Reference model can not contain " "a StochasticObjectiveAnnotation declaration.") # now add any necessary annotations if sto_obj.has_declarations: assert not hasattr( self.reference_model, ".pyspembeddedsp_stochastic_objective_annotation") setattr(self.reference_model, ".pyspembeddedsp_stochastic_objective_annotation", sto_obj) if sto_conbody.has_declarations: assert not hasattr( self.reference_model, ".pyspembeddedsp_stochastic_constraint_body_annotation") setattr(self.reference_model, ".pyspembeddedsp_stochastic_constraint_body_annotation", sto_conbody) if sto_conbounds.has_declarations: assert not hasattr( self.reference_model, ".pyspembeddedsp_stochastic_constraint_bounds_annotation") setattr(self.reference_model, ".pyspembeddedsp_stochastic_constraint_bounds_annotation", sto_conbounds) if sto_varbounds.has_declarations: assert not hasattr( self.reference_model, ".pyspembeddedsp_stochastic_variable_bounds_annotation") setattr(self.reference_model, ".pyspembeddedsp_stochastic_variable_bounds_annotation", sto_varbounds)
mymodel = CirclePacking(i, 0, 1) Multi_n_iter = i * 5 PRS_n_iter = Multi_n_iter * i * 20 seed1 = 42 gen_multi = random.Random() print(gen_multi) # chosing the solver localsolver = create_solver(path + solver) print(mymodel) # needed to retrieve variable names labels = generate_cuid_names(mymodel) logfile = open("mylog.txt", 'w') gen_multi.seed(seed1) if algo == "Multistart": FoundSolution, points = multistart(mymodel, Multi_n_iter, gen_multi, localsolver, labels, epsilon=10**-eps, logfile=logfile) elif algo == "MBH":
def test_generate_cuid_names(self): model = Block(concrete=True) model.x = Var() model.y = Var([1, 2]) model.V = Var([('a', 'b'), (1, '2'), (3, 4)]) model.b = Block(concrete=True) model.b.z = Var([1, '2']) setattr(model.b, '.H', Var(['a', 2])) model.B = Block(['a', 2], concrete=True) setattr(model.B['a'], '.k', Var()) model.B[2].b = Block() model.B[2].b.x = Var() cuids = generate_cuid_names(model) self.assertEqual(len(cuids), 26) for obj in [ model.x, model.y, model.y_index, model.y[1], model.y[2], model.V, model.V_index, model.V['a', 'b'], model.V[1, '2'], model.V[3, 4], model.b, model.b.z, model.b.z_index, model.b.z[1], model.b.z['2'], getattr(model.b, '.H'), getattr(model.b, '.H_index'), getattr(model.b, '.H')['a'], getattr(model.b, '.H')[2], model.B, model.B_index, model.B['a'], getattr(model.B['a'], '.k'), model.B[2], model.B[2].b, model.B[2].b.x ]: assert repr(ComponentUID(obj)) == cuids[obj] del cuids[obj] self.assertEqual(len(cuids), 0) cuids = generate_cuid_names(model, descend_into=False) self.assertEqual(len(cuids), 15) for obj in [ model.x, model.y, model.y_index, model.y[1], model.y[2], model.V, model.V_index, model.V['a', 'b'], model.V[1, '2'], model.V[3, 4], model.b, model.B, model.B_index, model.B['a'], model.B[2] ]: assert repr(ComponentUID(obj)) == cuids[obj] del cuids[obj] self.assertEqual(len(cuids), 0) cuids = generate_cuid_names(model, ctype=Var) self.assertEqual(len(cuids), 21) for obj in [ model.x, model.y, model.y[1], model.y[2], model.V, model.V['a', 'b'], model.V[1, '2'], model.V[3, 4], model.b, model.b.z, model.b.z[1], model.b.z['2'], getattr(model.b, '.H'), getattr(model.b, '.H')['a'], getattr(model.b, '.H')[2], model.B, model.B['a'], getattr(model.B['a'], '.k'), model.B[2], model.B[2].b, model.B[2].b.x ]: assert repr(ComponentUID(obj)) == cuids[obj] del cuids[obj] self.assertEqual(len(cuids), 0) cuids = generate_cuid_names(model, ctype=Var, descend_into=False) self.assertEqual(len(cuids), 8) for obj in [ model.x, model.y, model.y[1], model.y[2], model.V, model.V['a', 'b'], model.V[1, '2'], model.V[3, 4] ]: assert repr(ComponentUID(obj)) == cuids[obj] del cuids[obj] self.assertEqual(len(cuids), 0)
def main3(): infofile = open("infoMStart.txt", 'w') infofile.write("N R_FOUND SOLUTION PERC_ERR TIME_MBH\n") Rfile = open("real_R.txt", 'r') lines = Rfile.readlines() n_min = 2 n_max = 50 real_R = [0] * n_max for i in range(n_min, n_max): real_R[i] = lines[i - 1].split()[1] for i in range(n_min, n_max): n = 6 max_no_improve = n * 2 seed1 = 123 seed2 = 48 gen = random.Random() pert = random.Random() # chosing the solver localsolver = create_solver('knitro') # mymodel = Rastrigin(n, -5.12, 5.12) # mymodel = Griewank(n, -600,600) mymodel = CirclePacking(i, 0, 1) # mymodel = CubeCirclePacking(8,0,1) #needed to retrieve variable names labels = generate_cuid_names(mymodel) tech_time = time.process_time() gen.seed(seed1) pert.seed(seed2) delta = 0.8 logfile = open("mylog.txt", 'w') # launching multistart r = float(real_R[i]) FoundSolution = multistart(mymodel, gen, localsolver, labels, max_no_improve, pert, delta, logfile, infofile, i, r) multistart_time = time.process_time() infofile.write("{0:8.8f} \n".format(multistart_time - tech_time)) logfile.close() print("\n--------------\nLoading... ", tech_time) print("MBH ", multistart_time - tech_time) print("Total ", mbh_time) infofile.close()
def __init__(self, reference_model): self.reference_model = None self.objective = None self.time_stages = None self.stage_to_variables_map = {} self.variable_to_stage_map = {} # the set of stochastic data objects # (possibly mapped to some distribution) self.stochastic_data = None # maps between variables and objectives self.variable_to_objectives_map = ComponentMap() self.objective_to_variables_map = ComponentMap() # maps between variables and constraints self.variable_to_constraints_map = ComponentMap() self.constraint_to_variables_map = ComponentMap() # maps between stochastic data and objectives self.stochastic_data_to_objectives_map = ComponentMap() self.objective_to_stochastic_data_map = ComponentMap() # maps between stochastic data and constraints self.stochastic_data_to_constraints_map = ComponentMap() self.constraint_to_stochastic_data_map = ComponentMap() # maps between stochastic data and variable lower and upper bounds self.stochastic_data_to_variables_lb_map = ComponentMap() self.variable_to_stochastic_data_lb_map = ComponentMap() self.stochastic_data_to_variables_ub_map = ComponentMap() self.variable_to_stochastic_data_ub_map = ComponentMap() self.variable_symbols = ComponentMap() if not isinstance(reference_model, Block): raise TypeError("reference model input must be a Pyomo model") self.reference_model = reference_model # # Extract stochastic parameters from the # StochasticDataAnnotation object # self.stochastic_data = \ _extract_stochastic_data(self.reference_model) # # Get the variable stages from the # VariableStageAnnotation object # (self.stage_to_variables_map, self.variable_to_stage_map, self._variable_stage_assignments) = \ _map_variable_stages(self.reference_model) self.time_stages = tuple(sorted(self.stage_to_variables_map)) assert self.time_stages[0] == 1 self.variable_symbols = generate_cuid_names(self.reference_model, ctype=Var) # remove the parent blocks from this map keys_to_delete = [] for var in self.variable_symbols: if var.parent_component().type() is not Var: keys_to_delete.append(var) for key in keys_to_delete: del self.variable_symbols[key] # # Get the stage cost components from the StageCostAnnotation # and generate a dummy single-scenario scenario tree # stage_cost_annotation = locate_annotations( self.reference_model, StageCostAnnotation, max_allowed=1) if len(stage_cost_annotation) == 0: raise ValueError( "Reference model is missing stage cost " "annotation: %s" % (StageCostAnnotation.__name__)) else: assert len(stage_cost_annotation) == 1 stage_cost_annotation = stage_cost_annotation[0][1] stage_cost_assignments = ComponentMap( stage_cost_annotation.expand_entries()) stage1_cost = None stage2_cost = None for cdata, stagenum in stage_cost_assignments.items(): if stagenum == 1: stage1_cost = cdata elif stagenum == 2: stage2_cost = cdata if stage1_cost is None: raise ValueError("Missing stage cost annotation " "for time stage: 1") if stage2_cost is None: raise ValueError("Missing stage cost annotation " "for time stage: 2") assert stage1_cost is not stage2_cost self._stage1_cost = stage1_cost self._stage2_cost = stage2_cost # # Extract the locations of variables and stochastic data # within the model # sto_obj = StochasticObjectiveAnnotation() for objcntr, obj in enumerate( self.reference_model.component_data_objects( Objective, active=True, descend_into=True), 1): if objcntr > 1: raise ValueError( "Reference model can not contain more than one " "active objective") self.objective = obj self.objective_sense = obj.sense obj_params = tuple( self._collect_mutable_parameters(obj.expr).values()) self.objective_to_stochastic_data_map[obj] = [] for paramdata in obj_params: if paramdata in self.stochastic_data: self.stochastic_data_to_objectives_map.\ setdefault(paramdata, []).append(obj) self.objective_to_stochastic_data_map[obj].\ append(paramdata) if len(self.objective_to_stochastic_data_map[obj]) == 0: del self.objective_to_stochastic_data_map[obj] else: # TODO: Can we make this declaration sparse # by identifying which variables have # stochastic coefficients? How to handle # non-linear expressions? sto_obj.declare(obj) obj_variables = tuple( self._collect_variables(obj.expr).values()) self.objective_to_variables_map[obj] = [] for var in obj_variables: self.variable_to_objectives_map.\ setdefault(var, []).append(obj) self.objective_to_variables_map[obj].append(var) if len(self.objective_to_variables_map[obj]) == 0: del self.objective_to_variables_map[obj] sto_conbounds = StochasticConstraintBoundsAnnotation() sto_conbody = StochasticConstraintBodyAnnotation() for con in self.reference_model.component_data_objects( Constraint, active=True, descend_into=True): lower_params = tuple( self._collect_mutable_parameters(con.lower).values()) body_params = tuple( self._collect_mutable_parameters(con.body).values()) upper_params = tuple( self._collect_mutable_parameters(con.upper).values()) # TODO: Can we make this declaration sparse # by idenfifying which variables have # stochastic coefficients? How to handle # non-linear expressions? Currently, this # code also fails to detect that mutable # "constant" expressions might fall out # of the body and into the bounds. if len(body_params): sto_conbody.declare(con) if len(body_params) or \ len(lower_params) or \ len(upper_params): sto_conbounds.declare(con, lb=bool(len(lower_params) or len(body_params)), ub=bool(len(upper_params) or len(body_params))) all_stochastic_params = {} for param in itertools.chain(lower_params, body_params, upper_params): if param in self.stochastic_data: all_stochastic_params[id(param)] = param if len(all_stochastic_params) > 0: self.constraint_to_stochastic_data_map[con] = [] # no params will appear twice in this iteration for param in all_stochastic_params.values(): self.stochastic_data_to_constraints_map.\ setdefault(param, []).append(con) self.constraint_to_stochastic_data_map[con].\ append(param) body_variables = tuple( self._collect_variables(con.body).values()) self.constraint_to_variables_map[con] = [] for var in body_variables: self.variable_to_constraints_map.\ setdefault(var, []).append(con) self.constraint_to_variables_map[con].append(var) # For now, it is okay to have SOSConstraints in the # representation of a problem, but the SOS # constraints can't have custom weights that # represent stochastic data for soscon in self.reference_model.component_data_objects( SOSConstraint, active=True, descend_into=True): for var, weight in soscon.get_items(): weight_params = tuple( self._collect_mutable_parameters(weight).values()) if param in self.stochastic_data: raise ValueError( "SOSConstraints with stochastic data are currently" " not supported in embedded stochastic programs. " "The SOSConstraint component '%s' has a weight " "term for variable '%s' that references stochastic" " parameter '%s'" % (soscon.name, var.name, param.name)) self.variable_to_constraints_map.\ setdefault(var, []).append(soscon) self.constraint_to_variables_map.\ setdefault(soscon, []).append(var) sto_varbounds = StochasticVariableBoundsAnnotation() for var in self.reference_model.component_data_objects( Var, descend_into=True): lower_params = tuple( self._collect_mutable_parameters(var.lb).values()) upper_params = tuple( self._collect_mutable_parameters(var.ub).values()) if (len(lower_params) > 0) or \ (len(upper_params) > 0): sto_varbounds.declare(var, lb=bool(len(lower_params) > 0), ub=bool(len(upper_params) > 0)) self.variable_to_stochastic_data_lb_map[var] = [] for param in lower_params: if param in self.stochastic_data: self.stochastic_data_to_variables_lb_map.\ setdefault(param, []).append(var) self.variable_to_stochastic_data_lb_map[var].\ append(param) if len(self.variable_to_stochastic_data_lb_map[var]) == 0: del self.variable_to_stochastic_data_lb_map[var] self.variable_to_stochastic_data_ub_map[var] = [] for param in upper_params: if param in self.stochastic_data: self.stochastic_data_to_variables_ub_map.\ setdefault(param, []).append(var) self.variable_to_stochastic_data_ub_map[var].\ append(param) if len(self.variable_to_stochastic_data_ub_map[var]) == 0: del self.variable_to_stochastic_data_ub_map[var] # # Generate the explicit annotations # # first make sure these annotations do not already exist if len(locate_annotations(self.reference_model, StochasticConstraintBoundsAnnotation)) > 0: raise ValueError("Reference model can not contain " "a StochasticConstraintBoundsAnnotation declaration.") if len(locate_annotations(self.reference_model, StochasticConstraintBodyAnnotation)) > 0: raise ValueError("Reference model can not contain " "a StochasticConstraintBodyAnnotation declaration.") if len(locate_annotations(self.reference_model, StochasticObjectiveAnnotation)) > 0: raise ValueError("Reference model can not contain " "a StochasticObjectiveAnnotation declaration.") # now add any necessary annotations if sto_obj.has_declarations: assert not hasattr(self.reference_model, ".pyspembeddedsp_stochastic_objective_annotation") setattr(self.reference_model, ".pyspembeddedsp_stochastic_objective_annotation", sto_obj) if sto_conbody.has_declarations: assert not hasattr(self.reference_model, ".pyspembeddedsp_stochastic_constraint_body_annotation") setattr(self.reference_model, ".pyspembeddedsp_stochastic_constraint_body_annotation", sto_conbody) if sto_conbounds.has_declarations: assert not hasattr(self.reference_model, ".pyspembeddedsp_stochastic_constraint_bounds_annotation") setattr(self.reference_model, ".pyspembeddedsp_stochastic_constraint_bounds_annotation", sto_conbounds) if sto_varbounds.has_declarations: assert not hasattr(self.reference_model, ".pyspembeddedsp_stochastic_variable_bounds_annotation") setattr(self.reference_model, ".pyspembeddedsp_stochastic_variable_bounds_annotation", sto_varbounds)
def test_generate_cuid_names(self): model = Block(concrete=True) model.x = Var() model.y = Var([1,2]) model.V = Var([('a','b'),(1,'2'),(3,4)]) model.b = Block(concrete=True) model.b.z = Var([1,'2']) setattr(model.b, '.H', Var(['a',2])) model.B = Block(['a',2], concrete=True) setattr(model.B['a'],'.k', Var()) model.B[2].b = Block() model.B[2].b.x = Var() cuids = generate_cuid_names(model) self.assertEqual(len(cuids), 26) for obj in [model.x, model.y, model.y_index, model.y[1], model.y[2], model.V, model.V_index, model.V['a','b'], model.V[1,'2'], model.V[3,4], model.b, model.b.z, model.b.z_index, model.b.z[1], model.b.z['2'], getattr(model.b, '.H'), getattr(model.b, '.H_index'), getattr(model.b, '.H')['a'], getattr(model.b, '.H')[2], model.B, model.B_index, model.B['a'], getattr(model.B['a'],'.k'), model.B[2], model.B[2].b, model.B[2].b.x]: assert repr(ComponentUID(obj)) == cuids[obj] del cuids[obj] self.assertEqual(len(cuids), 0) cuids = generate_cuid_names(model, descend_into=False) self.assertEqual(len(cuids), 15) for obj in [model.x, model.y, model.y_index, model.y[1], model.y[2], model.V, model.V_index, model.V['a','b'], model.V[1,'2'], model.V[3,4], model.b, model.B, model.B_index, model.B['a'], model.B[2]]: assert repr(ComponentUID(obj)) == cuids[obj] del cuids[obj] self.assertEqual(len(cuids), 0) cuids = generate_cuid_names(model, ctype=Var) self.assertEqual(len(cuids), 21) for obj in [model.x, model.y, model.y[1], model.y[2], model.V, model.V['a','b'], model.V[1,'2'], model.V[3,4], model.b, model.b.z, model.b.z[1], model.b.z['2'], getattr(model.b, '.H'), getattr(model.b, '.H')['a'], getattr(model.b, '.H')[2], model.B, model.B['a'], getattr(model.B['a'],'.k'), model.B[2], model.B[2].b, model.B[2].b.x]: assert repr(ComponentUID(obj)) == cuids[obj] del cuids[obj] self.assertEqual(len(cuids), 0) cuids = generate_cuid_names(model, ctype=Var, descend_into=False) self.assertEqual(len(cuids), 8) for obj in [model.x, model.y, model.y[1], model.y[2], model.V, model.V['a','b'], model.V[1,'2'], model.V[3,4]]: assert repr(ComponentUID(obj)) == cuids[obj] del cuids[obj] self.assertEqual(len(cuids), 0)