Skip to content

LpReader

A class for reading lp files

Methods

read(obj) classmethod

Reads in an LP file and parse it into a flipy.LpProblem object

Parameters:

Name Type Description Default
obj Union[str, IO, _io.StringIO]

The content of an LP file as a string or read buffer

required

Exceptions:

Type Description
ValueError

If obj is unreadable and is not a LP string

Returns:

Type Description
LpProblem

Parsed LpProblem based on the LP file

Source code in flipy/lp_reader.py
@classmethod
def read(cls, obj: Union[str, IO, TextIO, io.StringIO]) -> LpProblem:
    """ Reads in an LP file and parse it into a flipy.LpProblem object

    Raises
    ------
    ValueError
        If `obj` is unreadable and is not a LP string

    Parameters
    ----------
    obj: str or buffer
        The content of an LP file as a string or read buffer

    Returns
    -------
    LpProblem
        Parsed LpProblem based on the LP file
    """
    if hasattr(obj, 'read'):
        content = obj.read()
    elif isinstance(obj, (str, bytes)):
        content = obj
        try:
            if os.path.isfile(content):
                with open(content, "rb") as f:
                    content = f.read()
        except (TypeError, ValueError):
            pass
    else:
        raise ValueError("Cannot read object of type %r" % type(obj).__name__)

    content = content.strip()

    problem_name = cls._find_problem_name(content)

    is_maximize, sections = cls._split_content_by_sections(cls._remove_comments(content))

    obj_name, obj_expr, obj_coeff = cls._parse_named_expression(sections['objective'])
    constraints = cls._parse_constraints(sections['constraints']) if 'constraints' in sections else []
    bounds = cls._parse_bounds(sections['bounds']) if 'bounds' in sections else {}
    generals = cls._parse_generals(sections['generals']) if 'generals' in sections else []
    binaries = cls._parse_binaries(sections['binaries']) if 'binaries' in sections else []

    lp_variables = {}
    lp_objective = LpObjective(obj_name, constant=obj_coeff, sense=Maximize if is_maximize else Minimize)

    for obj_var_name, obj_coeff in obj_expr.items():
        obj_var = cls._find_variable(lp_variables, obj_var_name)
        lp_objective.expr[obj_var] = obj_coeff

    lp_constraints = []
    for constraint in constraints:
        lhs_expr = LpExpression()
        for var_name, cons_var_coeff in constraint['lhs'].items():
            var = cls._find_variable(lp_variables, var_name)
            lhs_expr.expr[var] = cons_var_coeff
        lhs_expr.const = constraint['lhs_const']

        rhs_expr = LpExpression()
        for var_name, cons_var_coeff in constraint['rhs'].items():
            var = cls._find_variable(lp_variables, var_name)
            rhs_expr.expr[var] = cons_var_coeff
        rhs_expr.const = constraint['rhs_const']

        lp_constraints.append(LpConstraint(lhs_expr, constraint['sense'], rhs_expr, name=constraint['name']))

    cls._parse_variables(lp_variables, bounds, generals, binaries)

    return LpProblem(problem_name, lp_objective=lp_objective, lp_constraints=lp_constraints)