def add_parameter(self, expression): """ Adds a parameter to the problem from a string expression Parameters: expression: string, variable name expression in python code with a value Example: problem.add_parameter('A = 5') problem.add_parameter('p[i,j] = 0.20 if j==0 else 0.30 for i in range(24) for j in range(5)') """ # parse the rest of the expression (name, indexvalue, value) = parse.variable(expression) if value == []: raise ValueError("Parameters are required to have a value. {}".format(expression)) # add the parameter if len(indexvalue) == 0: setattr(self.model, name, pm.Param(default=value, mutable=True)) else: setattr(self.model, name, pm.Param(indexvalue, default=lambda model, *args: value[args], mutable=True)) self.parameters[name] = getattr(self.model, name)
def add_variable(self, expression): """ Adds a variable to the problem from a string expression Parameters: expression: string, variable name expression in python code with optional default value Example: problem = jsonipopt.Problem() problem.add_variable('Reals x[j] for j in range(25)') problem.add_variable('Reals p[i,j] = 0.20 if j==0 else 0.30 for i in range(24) for j in range(5)') """ # get the domain of the variable splitexpression = expression.split(" ") domainexpr = splitexpression[0] if domainexpr in self.validDomainExpressions: domain = eval("pm." + domainexpr) else: raise ValueError( "The domain {} is not a valid domain. Valid domains are:\n{}".format( domainexpr, self.validDomainExpressions ) ) restexpression = " ".join(splitexpression[1:]) # parse the rest of the expression (name, indexvalue, initial) = parse.variable(restexpression) # add the variable if len(indexvalue) == 0: if initial == []: setattr(self.model, name, pm.Var(domain=domain)) else: setattr(self.model, name, pm.Var(domain=domain, initialize=initial)) else: if initial == []: setattr(self.model, name, pm.Var(indexvalue, domain=domain)) else: setattr( self.model, name, pm.Var(indexvalue, domain=domain, initialize=lambda model, *args: initial[args]) ) self.variables[name] = getattr(self.model, name)