def prepare_for_merge(model, suffix): suffix = str(suffix) path = model['path'] with open(os.path.join(repo_dir, path), 'r') as f: nodes = ampl.parse(f.read(), path).nodes # Rename declarations. names = {} visitor = RenamingVisitor(names) for n in nodes: if isinstance(n, ampl.Decl): new_name = n.name + suffix names[n.name] = new_name n.name = new_name if n.indexing: n.indexing.accept(visitor) if n.body: n.body.accept(visitor) if isinstance(n, ampl.DataStmt): n.set_name = n.set_name + suffix n.param_names = [name + suffix for name in n.param_names] # Find the first objective and partition the nodes around it. obj_index = find_obj(nodes) # Add objective offset to make the optimal value nonnegative. obj = nodes[obj_index] sign = 1 if obj.kind == 'minimize' else -1 best_obj = sign * model['best_obj'] offset = math.ceil(abs(min(0.0, best_obj))) obj.body = ampl.ParenExpr(obj.body) if obj.kind == 'maximize': obj.body = ampl.UnaryExpr('-', obj.body) if offset > 0: obj.body = ampl.ParenExpr(ampl.BinaryExpr('+', obj.body, ampl.Reference(str(offset)))) return nodes[:obj_index], obj, nodes[obj_index + 1:], best_obj + offset
def prepare_for_merge(model, suffix): suffix = str(suffix) path = model['path'] with open(os.path.join(repo_dir, path), 'r') as f: nodes = ampl.parse(f.read(), path).nodes # Rename declarations. names = {} visitor = RenamingVisitor(names) for n in nodes: if isinstance(n, ampl.Decl): new_name = n.name + suffix names[n.name] = new_name n.name = new_name if n.indexing: n.indexing.accept(visitor) if n.body: n.body.accept(visitor) if isinstance(n, ampl.DataStmt): n.set_name = n.set_name + suffix n.param_names = [name + suffix for name in n.param_names] # Find the first objective and partition the nodes around it. obj_index = find_obj(nodes) # Add objective offset to make the optimal value nonnegative. obj = nodes[obj_index] sign = 1 if obj.kind == 'minimize' else -1 best_obj = sign * model['best_obj'] offset = math.ceil(abs(min(0.0, best_obj))) obj.body = ampl.ParenExpr(obj.body) if obj.kind == 'maximize': obj.body = ampl.UnaryExpr('-', obj.body) if offset > 0: obj.body = ampl.ParenExpr( ampl.BinaryExpr('+', obj.body, ampl.Reference(str(offset)))) return nodes[:obj_index], obj, nodes[obj_index + 1:], best_obj + offset
def check_parse_expr(input, expr): "Check parsing arithmetic expression." assert equal_nodes(ampl.parse('var x = {};'.format(input), 'in'), ampl.CompoundStmt([ampl.Decl('var', 'x', None, [ampl.InitAttr(expr)])]))
def check_parse(input, *nodes): assert equal_nodes(ampl.parse(input, 'in'), ampl.CompoundStmt(nodes))