Beispiel #1
0
def from_pandas_dataframe(bqm_df, offset=0.0, interactions=[]):
    """Build a binary quadratic model from a pandas dataframe.

    Args:
        bqm_df (:class:`pandas.DataFrame`):
            A pandas dataframe. The row and column indices should be that variables of the binary
            quadratic program. The values should be the coefficients of a qubo.

        offset (optional, default=0.0):
            The constant offset for the binary quadratic program.

        interactions (iterable, optional, default=[]):
            Any additional 0.0-bias interactions to be added to the binary quadratic model.

    Returns:
        :class:`.BinaryQuadraticModel`

    """
    bqm = BinaryQuadraticModel({}, {}, offset, Vartype.BINARY)

    for u, row in bqm_df.iterrows():
        for v, bias in row.iteritems():
            if u == v:
                bqm.add_variable(u, bias)
            elif bias:
                bqm.add_interaction(u, v, bias)

    for u, v in interactions:
        bqm.add_interaction(u, v, 0.0)

    return bqm
Beispiel #2
0
def from_numpy_matrix(mat, variable_order=None, offset=0.0, interactions=[]):
    """Build a binary quadratic model from a numpy matrix.

    Args:
        mat (:class:`numpy.matrix`):
            A square numpy matrix. The coefficients of a qubo.

        variable_order (list, optional):
            If variable_order is provided, provides the labels for the variables in the binary
            quadratic program, otherwise the row/column indices will be used. If variable_order
            is longer than the matrix, the extra values are ignored.

        offset (optional, default=0.0):
            The constant offset for the binary quadratic program.

        interactions (iterable, optional, default=[]):
            Any additional 0.0-bias interactions to be added to the binary quadratic model.

    Returns:
        :class:`.BinaryQuadraticModel`

    """
    import numpy as np

    if mat.ndim != 2:
        raise ValueError("expected input mat to be a square matrix")  # pragma: no cover

    num_row, num_col = mat.shape
    if num_col != num_row:
        raise ValueError("expected input mat to be a square matrix")  # pragma: no cover

    if variable_order is None:
        variable_order = list(range(num_row))

    bqm = BinaryQuadraticModel({}, {}, offset, Vartype.BINARY)

    for (row, col), bias in np.ndenumerate(mat):
        if row == col:
            bqm.add_variable(variable_order[row], bias)
        elif bias:
            bqm.add_interaction(variable_order[row], variable_order[col], bias)

    for u, v in interactions:
        bqm.add_interaction(u, v, 0.0)

    return bqm