Instruction:
Create a Python 3 function for
returning a penalty model with the given specification.

Response:
def get_penalty_model(specification):
    """Factory function for penaltymodel_maxgap.

    Args:
        specification (penaltymodel.Specification): The specification
            for the desired penalty model.

    Returns:
        :class:`penaltymodel.PenaltyModel`: Penalty model with the given specification.

    Raises:
        :class:`penaltymodel.ImpossiblePenaltyModel`: If the penalty cannot be built.

    Parameters:
        priority (int): -100

    """

    # check that the feasible_configurations are spin
    feasible_configurations = specification.feasible_configurations
    if specification.vartype is dimod.BINARY:
        feasible_configurations = {tuple(2 * v - 1 for v in config): en
                                   for config, en in feasible_configurations.items()}

    # convert ising_quadratic_ranges to the form we expect
    ising_quadratic_ranges = specification.ising_quadratic_ranges
    quadratic_ranges = {(u, v): ising_quadratic_ranges[u][v] for u, v in specification.graph.edges}

    bqm, gap = generate(specification.graph,
                        feasible_configurations,
                        specification.decision_variables,
                        specification.ising_linear_ranges,
                        quadratic_ranges,
                        specification.min_classical_gap,
                        None)  # unspecified smt solver

    try:
        ground = max(feasible_configurations.values())
    except ValueError:
        ground = 0.0  # if empty

    return pm.PenaltyModel.from_specification(specification, bqm, gap, ground)


Instruction:
Write a Python 3 script to
insert a group of feasible configuration into the cache.

Response:
def insert_feasible_configurations(cur, feasible_configurations, encoded_data=None):
    """Insert a group of feasible configurations into the cache.

    Args:
        cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function
            is meant to be run within a :obj:`with` statement.
        feasible_configurations (dict[tuple[int]): The set of feasible
            configurations. Each key should be a tuple of variable assignments.
            The values are the relative energies.
        encoded_data (dict, optional): If a dictionary is provided, it
            will be populated with the serialized data. This is useful for
            preventing encoding the same information many times.

    Examples:
        >>> feasible_configurations = {(-1, -1): 0.0, (+1, +1): 0.0}
        >>> with pmc.cache_connect(':memory:') as cur:
        ...     pmc.insert_feasible_configurations(cur, feasible_configurations)

    """
    if encoded_data is None:
        encoded_data = {}

    if 'num_variables' not in encoded_data:
        encoded_data['num_variables'] = len(next(iter(feasible_configurations)))
    if 'num_feasible_configurations' not in encoded_data:
        encoded_data['num_feasible_configurations'] = len(feasible_configurations)
    if 'feasible_configurations' not in encoded_data or 'energies' not in encoded_data:
        encoded = {_serialize_config(config): en for config, en in feasible_configurations.items()}

        configs, energies = zip(*sorted(encoded.items()))
        encoded_data['feasible_configurations'] = json.dumps(configs, separators=(',', ':'))
        encoded_data['energies'] = json.dumps(energies, separators=(',', ':'))

    insert = """
            INSERT OR IGNORE INTO feasible_configurations(
                num_variables,
                num_feasible_configurations,
                feasible_configurations,
                energies)
            VALUES (
                :num_variables,
                :num_feasible_configurations,
                :feasible_configurations,
                :energies);
            """

    cur.execute(insert, encoded_data)


Instruction:
Can you tell what is the following Python 3 function doing
def iter_feasible_configurations(cur):
    select = \
        """
        SELECT num_variables, feasible_configurations, energies
        FROM feasible_configurations
        """
    for num_variables, feasible_configurations, energies in cur.execute(select):
        configs = json.loads(feasible_configurations)
        energies = json.loads(energies)

        yield {_decode_config(config, num_variables): energy
               for config, energy in zip(configs, energies)}

Response: Iterate over all feasible configurations in the cache.


Instruction:
Write a Python 3 script for
inversing of _serialize_config always converts to spin.

Response:
def _decode_config(c, num_variables):
    """inverse of _serialize_config, always converts to spin."""
    def bits(c):
        n = 1 << (num_variables - 1)
        for __ in range(num_variables):
            yield 1 if c & n else -1
            n >>= 1
    return tuple(bits(c))


Instruction:
Can you implement a function in Python 3 that
inserts an Ising model into the cache.

Response:
def insert_ising_model(cur, nodelist, edgelist, linear, quadratic, offset, encoded_data=None):
    """Insert an Ising model into the cache.

    Args:
        cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function
            is meant to be run within a :obj:`with` statement.
        nodelist (list): The nodes in the graph.
        edgelist (list): The edges in the graph.
        linear (dict): The linear bias associated with each node in nodelist.
        quadratic (dict): The quadratic bias associated with teach edge in edgelist.
        offset (float): The constant offset applied to the ising problem.
        encoded_data (dict, optional): If a dictionary is provided, it
            will be populated with the serialized data. This is useful for
            preventing encoding the same information many times.

    """
    if encoded_data is None:
        encoded_data = {}

    # insert graph and partially populate encoded_data with graph info
    insert_graph(cur, nodelist, edgelist, encoded_data=encoded_data)

    # need to encode the biases
    if 'linear_biases' not in encoded_data:
        encoded_data['linear_biases'] = _serialize_linear_biases(linear, nodelist)
    if 'quadratic_biases' not in encoded_data:
        encoded_data['quadratic_biases'] = _serialize_quadratic_biases(quadratic, edgelist)
    if 'offset' not in encoded_data:
        encoded_data['offset'] = offset
    if 'max_quadratic_bias' not in encoded_data:
        encoded_data['max_quadratic_bias'] = max(itervalues(quadratic))
    if 'min_quadratic_bias' not in encoded_data:
        encoded_data['min_quadratic_bias'] = min(itervalues(quadratic))
    if 'max_linear_bias' not in encoded_data:
        encoded_data['max_linear_bias'] = max(itervalues(linear))
    if 'min_linear_bias' not in encoded_data:
        encoded_data['min_linear_bias'] = min(itervalues(linear))

    insert = \
        """
        INSERT OR IGNORE INTO ising_model(
            linear_biases,
            quadratic_biases,
            offset,
            max_quadratic_bias,
            min_quadratic_bias,
            max_linear_bias,
            min_linear_bias,
            graph_id)
        SELECT
            :linear_biases,
            :quadratic_biases,
            :offset,
            :max_quadratic_bias,
            :min_quadratic_bias,
            :max_linear_bias,
            :min_linear_bias,
            graph.id
        FROM graph WHERE
            num_nodes = :num_nodes AND
            num_edges = :num_edges AND
            edges = :edges;
        """

    cur.execute(insert, encoded_data)


Instruction:
Write a Python 3 function for
serializing the linear biases.

Response:
def _serialize_linear_biases(linear, nodelist):
    """Serializes the linear biases.

    Args:
        linear: a interable object where linear[v] is the bias
            associated with v.
        nodelist (list): an ordered iterable containing the nodes.

    Returns:
        str: base 64 encoded string of little endian 8 byte floats,
            one for each of the biases in linear. Ordered according
            to nodelist.

    Examples:
        >>> _serialize_linear_biases({1: -1, 2: 1, 3: 0}, [1, 2, 3])
        'AAAAAAAA8L8AAAAAAADwPwAAAAAAAAAA'
        >>> _serialize_linear_biases({1: -1, 2: 1, 3: 0}, [3, 2, 1])
        'AAAAAAAAAAAAAAAAAADwPwAAAAAAAPC/'

    """
    linear_bytes = struct.pack('<' + 'd' * len(linear), *[linear[i] for i in nodelist])
    return base64.b64encode(linear_bytes).decode('utf-8')


Instruction:
How would you explain what the following Python 3 function does
def _serialize_quadratic_biases(quadratic, edgelist):
    # assumes quadratic is upper-triangular or reflected in edgelist
    quadratic_list = [quadratic[(u, v)] if (u, v) in quadratic else quadratic[(v, u)]
                      for u, v in edgelist]
    quadratic_bytes = struct.pack('<' + 'd' * len(quadratic), *quadratic_list)
    return base64.b64encode(quadratic_bytes).decode('utf-8')

Response: Serializes the quadratic biases.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def iter_ising_model(cur):
    select = \
        """
        SELECT linear_biases, quadratic_biases, num_nodes, edges, offset
        FROM ising_model, graph
        WHERE graph.id = ising_model.graph_id;
        """

    for linear_biases, quadratic_biases, num_nodes, edges, offset in cur.execute(select):
        nodelist = list(range(num_nodes))
        edgelist = json.loads(edges)
        yield (nodelist, edgelist,
               _decode_linear_biases(linear_biases, nodelist),
               _decode_quadratic_biases(quadratic_biases, edgelist),
               offset)

Response: Iterate over all of the Ising models in the cache.


Instruction:
Create a Python 3 function for
inversing of _serialize_linear_biases. Args: linear_string (str): base 64 encoded string of little endian 8 byte floats, one for each of the nodes in nodelist. nodelist (list): list of the form [node1, node2, ...]. Returns: dict: linear biases in a dict. Examples: >>> _decode_linear_biases('AAAAAAAA8L8AAAAAAADwPwAAAAAAAAAA', [1, 2, 3]) {1: -1.0, 2: 1.0, 3: 0.0} >>> _decode_linear_biases('AAAAAAAA8L8AAAAAAADwPwAAAAAAAAAA', [3, 2, 1]) {1: 0.0, 2: 1.0, 3: -1.0}

Response:
def _decode_linear_biases(linear_string, nodelist):
    """Inverse of _serialize_linear_biases.

    Args:
        linear_string (str): base 64 encoded string of little endian
            8 byte floats, one for each of the nodes in nodelist.
        nodelist (list): list of the form [node1, node2, ...].

    Returns:
        dict: linear biases in a dict.

    Examples:
        >>> _decode_linear_biases('AAAAAAAA8L8AAAAAAADwPwAAAAAAAAAA', [1, 2, 3])
        {1: -1.0, 2: 1.0, 3: 0.0}
        >>> _decode_linear_biases('AAAAAAAA8L8AAAAAAADwPwAAAAAAAAAA', [3, 2, 1])
        {1: 0.0, 2: 1.0, 3: -1.0}

    """
    linear_bytes = base64.b64decode(linear_string)
    return dict(zip(nodelist, struct.unpack('<' + 'd' * (len(linear_bytes) // 8), linear_bytes)))


Instruction:
Can you create a Python 3 function that
inverses of _serialize_quadratic_biases Args: quadratic_string (str) : base 64 encoded string of little endian 8 byte floats, one for each of the edges. edgelist (list): a list of edges of the form [(node1, node2), ...]. Returns: dict: J. A dict of the form {edge1: bias1, ...} where each edge is of the form (node1, node2). Example: >>> _decode_quadratic_biases('AAAAAAAA8L8AAAAAAADwP5qZmZmZmdk/', ... [(0, 1), (1, 2), (0, 2)]) {(0, 1): -1.0, (0, 2): 0.4, (1, 2): 1.0}

Response:
def _decode_quadratic_biases(quadratic_string, edgelist):
    """Inverse of _serialize_quadratic_biases

    Args:
        quadratic_string (str) : base 64 encoded string of little
            endian 8 byte floats, one for each of the edges.
        edgelist (list): a list of edges of the form [(node1, node2), ...].

    Returns:
        dict: J. A dict of the form {edge1: bias1, ...} where each
            edge is of the form (node1, node2).

    Example:
        >>> _decode_quadratic_biases('AAAAAAAA8L8AAAAAAADwP5qZmZmZmdk/',
        ...                          [(0, 1), (1, 2), (0, 2)])
        {(0, 1): -1.0, (0, 2): 0.4, (1, 2): 1.0}

    """
    quadratic_bytes = base64.b64decode(quadratic_string)
    return {tuple(edge): bias for edge, bias in zip(edgelist,
            struct.unpack('<' + 'd' * (len(quadratic_bytes) // 8), quadratic_bytes))}


Instruction:
Here you have a function in Python 3, explain what it does
def insert_penalty_model(cur, penalty_model):
    encoded_data = {}

    linear, quadratic, offset = penalty_model.model.to_ising()
    nodelist = sorted(linear)
    edgelist = sorted(sorted(edge) for edge in penalty_model.graph.edges)

    insert_graph(cur, nodelist, edgelist, encoded_data)
    insert_feasible_configurations(cur, penalty_model.feasible_configurations, encoded_data)
    insert_ising_model(cur, nodelist, edgelist, linear, quadratic, offset, encoded_data)

    encoded_data['decision_variables'] = json.dumps(penalty_model.decision_variables, separators=(',', ':'))
    encoded_data['classical_gap'] = penalty_model.classical_gap
    encoded_data['ground_energy'] = penalty_model.ground_energy

    insert = \
        """
        INSERT OR IGNORE INTO penalty_model(
            decision_variables,
            classical_gap,
            ground_energy,
            feasible_configurations_id,
            ising_model_id)
        SELECT
            :decision_variables,
            :classical_gap,
            :ground_energy,
            feasible_configurations.id,
            ising_model.id
        FROM feasible_configurations, ising_model, graph
        WHERE
            graph.edges = :edges AND
            graph.num_nodes = :num_nodes AND
            ising_model.graph_id = graph.id AND
            ising_model.linear_biases = :linear_biases AND
            ising_model.quadratic_biases = :quadratic_biases AND
            ising_model.offset = :offset AND
            feasible_configurations.num_variables = :num_variables AND
            feasible_configurations.num_feasible_configurations = :num_feasible_configurations AND
            feasible_configurations.feasible_configurations = :feasible_configurations AND
            feasible_configurations.energies = :energies;
        """

    cur.execute(insert, encoded_data)

Response: Insert a penalty model into the database.


Instruction:
Here you have a function in Python 3, explain what it does
def iter_penalty_model_from_specification(cur, specification):
    encoded_data = {}

    nodelist = sorted(specification.graph)
    edgelist = sorted(sorted(edge) for edge in specification.graph.edges)
    encoded_data['num_nodes'] = len(nodelist)
    encoded_data['num_edges'] = len(edgelist)
    encoded_data['edges'] = json.dumps(edgelist, separators=(',', ':'))
    encoded_data['num_variables'] = len(next(iter(specification.feasible_configurations)))
    encoded_data['num_feasible_configurations'] = len(specification.feasible_configurations)

    encoded = {_serialize_config(config): en for config, en in specification.feasible_configurations.items()}
    configs, energies = zip(*sorted(encoded.items()))
    encoded_data['feasible_configurations'] = json.dumps(configs, separators=(',', ':'))
    encoded_data['energies'] = json.dumps(energies, separators=(',', ':'))

    encoded_data['decision_variables'] = json.dumps(specification.decision_variables, separators=(',', ':'))
    encoded_data['classical_gap'] = json.dumps(specification.min_classical_gap, separators=(',', ':'))

    select = \
        """
        SELECT
            linear_biases,
            quadratic_biases,
            offset,
            decision_variables,
            classical_gap,
            ground_energy
        FROM penalty_model_view
        WHERE
            -- graph:
            num_nodes = :num_nodes AND
            num_edges = :num_edges AND
            edges = :edges AND
            -- feasible_configurations:
            num_variables = :num_variables AND
            num_feasible_configurations = :num_feasible_configurations AND
            feasible_configurations = :feasible_configurations AND
            energies = :energies AND
            -- decision variables:
            decision_variables = :decision_variables AND
            -- we could apply filters based on the energy ranges but in practice this seems slower
            classical_gap >= :classical_gap
        ORDER BY classical_gap DESC;
        """

    for row in cur.execute(select, encoded_data):
        # we need to build the model
        linear = _decode_linear_biases(row['linear_biases'], nodelist)
        quadratic = _decode_quadratic_biases(row['quadratic_biases'], edgelist)

        model = dimod.BinaryQuadraticModel(linear, quadratic, row['offset'], dimod.SPIN)  # always spin

        yield pm.PenaltyModel.from_specification(specification, model, row['classical_gap'], row['ground_energy'])

Response: Iterate through all penalty models in the cache matching the given specification.


Instruction:
Write a Python 3 function for
constructing a PenaltyModel from a Specification.

Response:
def from_specification(cls, specification, model, classical_gap, ground_energy):
        """Construct a PenaltyModel from a Specification.

        Args:
            specification (:class:`.Specification`): A specification that was used
                to generate the model.
            model (:class:`dimod.BinaryQuadraticModel`): A binary quadratic model
                that has ground states that match the feasible_configurations.
            classical_gap (numeric): The difference in classical energy between the ground
                state and the first excited state. Must be positive.
            ground_energy (numeric): The minimum energy of all possible configurations.

        Returns:
            :class:`.PenaltyModel`

        """

        # Author note: there might be a way that avoids rechecking all of the values without
        # side-effects or lots of repeated code, but this seems simpler and more explicit
        return cls(specification.graph,
                   specification.decision_variables,
                   specification.feasible_configurations,
                   specification.vartype,
                   model,
                   classical_gap,
                   ground_energy,
                   ising_linear_ranges=specification.ising_linear_ranges,
                   ising_quadratic_ranges=specification.ising_quadratic_ranges)


Instruction:
Make a summary of the following Python 3 code
def relabel_variables(self, mapping, inplace=True):
        # just use the relabeling of each component
        if inplace:
            Specification.relabel_variables(self, mapping, inplace=True)
            self.model.relabel_variables(mapping, inplace=True)
            return self
        else:
            spec = Specification.relabel_variables(self, mapping, inplace=False)
            model = self.model.relabel_variables(mapping, inplace=False)
            return PenaltyModel.from_specification(spec, model, self.classical_gap, self.ground_energy)

Response: Relabel the variables and nodes according to the given mapping.


Instruction:
Implement a function in Python 3 to
return a penalty model with the given specification.

Response:
def get_penalty_model(specification, database=None):
    """Factory function for penaltymodel_cache.

    Args:
        specification (penaltymodel.Specification): The specification
            for the desired penalty model.
        database (str, optional): The path to the desired sqlite database
            file. If None, will use the default.

    Returns:
        :class:`penaltymodel.PenaltyModel`: Penalty model with the given specification.

    Raises:
        :class:`penaltymodel.MissingPenaltyModel`: If the penalty model is not in the
            cache.

    Parameters:
        priority (int): 100

    """
    # only handles index-labelled nodes
    if not _is_index_labelled(specification.graph):
        relabel_applied = True
        mapping, inverse_mapping = _graph_canonicalization(specification.graph)
        specification = specification.relabel_variables(mapping, inplace=False)
    else:
        relabel_applied = False

    # connect to the database. Note that once the connection is made it cannot be
    # broken up between several processes.
    if database is None:
        conn = cache_connect()
    else:
        conn = cache_connect(database)

    # get the penalty_model
    with conn as cur:
        try:
            widget = next(iter_penalty_model_from_specification(cur, specification))
        except StopIteration:
            widget = None

    # close the connection
    conn.close()

    if widget is None:
        raise pm.MissingPenaltyModel("no penalty model with the given specification found in cache")

    if relabel_applied:
        # relabel the widget in-place
        widget.relabel_variables(inverse_mapping, inplace=True)

    return widget


Instruction:
Write a Python 3 function for
caching function for penaltymodel_cache.

Response:
def cache_penalty_model(penalty_model, database=None):
    """Caching function for penaltymodel_cache.

    Args:
        penalty_model (:class:`penaltymodel.PenaltyModel`): Penalty model to
            be cached.
        database (str, optional): The path to the desired sqlite database
            file. If None, will use the default.

    """

    # only handles index-labelled nodes
    if not _is_index_labelled(penalty_model.graph):
        mapping, __ = _graph_canonicalization(penalty_model.graph)
        penalty_model = penalty_model.relabel_variables(mapping, inplace=False)

    # connect to the database. Note that once the connection is made it cannot be
    # broken up between several processes.
    if database is None:
        conn = cache_connect()
    else:
        conn = cache_connect(database)

    # load into the database
    with conn as cur:
        insert_penalty_model(cur, penalty_model)

    # close the connection
    conn.close()


Instruction:
Implement a Python 3 function for
retrieving a PenaltyModel from one of the available PenaltyModel factories.

Response:
def get_penalty_model(specification):
    """Retrieve a PenaltyModel from one of the available factories.

    Args:
        specification (:class:`.Specification`): The specification
            for the desired PenaltyModel.

    Returns:
        :class:`.PenaltyModel`/None: A PenaltyModel as returned by
        the highest priority factory, or None if no factory could
        produce it.

    Raises:
        :exc:`ImpossiblePenaltyModel`: If the specification
            describes a penalty model that cannot be built by any
            factory.

    """

    # Iterate through the available factories until one gives a penalty model
    for factory in iter_factories():
        try:
            pm = factory(specification)
        except ImpossiblePenaltyModel as e:
            # information about impossible models should be propagated
            raise e
        except FactoryException:
            # any other type of factory exception, continue through the list
            continue

        # if penalty model was found, broadcast to all of the caches. This could be done
        # asynchronously
        for cache in iter_caches():
            cache(pm)

        return pm

    return None


Instruction:
Can you tell what is the following Python 3 function doing
def iter_factories():
    # retrieve all of the factories with
    factories = (entry.load() for entry in iter_entry_points(FACTORY_ENTRYPOINT))

    # sort the factories from highest priority to lowest. Any factory with unknown priority
    # gets assigned priority -1000.
    for factory in sorted(factories, key=lambda f: getattr(f, 'priority', -1000), reverse=True):
        yield factory

Response: Iterate through all of the factories in the entry point.


Instruction:
Given the following Python 3 function, write the documentation
def generate_bqm(graph, table, decision,
                 linear_energy_ranges=None, quadratic_energy_ranges=None, min_classical_gap=2,
                 precision=7, max_decision=8, max_variables=10,
                 return_auxiliary=False):
    """Get a binary quadratic model with specific ground states.

    Args:
        graph (:obj:`~networkx.Graph`):
            Defines the structure of the generated binary quadratic model.

        table (iterable):
            Iterable of valid configurations (of spin-values). Each configuration is a tuple of
            variable assignments ordered by `decision`.

        decision (list/tuple):
            The variables in the binary quadratic model which have specified configurations.

        linear_energy_ranges (dict, optional):
            Dict of the form {v: (min, max, ...} where min and max are the range of values allowed
            to v. The default range is [-2, 2].

        quadratic_energy_ranges (dict, optional):
            Dict of the form {(u, v): (min, max), ...} where min and max are the range of values
            allowed to (u, v). The default range is [-1, 1].

        min_classical_gap (float):
            The minimum energy gap between the highest feasible state and the lowest infeasible
            state.

        precision (int, optional, default=7):
            Values returned by the optimization solver are rounded to `precision` digits of
            precision.

        max_decision (int, optional, default=4):
            Maximum number of decision variables allowed. The algorithm is valid for arbitrary
            sizes of problem but can be extremely slow.

        max_variables (int, optional, default=4):
            Maximum number of variables allowed. The algorithm is valid for arbitrary
            sizes of problem but can be extremely slow.

        return_auxiliary (bool, optional, False):
            If True, the auxiliary configurations are returned for each configuration in table.

    Returns:
        If return_auxiliary is False:

            :obj:`dimod.BinaryQuadraticModel`: The binary quadratic model.

            float: The classical gap.

        If return_auxiliary is True:

            :obj:`dimod.BinaryQuadraticModel`: The binary quadratic model.

            float: The classical gap.

            dict: The auxiliary configurations, keyed on the configurations in table.

    Raises:
        ImpossiblePenaltyModel: If the penalty model cannot be built. Normally due
            to a non-zero infeasible gap.

    """

    # Developer note: This function is input checking and output formatting. The logic is
    # in _generate_ising

    if not isinstance(graph, nx.Graph):
        raise TypeError("expected input graph to be a NetworkX Graph.")

    if not set().union(*table).issubset({-1, 1}):
        raise ValueError("expected table to be spin-valued")

    if not isinstance(decision, list):
        decision = list(decision)  # handle iterables
    if not all(v in graph for v in decision):
        raise ValueError("given graph does not match the variable labels in decision variables")

    num_var = len(decision)
    if any(len(config) != num_var for config in table):
        raise ValueError("number of decision variables does not match all of the entires in the table")

    if len(decision) > max_decision:
        raise ValueError(("The table is too large. Note that larger models can be built by setting "
                          "max_decision to a higher number, but generation could be extremely slow."))

    if len(graph) > max_variables:
        raise ValueError(("The graph is too large. Note that larger models can be built by setting "
                          "max_variables to a higher number, but generation could be extremely slow."))

    if linear_energy_ranges is None:
        linear_energy_ranges = defaultdict(lambda: (-2, 2))
    if quadratic_energy_ranges is None:
        quadratic_energy_ranges = defaultdict(lambda: (-1, 1))

    if not isinstance(table, Mapping):
        table = {config: 0. for config in table}

    h, J, offset, gap, aux = _generate_ising(graph, table, decision, min_classical_gap,
                                             linear_energy_ranges, quadratic_energy_ranges)

    bqm = dimod.BinaryQuadraticModel.empty(dimod.SPIN)
    bqm.add_variables_from((v, round(bias, precision)) for v, bias in h.items())
    bqm.add_interactions_from((u, v, round(bias, precision)) for (u, v), bias in J.items())
    bqm.add_offset(round(offset, precision))

    if return_auxiliary:
        return bqm, round(gap, precision), aux
    else:
        return bqm, round(gap, precision)

Response: Generates a binary quadratic model with specific ground states.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_penalty_model(specification):
    # check that the feasible_configurations are spin
    feasible_configurations = specification.feasible_configurations
    if specification.vartype is dimod.BINARY:
        feasible_configurations = {tuple(2 * v - 1 for v in config): en
                                   for config, en in iteritems(feasible_configurations)}

    # convert ising_quadratic_ranges to the form we expect
    ising_quadratic_ranges = specification.ising_quadratic_ranges
    quadratic_ranges = {(u, v): ising_quadratic_ranges[u][v] for u, v in specification.graph.edges}

    try:
        bqm, gap = generate_bqm(specification.graph, feasible_configurations,
                                specification.decision_variables,
                                linear_energy_ranges=specification.ising_linear_ranges,
                                quadratic_energy_ranges=quadratic_ranges,
                                min_classical_gap=specification.min_classical_gap)
    except ValueError:
        raise pm.exceptions.FactoryException("Specification is for too large of a model")

    return pm.PenaltyModel.from_specification(specification, bqm, gap, 0.0)

Response: Returns a penalty model with the given specification.


Instruction:
Write a Python 3 script for
checking correctness of ising_linear_ranges.

Response:
def _check_ising_linear_ranges(linear_ranges, graph):
        """check correctness/populate defaults for ising_linear_ranges."""
        if linear_ranges is None:
            linear_ranges = {}

        for v in graph:
            if v in linear_ranges:
                # check
                linear_ranges[v] = Specification._check_range(linear_ranges[v])
            else:
                # set default
                linear_ranges[v] = [-2, 2]

        return linear_ranges


Instruction:
Implement a function in Python 3 to
check correctness of ising_quadratic_ranges.

Response:
def _check_ising_quadratic_ranges(quad_ranges, graph):
        """check correctness/populate defaults for ising_quadratic_ranges."""
        if quad_ranges is None:
            quad_ranges = {}

        # first just populate the top level so we can rely on the structure
        for u in graph:
            if u not in quad_ranges:
                quad_ranges[u] = {}

        # next let's propgate and check what is already present
        for u, neighbors in iteritems(quad_ranges):
            for v, rang in iteritems(neighbors):
                # check the range
                rang = Specification._check_range(rang)

                if u in quad_ranges[v]:
                    # it's symmetric
                    if quad_ranges[u][v] != quad_ranges[v][u]:
                        raise ValueError("mismatched ranges for ising_quadratic_ranges")
                quad_ranges[v][u] = quad_ranges[u][v] = rang

        # finally fill in the missing stuff
        for u, v in graph.edges:
            if u not in quad_ranges[v]:
                quad_ranges[u][v] = quad_ranges[v][u] = [-1, 1]

        return quad_ranges


Instruction:
How would you implement a function in Python 3 that
checks that a range is in the format we expect min max and return

Response:
def _check_range(range_):
        """Check that a range is in the format we expect [min, max] and return"""
        try:
            if not isinstance(range_, list):
                range_ = list(range_)
            min_, max_ = range_
        except (ValueError, TypeError):
            raise TypeError("each range in ising_linear_ranges should be a list of length 2.")
        if not isinstance(min_, Number) or not isinstance(max_, Number) or min_ > max_:
            raise ValueError(("each range in ising_linear_ranges should be a 2-tuple "
                              "(min, max) where min <= max"))
        return range_


Instruction:
Write a Python 3 script to
relabel the variables and nodes according to the given mapping.

Response:
def relabel_variables(self, mapping, inplace=True):
        """Relabel the variables and nodes according to the given mapping.

        Args:
            mapping (dict): a dict mapping the current variable/node labels
                to new ones.
            inplace (bool, optional, default=True):
                If True, the specification is updated in-place; otherwise, a new specification
                is returned.

        Returns:
            :class:`.Specification`: A Specification with the variables
            relabeled according to mapping. If copy=False returns itself,
            if copy=True returns a new Specification.

        """
        graph = self.graph
        ising_linear_ranges = self.ising_linear_ranges
        ising_quadratic_ranges = self.ising_quadratic_ranges

        try:
            old_labels = set(iterkeys(mapping))
            new_labels = set(itervalues(mapping))
        except TypeError:
            raise ValueError("mapping targets must be hashable objects")

        for v in new_labels:
            if v in graph and v not in old_labels:
                raise ValueError(('A variable cannot be relabeled "{}" without also relabeling '
                                  "the existing variable of the same name").format(v))

        if not inplace:
            return Specification(nx.relabel_nodes(graph, mapping, copy=True),  # also checks the mapping
                                 tuple(mapping.get(v, v) for v in self.decision_variables),
                                 self.feasible_configurations,  # does not change
                                 vartype=self.vartype,  # does not change
                                 ising_linear_ranges={mapping.get(v, v): ising_linear_ranges[v] for v in graph},
                                 ising_quadratic_ranges={mapping.get(v, v): {mapping.get(u, u): r
                                                                             for u, r in iteritems(neighbors)}
                                                         for v, neighbors in iteritems(ising_quadratic_ranges)})
        else:
            # now we need the ising_linear_ranges and ising_quadratic_ranges
            shared = old_labels & new_labels

            if shared:
                # in this case we need to transform to an intermediate state
                # counter will be used to generate the intermediate labels, as an easy optimization
                # we start the counter with a high number because often variables are labeled by
                # integers starting from 0
                counter = itertools.count(2 * len(self))

                old_to_intermediate = {}
                intermediate_to_new = {}

                for old, new in iteritems(mapping):
                    if old == new:
                        # we can remove self-labels
                        continue

                    if old in new_labels or new in old_labels:

                        # try to get a new unique label
                        lbl = next(counter)
                        while lbl in new_labels or lbl in old_labels:
                            lbl = next(counter)

                        # add it to the mapping
                        old_to_intermediate[old] = lbl
                        intermediate_to_new[lbl] = new

                    else:
                        old_to_intermediate[old] = new
                        # don't need to add it to intermediate_to_new because it is a self-label

                Specification.relabel_variables(self, old_to_intermediate, inplace=True)
                Specification.relabel_variables(self, intermediate_to_new, inplace=True)
                return self

            # modifies graph in place
            nx.relabel_nodes(self.graph, mapping, copy=False)

            # this is always a new object
            self.decision_variables = tuple(mapping.get(v, v) for v in self.decision_variables)

            # we can just relabel in-place without worrying about conflict
            for v in old_labels:
                if v in mapping:
                    ising_linear_ranges[mapping[v]] = ising_linear_ranges[v]
                    del ising_linear_ranges[v]

            # need to do the deeper level first
            for neighbors in itervalues(ising_quadratic_ranges):
                for v in list(neighbors):
                    if v in mapping:
                        neighbors[mapping[v]] = neighbors[v]
                        del neighbors[v]

            # now the top level
            for v in old_labels:
                if v in mapping:
                    ising_quadratic_ranges[mapping[v]] = ising_quadratic_ranges[v]
                    del ising_quadratic_ranges[v]

            return self


Instruction:
How would you implement a function in Python 3 that
grabs values from a dictionary using an unordered tuple as a key.

Response:
def get_item(dictionary, tuple_key, default_value):
    """Grab values from a dictionary using an unordered tuple as a key.

    Dictionary should not contain None, 0, or False as dictionary values.

    Args:
        dictionary: Dictionary that uses two-element tuple as keys
        tuple_key: Unordered tuple of two elements
        default_value: Value that is returned when the tuple_key is not found in the dictionary
    """
    u, v = tuple_key

    # Grab tuple-values from dictionary
    tuple1 = dictionary.get((u, v), None)
    tuple2 = dictionary.get((v, u), None)

    # Return the first value that is not {None, 0, False}
    return tuple1 or tuple2 or default_value


Instruction:
Can you create a Python 3 function that
creates a linear programming matrix based on the spin states graph and scalars provided.

Response:
def _get_lp_matrix(spin_states, nodes, edges, offset_weight, gap_weight):
    """Creates an linear programming matrix based on the spin states, graph, and scalars provided.
    LP matrix:
        [spin_states, corresponding states of edges, offset_weight, gap_weight]

    Args:
        spin_states: Numpy array of spin states
        nodes: Iterable
        edges: Iterable of tuples
        offset_weight: Numpy 1-D array or number
        gap_weight: Numpy 1-D array or a number
    """
    if len(spin_states) == 0:
        return None

    # Set up an empty matrix
    n_states = len(spin_states)
    m_linear = len(nodes)
    m_quadratic = len(edges)
    matrix = np.empty((n_states, m_linear + m_quadratic + 2))   # +2 columns for offset and gap

    # Populate linear terms (i.e. spin states)
    if spin_states.ndim == 1:
        spin_states = np.expand_dims(spin_states, 1)
    matrix[:, :m_linear] = spin_states

    # Populate quadratic terms
    node_indices = dict(zip(nodes, range(m_linear)))
    for j, (u, v) in enumerate(edges):
        u_ind = node_indices[u]
        v_ind = node_indices[v]
        matrix[:, j + m_linear] = np.multiply(matrix[:, u_ind], matrix[:, v_ind])

    # Populate offset and gap columns, respectively
    matrix[:, -2] = offset_weight
    matrix[:, -1] = gap_weight
    return matrix


Instruction:
How would you implement a function in Python 3 that
generates a binary quadratic model for the given set of variables in the given graph.

Response:
def generate_bqm(graph, table, decision_variables,
                 linear_energy_ranges=None, quadratic_energy_ranges=None, min_classical_gap=2):
    """
    Args:
        graph: A networkx.Graph
        table: An iterable of valid spin configurations. Each configuration is a tuple of
            variable assignments ordered by `decision`.
        decision_variables: An ordered iterable of the variables in the binary quadratic model.
        linear_energy_ranges: Dictionary of the form {v: (min, max), ...} where min and
            max are the range of values allowed to v. The default range is [-2, 2].
        quadratic_energy_ranges: Dict of the form {(u, v): (min, max), ...} where min and max are
            the range of values allowed to (u, v). The default range is [-1, 1].
        min_classical_gap: A float. The minimum energy gap between the highest feasible state and
            the lowest infeasible state.
    """
    # Check for auxiliary variables in the graph
    if len(graph) != len(decision_variables):
        raise ValueError('Penaltymodel-lp does not handle problems with auxiliary variables')

    if not linear_energy_ranges:
        linear_energy_ranges = {}

    if not quadratic_energy_ranges:
        quadratic_energy_ranges = {}

    # Simplify graph naming
    # Note: nodes' and edges' order determine the column order of the LP
    nodes = decision_variables
    edges = graph.edges

    # Set variable names for lengths
    m_linear = len(nodes)                   # Number of linear biases
    m_quadratic = len(edges)                # Number of quadratic biases
    n_noted = len(table)                    # Number of spin combinations specified in the table
    n_unnoted = 2**m_linear - n_noted       # Number of spin combinations that were not specified

    # Linear programming matrix for spin states specified by 'table'
    noted_states = table.keys() if isinstance(table, dict) else table
    noted_states = list(noted_states)
    noted_matrix = _get_lp_matrix(np.asarray(noted_states), nodes, edges, 1, 0)

    # Linear programming matrix for spins states that were not specified by 'table'
    spin_states = product([-1, 1], repeat=m_linear) if m_linear > 1 else [-1, 1]
    unnoted_states = [state for state in spin_states if state not in noted_states]
    unnoted_matrix = _get_lp_matrix(np.asarray(unnoted_states), nodes, edges, 1, -1)
    if unnoted_matrix is not None:
        unnoted_matrix *= -1   # Taking negative in order to flip the inequality

    # Constraints
    if isinstance(table, dict):
        noted_bound = np.asarray([table[state] for state in noted_states])
        unnoted_bound = np.full((n_unnoted, 1), -1 * max(table.values()))  # -1 for flipped inequality
    else:
        noted_bound = np.zeros((n_noted, 1))
        unnoted_bound = np.zeros((n_unnoted, 1))

    # Bounds
    linear_range = (MIN_LINEAR_BIAS, MAX_LINEAR_BIAS)
    quadratic_range = (MIN_QUADRATIC_BIAS, MAX_QUADRATIC_BIAS)

    bounds = [linear_energy_ranges.get(node, linear_range) for node in nodes]
    bounds += [get_item(quadratic_energy_ranges, edge, quadratic_range) for edge in edges]

    # Note: Since ising has {-1, 1}, the largest possible gap is [-largest_bias, largest_bias],
    #   hence that 2 * sum(largest_biases)
    max_gap = 2 * sum(max(abs(lbound), abs(ubound)) for lbound, ubound in bounds)
    bounds.append((None, None))     # Bound for offset
    bounds.append((min_classical_gap, max_gap))     # Bound for gap.

    # Cost function
    cost_weights = np.zeros((1, m_linear + m_quadratic + 2))
    cost_weights[0, -1] = -1     # Only interested in maximizing the gap

    # Returns a Scipy OptimizeResult
    result = linprog(cost_weights.flatten(), A_eq=noted_matrix, b_eq=noted_bound,
                     A_ub=unnoted_matrix, b_ub=unnoted_bound, bounds=bounds)

    #TODO: propagate scipy.optimize.linprog's error message?
    if not result.success:
        raise ValueError('Penaltymodel-lp is unable to find a solution.')

    # Split result
    x = result.x
    h = x[:m_linear]
    j = x[m_linear:-2]
    offset = x[-2]
    gap = x[-1]

    if gap <= 0:
        raise ValueError('Penaltymodel-lp is unable to find a solution.')

    # Create BQM
    bqm = dimod.BinaryQuadraticModel.empty(dimod.SPIN)
    bqm.add_variables_from((v, bias) for v, bias in zip(nodes, h))
    bqm.add_interactions_from((u, v, bias) for (u, v), bias in zip(edges, j))
    bqm.add_offset(offset)

    return bqm, gap


Instruction:
Explain what the following Python 3 code does
def generate(graph, feasible_configurations, decision_variables,
             linear_energy_ranges, quadratic_energy_ranges, min_classical_gap,
             smt_solver_name=None):
    """Generates the Ising model that induces the given feasible configurations. The code is based
    on the papers [#do]_ and [#mc]_.

    Args:
        graph (nx.Graph): The target graph on which the Ising model is to be built.
        feasible_configurations (dict): The set of feasible configurations
            of the decision variables. The key is a feasible configuration
            as a tuple of spins, the values are the associated energy.
        decision_variables (list/tuple): Which variables in the graph are
            assigned as decision variables.
        linear_energy_ranges (dict, optional): A dict of the form
            {v: (min, max), ...} where min and max are the range
            of values allowed to v.
        quadratic_energy_ranges (dict): A dict of the form
            {(u, v): (min, max), ...} where min and max are the range
            of values allowed to (u, v).
        min_classical_gap (float): The minimum energy gap between the highest feasible state and the
            lowest infeasible state.
        smt_solver_name (str/None): The name of the smt solver. Must
            be a solver available to pysmt. If None, uses the pysmt default.

    Returns:
        tuple: A 4-tuple containing:

            dict: The linear biases of the Ising problem.

            dict: The quadratic biases of the Ising problem.

            :obj:`dimod.BinaryQuadraticModel`

            float: The classical energy gap between ground and the first
            excited state.

    Raises:
        ImpossiblePenaltyModel: If the penalty model cannot be built. Normally due
            to a non-zero infeasible gap.

    .. [#do] Bian et al., "Discrete optimization using quantum annealing on sparse Ising models",
        https://www.frontiersin.org/articles/10.3389/fphy.2014.00056/full

    .. [#mc] Z. Bian, F. Chudak, R. Israel, B. Lackey, W. G. Macready, and A. Roy
        "Mapping constrained optimization problems to quantum annealing with application to fault diagnosis"
        https://arxiv.org/pdf/1603.03111.pdf

    """
    if len(graph) == 0:
        return dimod.BinaryQuadraticModel.empty(dimod.SPIN), float('inf')

    # we need to build a Table. The table encodes all of the information used by the smt solver
    table = Table(graph, decision_variables, linear_energy_ranges, quadratic_energy_ranges)

    # iterate over every possible configuration of the decision variables.
    for config in itertools.product((-1, 1), repeat=len(decision_variables)):

        # determine the spin associated with each variable in decision variables.
        spins = dict(zip(decision_variables, config))

        if config in feasible_configurations:
            # if the configuration is feasible, we require that the minimum energy over all
            # possible aux variable settings be exactly its target energy (given by the value)
            table.set_energy(spins, feasible_configurations[config])
        else:
            # if the configuration is infeasible, we simply want its minimum energy over all
            # possible aux variable settings to be an upper bound on the classical gap.
            if isinstance(feasible_configurations, dict) and feasible_configurations:
                highest_feasible_energy = max(feasible_configurations.values())
            else:
                highest_feasible_energy = 0

            table.set_energy_upperbound(spins, highest_feasible_energy)

    # now we just need to get a solver
    with Solver(smt_solver_name) as solver:

        # add all of the assertions from the table to the solver
        for assertion in table.assertions:
            solver.add_assertion(assertion)

        # add min classical gap assertion
        gap_assertion = table.gap_bound_assertion(min_classical_gap)
        solver.add_assertion(gap_assertion)

        # check if the model is feasible at all.
        if solver.solve():
            # since we know the current model is feasible, grab the initial model.
            model = solver.get_model()

            # we want to increase the gap until we have found the max classical gap
            # note: gmax is the maximum possible gap for a particular set of variables. To find it,
            #   we take the sum of the largest coefficients possible and double it. We double it
            #   because in Ising, the largest gap possible from the largest coefficient is the
            #   negative of said coefficient. Example: consider a graph with one node A, with a
            #   energy range of [-2, 1]. The largest energy gap between spins +1 and -1 is 4;
            #   namely, the largest absolute coefficient -2 with the ising spins results to
            #   gap = (-2)(-1) - (-2)(1) = 4.
            gmin = min_classical_gap
            gmax = sum(max(abs(r) for r in linear_energy_ranges[v]) for v in graph)
            gmax += sum(max(abs(r) for r in quadratic_energy_ranges[(u, v)])
                        for (u, v) in graph.edges)
            gmax *= 2

            # 2 is a good target gap
            g = max(2., gmin)

            while abs(gmax - gmin) >= MAX_GAP_DELTA:
                solver.push()

                gap_assertion = table.gap_bound_assertion(g)
                solver.add_assertion(gap_assertion)

                if solver.solve():
                    model = solver.get_model()
                    gmin = float(model.get_py_value(table.gap))

                else:
                    solver.pop()
                    gmax = g

                g = min(gmin + .1, (gmax + gmin) / 2)

        else:
            raise ImpossiblePenaltyModel("Model cannot be built")

    # finally we need to convert our values back into python floats.

    classical_gap = float(model.get_py_value(table.gap))

    # if the problem is fully specified (or empty) it has infinite gap
    if (len(decision_variables) == len(graph) and
            decision_variables and  # at least one variable
            len(feasible_configurations) == 2**len(decision_variables)):
        classical_gap = float('inf')

    return table.theta.to_bqm(model), classical_gap

Response: Generates the Ising model that induces the given feasible configurations.


Instruction:
Can you write a function in Python 3 where it
creates an pysmt Real constant from a number x and the denominator limited.

Response:
def limitReal(x, max_denominator=1000000):
    """Creates an pysmt Real constant from x.

    Args:
        x (number): A number to be cast to a pysmt constant.
        max_denominator (int, optional): The maximum size of the denominator.
            Default 1000000.

    Returns:
        A Real constant with the given value and the denominator limited.

    """
    f = Fraction(x).limit_denominator(max_denominator)
    return Real((f.numerator, f.denominator))


Instruction:
Create a Python 3 function for
creating Theta from a networkx. Graph object and a set of energy ranges.

Response:
def from_graph(cls, graph, linear_energy_ranges, quadratic_energy_ranges):
        """Create Theta from a graph and energy ranges.

        Args:
            graph (:obj:`networkx.Graph`):
                Provides the structure for Theta.

            linear_energy_ranges (dict):
                A dict of the form {v: (min, max), ...} where min and max are the
                range of values allowed to v.
            quadratic_energy_ranges (dict):
                A dict of the form {(u, v): (min, max), ...} where min and max
                are the range of values allowed to (u, v).

        Returns:
            :obj:`.Theta`

        """
        get_env().enable_infix_notation = True  # not sure why we need this here

        theta = cls.empty(dimod.SPIN)

        theta.add_offset(Symbol('offset', REAL))

        def Linear(v):
            """Create a Symbol for the linear bias including the energy range
            constraints."""
            bias = Symbol('h_{}'.format(v), REAL)

            min_, max_ = linear_energy_ranges[v]

            theta.assertions.add(LE(bias, limitReal(max_)))
            theta.assertions.add(GE(bias, limitReal(min_)))

            return bias

        def Quadratic(u, v):
            """Create a Symbol for the quadratic bias including the energy range
            constraints."""
            bias = Symbol('J_{},{}'.format(u, v), REAL)

            if (v, u) in quadratic_energy_ranges:
                min_, max_ = quadratic_energy_ranges[(v, u)]
            else:
                min_, max_ = quadratic_energy_ranges[(u, v)]

            theta.assertions.add(LE(bias, limitReal(max_)))
            theta.assertions.add(GE(bias, limitReal(min_)))

            return bias

        for v in graph.nodes:
            theta.add_variable(v, Linear(v))

        for u, v in graph.edges:
            theta.add_interaction(u, v, Quadratic(u, v))

        return theta


Instruction:
Can you tell what is the following Python 3 function doing
def to_bqm(self, model):
        linear = ((v, float(model.get_py_value(bias)))
                  for v, bias in self.linear.items())
        quadratic = ((u, v, float(model.get_py_value(bias)))
                     for (u, v), bias in self.quadratic.items())
        offset = float(model.get_py_value(self.offset))

        return dimod.BinaryQuadraticModel(linear, quadratic, offset, dimod.SPIN)

Response: Given a pysmt model return a bqm.


Instruction:
Here you have a function in Python 3, explain what it does
def SpinTimes(spin, bias):
    if not isinstance(spin, int):
        raise TypeError('spin must be an int')
    if spin == -1:
        return Times(Real((-1, 1)), bias)  # -1 / 1
    elif spin == 1:
        # identity
        return bias
    else:
        raise ValueError('expected spins to be -1., or 1.')

Response: Define our own multiplication for bias times spins.


Instruction:
Given the following Python 3 function, write the documentation
def energy(self, spins, break_aux_symmetry=True):
        subtheta = self.theta.copy()
        subtheta.fix_variables(spins)

        # we need aux variables
        av = next(self._auxvar_counter)
        auxvars = {v: Symbol('aux{}_{}'.format(av, v), BOOL) for v in subtheta.linear}
        if break_aux_symmetry and av == 0:
            # without loss of generality, we can assume that the aux variables are all
            # spin-up for one configuration
            self.assertions.update(set(auxvars.values()))

        trees = self._trees

        if not trees:
            # if there are no variables to eliminate, then the offset of
            # subtheta is the exact value and we can just return it
            assert not subtheta.linear and not subtheta.quadratic
            return subtheta.offset

        energy = Plus(self.message(trees, {}, subtheta, auxvars), subtheta.offset)

        return energy

Response: A formula for the exact energy of Theta with spins fixed.


Instruction:
Write a Python 3 script for
determining the energy of the elimination tree. Args: tree (dict): The current elimination tree spins (dict): The current fixed spins subtheta (dict): Theta with spins fixed. auxvars (dict): The auxiliary variables for the given spins. Returns: The formula for the energy of the tree.

Response:
def message(self, tree, spins, subtheta, auxvars):
        """Determine the energy of the elimination tree.

        Args:
            tree (dict): The current elimination tree
            spins (dict): The current fixed spins
            subtheta (dict): Theta with spins fixed.
            auxvars (dict): The auxiliary variables for the given spins.

        Returns:
            The formula for the energy of the tree.

        """
        energy_sources = set()
        for v, children in tree.items():
            aux = auxvars[v]

            assert all(u in spins for u in self._ancestors[v])

            # build an iterable over all of the energies contributions
            # that we can exactly determine given v and our known spins
            # in these contributions we assume that v is positive
            def energy_contributions():
                yield subtheta.linear[v]

                for u, bias in subtheta.adj[v].items():
                    if u in spins:
                        yield SpinTimes(spins[u], bias)

            plus_energy = Plus(energy_contributions())
            minus_energy = SpinTimes(-1, plus_energy)

            # if the variable has children, we need to recursively determine their energies
            if children:
                # set v to be positive
                spins[v] = 1
                plus_energy = Plus(plus_energy, self.message(children, spins, subtheta, auxvars))
                spins[v] = -1
                minus_energy = Plus(minus_energy, self.message(children, spins, subtheta, auxvars))
                del spins[v]

            # we now need a real-valued smt variable to be our message
            m = FreshSymbol(REAL)

            ancestor_aux = {auxvars[u] if spins[u] > 0 else Not(auxvars[u])
                            for u in self._ancestors[v]}
            plus_aux = And({aux}.union(ancestor_aux))
            minus_aux = And({Not(aux)}.union(ancestor_aux))

            self.assertions.update({LE(m, plus_energy),
                                    LE(m, minus_energy),
                                    Implies(plus_aux, GE(m, plus_energy)),
                                    Implies(minus_aux, GE(m, minus_energy))
                                    })

            energy_sources.add(m)

        return Plus(energy_sources)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def message_upperbound(self, tree, spins, subtheta):
        energy_sources = set()
        for v, subtree in tree.items():

            assert all(u in spins for u in self._ancestors[v])

            # build an iterable over all of the energies contributions
            # that we can exactly determine given v and our known spins
            # in these contributions we assume that v is positive
            def energy_contributions():
                yield subtheta.linear[v]

                for u, bias in subtheta.adj[v].items():
                    if u in spins:
                        yield Times(limitReal(spins[u]), bias)

            energy = Plus(energy_contributions())

            # if there are no more variables in the order, we can stop
            # otherwise we need the next message variable
            if subtree:
                spins[v] = 1.
                plus = self.message_upperbound(subtree, spins, subtheta)
                spins[v] = -1.
                minus = self.message_upperbound(subtree, spins, subtheta)
                del spins[v]
            else:
                plus = minus = limitReal(0.0)

            # we now need a real-valued smt variable to be our message
            m = FreshSymbol(REAL)

            self.assertions.update({LE(m, Plus(energy, plus)),
                                    LE(m, Plus(Times(energy, limitReal(-1.)), minus))})

            energy_sources.add(m)

        return Plus(energy_sources)

Response: Determine an upper bound on the energy of the current elimination tree and the current fixed spins and subtheta.


Instruction:
Write a Python 3 script to
set the energy of Theta with spins fixed to target_energy.

Response:
def set_energy(self, spins, target_energy):
        """Set the energy of Theta with spins fixed to target_energy.

        Args:
            spins (dict): Spin values for a subset of the variables in Theta.
            target_energy (float): The desired energy for Theta with spins fixed.

        Notes:
            Add equality constraint to assertions.

        """
        spin_energy = self.energy(spins)
        self.assertions.add(Equals(spin_energy, limitReal(target_energy)))


Instruction:
How would you implement a function in Python 3 that
sets the energy of the Theta with spins fixed to be greater than gap + offset.

Response:
def set_energy_upperbound(self, spins, offset=0):
        """Upper bound the energy of Theta with spins fixed to be greater than (gap + offset).

        Args:
            spins (dict): Spin values for a subset of the variables in Theta.
            offset (float): A value that is added to the upper bound. Default value is 0.

        Notes:
            Add equality constraint to assertions.

        """
        spin_energy = self.energy_upperbound(spins)
        self.assertions.add(GE(spin_energy, self.gap + offset))


Instruction:
Write a Python 3 script for
looping until a change is received from the server

Response:
def _poll_loop(self):
        """At self.poll_period poll for changes"""
        next_poll = time.time()
        while True:
            next_poll += self._poll_period
            timeout = next_poll - time.time()
            if timeout < 0:
                timeout = 0
            try:
                return self._stop_queue.get(timeout=timeout)
            except TimeoutError:
                # No stop, no problem
                pass
            try:
                self.handle_changes(self.client.get_changes())
            except Exception:
                # TODO: should fault here?
                self.log.exception("Error while getting changes")


Instruction:
Create a Python 3 function to
take a camelCaseFieldName and returns an Title Case Field Name

Response:
def camel_to_title(name):
    """Takes a camelCaseFieldName and returns an Title Case Field Name

    Args:
        name (str): E.g. camelCaseFieldName

    Returns:
        str: Title Case converted name. E.g. Camel Case Field Name
    """
    split = re.findall(r"[A-Z]?[a-z0-9]+|[A-Z]+(?=[A-Z]|$)", name)
    ret = " ".join(split)
    ret = ret[0].upper() + ret[1:]
    return ret


Instruction:
Can you implement a function in Python 3 that
takes a snake_field_name and returns a camelCaseFieldName

Response:
def snake_to_camel(name):
    """Takes a snake_field_name and returns a camelCaseFieldName

    Args:
        name (str): E.g. snake_field_name or SNAKE_FIELD_NAME

    Returns:
        str: camelCase converted name. E.g. capsFieldName
    """
    ret = "".join(x.title() for x in name.split("_"))
    ret = ret[0].lower() + ret[1:]
    return ret


Instruction:
Can you implement a function in Python 3 that
creates a dictionary representation of object attributes

Response:
def to_dict(self):
        # type: () -> OrderedDict
        """Create a dictionary representation of object attributes

        Returns:
            OrderedDict serialised version of self
        """

        d = OrderedDict()
        if self.typeid:
            d["typeid"] = self.typeid

        for k in self.call_types:
            # check_camel_case(k)
            d[k] = serialize_object(getattr(self, k))

        return d


Instruction:
Can you write a function in Python 3 where it
creates an instance of cls from a serialized version of cls. d is a dict of endpoints of cls to set

Response:
def from_dict(cls, d, ignore=()):
        """Create an instance from a serialized version of cls

        Args:
            d(dict): Endpoints of cls to set
            ignore(tuple): Keys to ignore

        Returns:
            Instance of this class
        """
        filtered = {}
        for k, v in d.items():
            if k == "typeid":
                assert v == cls.typeid, \
                    "Dict has typeid %s but %s has typeid %s" % \
                    (v, cls, cls.typeid)
            elif k not in ignore:
                filtered[k] = v
        try:
            inst = cls(**filtered)
        except TypeError as e:
            raise TypeError("%s raised error: %s" % (cls.typeid, str(e)))
        return inst


Instruction:
Can you generate a brief explanation for the following Python 3 code
def register_subclass(cls, typeid):
        def decorator(subclass):
            cls._subcls_lookup[typeid] = subclass
            subclass.typeid = typeid
            return subclass
        return decorator

Response: Register a subclass so from_dict works


Instruction:
Implement a Python 3 function for
looking up a class based on a serialized dictionary containing a typeid

Response:
def lookup_subclass(cls, d):
        """Look up a class based on a serialized dictionary containing a typeid

        Args:
            d (dict): Dictionary with key "typeid"

        Returns:
            Serializable subclass
        """
        try:
            typeid = d["typeid"]
        except KeyError:
            raise FieldError("typeid not present in keys %s" % list(d))

        subclass = cls._subcls_lookup.get(typeid, None)
        if not subclass:
            raise FieldError("'%s' not a valid typeid" % typeid)
        else:
            return subclass


Instruction:
Write a Python 3 script to
start the process going

Response:
def start(self, timeout=None):
        """Start the process going

        Args:
            timeout (float): Maximum amount of time to wait for each spawned
                process. None means forever
        """
        assert self.state == STOPPED, "Process already started"
        self.state = STARTING
        should_publish = self._start_controllers(
            self._controllers.values(), timeout)
        if should_publish:
            self._publish_controllers(timeout)
        self.state = STARTED


Instruction:
Create a Python 3 function to
stop the process and wait for it to finish

Response:
def stop(self, timeout=None):
        """Stop the process and wait for it to finish

        Args:
            timeout (float): Maximum amount of time to wait for each spawned
                object. None means forever
        """
        assert self.state == STARTED, "Process not started"
        self.state = STOPPING
        # Allow every controller a chance to clean up
        self._run_hook(ProcessStopHook, timeout=timeout)
        for s in self._spawned:
            if not s.ready():
                self.log.debug(
                    "Waiting for %s *%s **%s", s._function, s._args, s._kwargs)
            s.wait(timeout=timeout)
        self._spawned = []
        self._controllers = OrderedDict()
        self._unpublished = set()
        self.state = STOPPED
        self.log.debug("Done process.stop()")


Instruction:
How would you code a function in Python 3 to
run the function in a worker thread returning a Spawned object.

Response:
def spawn(self, function, *args, **kwargs):
        # type: (Callable[..., Any], *Any, **Any) -> Spawned
        """Runs the function in a worker thread, returning a Result object

        Args:
            function: Function to run
            args: Positional arguments to run the function with
            kwargs: Keyword arguments to run the function with

        Returns:
            Spawned: Something you can call wait(timeout) on to see when it's
                finished executing
        """
        assert self.state != STOPPED, "Can't spawn when process stopped"
        spawned = Spawned(function, args, kwargs)
        self._spawned.append(spawned)
        self._spawn_count += 1
        # Filter out things that are ready to avoid memory leaks
        if self._spawn_count > SPAWN_CLEAR_COUNT:
            self._clear_spawn_list()
        return spawned


Instruction:
Write a Python 3 function for
adding a controller to be hosted by this process.

Response:
def add_controller(self, controller, timeout=None):
        # type: (Controller, float) -> None
        """Add a controller to be hosted by this process

        Args:
            controller (Controller): Its controller
            timeout (float): Maximum amount of time to wait for each spawned
                object. None means forever
        """
        assert controller.mri not in self._controllers, \
            "Controller already exists for %s" % controller.mri
        self._controllers[controller.mri] = controller
        controller.setup(self)
        if self.state:
            should_publish = self._start_controllers([controller], timeout)
            if self.state == STARTED and should_publish:
                self._publish_controllers(timeout)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def block_view(self, mri):
        # type: (str) -> Block
        """Get a Block view from a Controller with given mri"""
        controller = self.get_controller(mri)
        block = controller.block_view()
        return block

Response: Get a Block view from a Controller with given mri


Instruction:
How would you code a function in Python 3 to
update the label of the Block Meta object with the title of the given TitleInfo.

Response:
def update_title(self, _, info):
        # type: (object, TitleInfo) -> None
        """Set the label of the Block Meta object"""
        with self._lock:
            self._block.meta.set_label(info.title)


Instruction:
Can you write a function in Python 3 where it
updates the health attribute. Called from part.

Response:
def update_health(self, reporter, info):
        # type: (object, HealthInfo) -> None
        """Set the health attribute. Called from part"""
        with self.changes_squashed:
            alarm = info.alarm
            if alarm.is_ok():
                self._faults.pop(reporter, None)
            else:
                self._faults[reporter] = alarm
            if self._faults:
                # Sort them by severity
                faults = sorted(self._faults.values(),
                                key=lambda a: a.severity.value)
                alarm = faults[-1]
                text = faults[-1].message
            else:
                alarm = None
                text = "OK"
            self.health.set_value(text, alarm=alarm)


Instruction:
Can you write a function in Python 3 where it
creates the relevant parts for the current object.

Response:
def make_parts_for(self, field_name, field_data):
        """Create the relevant parts for this field

        Args:
            field_name (str): Short field name, e.g. VAL
            field_data (FieldData): Field data object
        """
        typ = field_data.field_type
        subtyp = field_data.field_subtype

        if typ in ("read", "xadc"):
            writeable = False
        else:
            writeable = True

        if typ == "time" or typ in ("param", "read") and subtyp == "time":
            self._make_time_parts(field_name, field_data, writeable)
        elif typ == "write" and subtyp == "action":
            self._make_action_part(field_name, field_data)
        elif typ in ("param", "read", "write", "xadc"):
            self._make_param_part(field_name, field_data, writeable)
        elif typ == "bit_out":
            self._make_out(field_name, field_data, "bit")
        elif typ == "pos_out":
            self._make_out(field_name, field_data, "pos")
            self._make_scale_offset(field_name)
            self._make_out_capture(field_name, field_data)
        elif typ == "ext_out":
            self._make_out_capture(field_name, field_data)
        elif typ == "bit_mux":
            self._make_mux(field_name, field_data, "bit")
            self._make_mux_delay(field_name)
        elif typ == "pos_mux":
            self._make_mux(field_name, field_data, "pos")
        elif typ == "table":
            self._make_table(field_name, field_data)
        else:
            raise ValueError("Unknown type %r subtype %r" % (typ, subtyp))


Instruction:
Create a Python 3 function to
get a view of a block in the controller with the given mri

Response:
def block_view(self, mri):
        # type: (str) -> Block
        """Get a view of a block

        Args:
            mri: The mri of the controller hosting the block

        Returns:
            Block: The block we control
        """
        controller = self.get_controller(mri)
        block = controller.block_view(weakref.proxy(self))
        return block


Instruction:
Create a Python 3 function for
setting function to call just before requests are dispatched

Response:
def set_notify_dispatch_request(self, notify_dispatch_request, *args):
        """Set function to call just before requests are dispatched

        Args:
            notify_dispatch_request (callable): function will be called
                with request as single arg just before request is dispatched
        """
        self._notify_dispatch_request = notify_dispatch_request
        self._notify_args = args


Instruction:
How would you explain what the following Python 3 function does
def ignore_stops_before_now(self):
        self._sentinel_stop = object()
        self._q.put(self._sentinel_stop)

Response: Ignore any stops received before this point


Instruction:
Explain what the following Python 3 code does
def put(self, path, value, timeout=None, event_timeout=None):
        future = self.put_async(path, value)
        self.wait_all_futures(
            future, timeout=timeout, event_timeout=event_timeout)
        return future.result()

Response: Puts a value to a path and returns when it completes


Instruction:
Make a summary of the following Python 3 code
def put_async(self, path, value):
        request = Put(self._get_next_id(), path, value)
        request.set_callback(self._q.put)
        future = self._dispatch_request(request)
        return future

Response: Puts a value to a path and returns immediately


Instruction:
Here you have a function in Python 3, explain what it does
def post_async(self, path, params=None):
        request = Post(self._get_next_id(), path, params)
        request.set_callback(self._q.put)
        future = self._dispatch_request(request)
        return future

Response:
Asynchronously calls a function on a child block
            and returns a Future that resolves to the result
           .


Instruction:
Given the following Python 3 function, write the documentation
def subscribe(self, path, callback, *args):
        request = Subscribe(self._get_next_id(), path, delta=False)
        request.set_callback(self._q.put)
        # If self is in args, then make weak version of it
        saved_args = []
        for arg in args:
            if arg is self:
                saved_args.append(weakref.proxy(self))
            else:
                saved_args.append(arg)
        self._subscriptions[request.id] = (callback, saved_args)
        future = self._dispatch_request(request)
        return future

Response: Subscribe to changes in a given attribute and call callback when it changes


Instruction:
Here you have a function in Python 3, explain what it does
def unsubscribe(self, future):
        assert future not in self._pending_unsubscribes, \
            "%r has already been unsubscribed from" % \
            self._pending_unsubscribes[future]
        subscribe = self._requests[future]
        self._pending_unsubscribes[future] = subscribe
        # Clear out the subscription
        self._subscriptions.pop(subscribe.id)
        request = Unsubscribe(subscribe.id)
        request.set_callback(self._q.put)
        try:
            controller = self.get_controller(subscribe.path[0])
        except ValueError:
            # Controller has already gone, probably during tearDown
            pass
        else:
            self.handle_request(controller, request)

Response: Terminates the subscription given by a future.


Instruction:
How would you implement a function in Python 3 that
sends an unsubscribe for all active subscriptions

Response:
def unsubscribe_all(self, callback=False):
        """Send an unsubscribe for all active subscriptions"""
        futures = ((f, r) for f, r in self._requests.items()
                   if isinstance(r, Subscribe)
                   and f not in self._pending_unsubscribes)
        if futures:
            for future, request in futures:
                if callback:
                    log.warn("Unsubscribing from %s", request.path)
                    cothread.Callback(self.unsubscribe, future)
                else:
                    self.unsubscribe(future)


Instruction:
Explain what the following Python 3 code does
def when_matches(self, path, good_value, bad_values=None, timeout=None,
                     event_timeout=None):
        """Resolve when an path value equals value

        Args:
            path (list): The path to wait to
            good_value (object): the value to wait for
            bad_values (list): values to raise an error on
            timeout (float): time in seconds to wait for responses, wait
                forever if None
            event_timeout: maximum time in seconds to wait between each response
                event, wait forever if None
        """
        future = self.when_matches_async(path, good_value, bad_values)
        self.wait_all_futures(
            future, timeout=timeout, event_timeout=event_timeout)

Response: Resolve when an path value equals value


Instruction:
Can you generate the documentation for the following Python 3 function
def when_matches_async(self, path, good_value, bad_values=None):
        when = When(good_value, bad_values)
        future = self.subscribe(path, when)
        when.set_future_context(future, weakref.proxy(self))
        return future

Response: Wait for an attribute to become a given value


Instruction:
Given the following Python 3 function, write the documentation
def wait_all_futures(self, futures, timeout=None, event_timeout=None):
        # type: (Union[List[Future], Future, None], float, float) -> None
        """Services all futures until the list 'futures' are all done
        then returns. Calls relevant subscription callbacks as they
        come off the queue and raises an exception on abort

        Args:
            futures: a `Future` or list of all futures that the caller
                wants to wait for
            timeout: maximum total time in seconds to wait for responses, wait
                forever if None
            event_timeout: maximum time in seconds to wait between each response
                event, wait forever if None
        """
        if timeout is None:
            end = None
        else:
            end = time.time() + timeout

        if not isinstance(futures, list):
            if futures:
                futures = [futures]
            else:
                futures = []

        filtered_futures = []

        for f in futures:
            if f.done():
                if f.exception() is not None:
                    raise f.exception()
            else:
                filtered_futures.append(f)

        while filtered_futures:
            if event_timeout is not None:
                until = time.time() + event_timeout
                if end is not None:
                    until = min(until, end)
            else:
                until = end
            self._service_futures(filtered_futures, until)

Response: Wait for all futures to complete and return the result of the service.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def sleep(self, seconds):
        until = time.time() + seconds
        try:
            while True:
                self._service_futures([], until)
        except TimeoutError:
            return

Response: Services all futures until seconds have passed


Instruction:
Explain what the following Python 3 code does
def _service_futures(self, futures, until=None):
        if until is None:
            timeout = None
        else:
            timeout = until - time.time()
            if timeout < 0:
                timeout = 0
        try:
            response = self._q.get(timeout)
        except TimeoutError:
            raise TimeoutError(
                "Timeout waiting for %s" % self._describe_futures(futures))
        if response is self._sentinel_stop:
            self._sentinel_stop = None
        elif response is self.STOP:
            if self._sentinel_stop is None:
                # This is a stop we should listen to...
                raise AbortedError(
                    "Aborted waiting for %s" % self._describe_futures(futures))
        elif isinstance(response, Update):
            # This is an update for a subscription
            if response.id in self._subscriptions:
                func, args = self._subscriptions[response.id]
                func(response.value, *args)
        elif isinstance(response, Return):
            future = self._futures.pop(response.id)
            del self._requests[future]
            self._pending_unsubscribes.pop(future, None)
            result = response.value
            future.set_result(result)
            try:
                futures.remove(future)
            except ValueError:
                pass
        elif isinstance(response, Error):
            future = self._futures.pop(response.id)
            del self._requests[future]
            future.set_exception(response.message)
            try:
                futures.remove(future)
            except ValueError:
                pass
            else:
                raise response.message

Response: This method is used to service the futures in the cluster.


Instruction:
Can you implement a function in Python 3 that
returns the result or raise the error the function has produced

Response:
def get(self, timeout=None):
        # type: (float) -> T
        """Return the result or raise the error the function has produced"""
        self.wait(timeout)
        if isinstance(self._result, Exception):
            raise self._result
        return self._result


Instruction:
Can you write a function in Python 3 where it
extracts the version number from the version. py file.

Response:
def get_version():
    """Extracts the version number from the version.py file.
    """
    VERSION_FILE = os.path.join(module_name, 'version.py')
    txt = open(VERSION_FILE).read()
    mo = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', txt, re.M)
    if mo:
        version = mo.group(1)
        bs_version = os.environ.get('MODULEVER', '0.0')
        assert bs_version == "0.0" or bs_version == version, \
            "Version {} specified by the build system doesn't match {} in " \
            "version.py".format(bs_version, version)
        return version
    else:
        raise RuntimeError('Unable to find version string in {0}.'
                           .format(VERSION_FILE))


Instruction:
Can you create a Python 3 function that
updates the dict of parameters that are needed to configure the controller.

Response:
def update_configure_params(self, part=None, info=None):
        # type: (Part, ConfigureParamsInfo) -> None
        """Tell controller part needs different things passed to Configure"""
        with self.changes_squashed:
            # Update the dict
            if part:
                self.part_configure_params[part] = info

            # No process yet, so don't do this yet
            if self.process is None:
                return

            # Get the model of our configure method as the starting point
            configure_model = MethodModel.from_callable(self.configure)

            # These will not be inserted as the already exist
            ignored = tuple(ConfigureHook.call_types)

            # Re-calculate the following
            required = []
            takes_elements = OrderedDict()
            defaults = OrderedDict()

            # First do the required arguments
            for k in configure_model.takes.required:
                required.append(k)
                takes_elements[k] = configure_model.takes.elements[k]
            for part in self.parts.values():
                try:
                    info = self.part_configure_params[part]
                except KeyError:
                    continue
                for k in info.required:
                    if k not in required and k not in ignored:
                        required.append(k)
                        takes_elements[k] = info.metas[k]

            # Now the default and optional
            for k in configure_model.takes.elements:
                if k not in required:
                    takes_elements[k] = configure_model.takes.elements[k]
            for part in self.parts.values():
                try:
                    info = self.part_configure_params[part]
                except KeyError:
                    continue
                for k in info.metas:
                    if k not in required and k not in ignored:
                        takes_elements[k] = info.metas[k]
                        if k in info.defaults:
                            defaults[k] = info.defaults[k]

            # Set the values
            configure_model.takes.set_elements(takes_elements)
            configure_model.takes.set_required(required)
            configure_model.set_defaults(defaults)

            # Update methods from the new metas
            self._block.configure.set_takes(configure_model.takes)
            self._block.configure.set_defaults(configure_model.defaults)

            # Now make a validate model with returns
            validate_model = MethodModel.from_dict(configure_model.to_dict())
            returns = MapMeta.from_dict(validate_model.takes.to_dict())
            for v in returns.elements.values():
                v.set_writeable(False)
            self._block.validate.set_takes(validate_model.takes)
            self._block.validate.set_defaults(validate_model.defaults)
            self._block.validate.set_returns(returns)


Instruction:
How would you explain what the following Python 3 function does
def validate(self, generator, axesToMove=None, **kwargs):
        # type: (AGenerator, AAxesToMove, **Any) -> AConfigureParams
        """Validate configuration parameters and return validated parameters.

        Doesn't take device state into account so can be run in any state
        """
        iterations = 10
        # We will return this, so make sure we fill in defaults
        for k, default in self._block.configure.defaults.items():
            if k not in kwargs:
                kwargs[k] = default
        # The validated parameters we will eventually return
        params = ConfigureParams(generator, axesToMove, **kwargs)
        # Make some tasks just for validate
        part_contexts = self.create_part_contexts()
        # Get any status from all parts
        status_part_info = self.run_hooks(
            ReportStatusHook(p, c) for p, c in part_contexts.items())
        while iterations > 0:
            # Try up to 10 times to get a valid set of parameters
            iterations -= 1
            # Validate the params with all the parts
            validate_part_info = self.run_hooks(
                ValidateHook(p, c, status_part_info, **kwargs)
                for p, c, kwargs in self._part_params(part_contexts, params))
            tweaks = ParameterTweakInfo.filter_values(validate_part_info)
            if tweaks:
                for tweak in tweaks:
                    deserialized = self._block.configure.takes.elements[
                        tweak.parameter].validate(tweak.value)
                    setattr(params, tweak.parameter, deserialized)
                    self.log.debug(
                        "Tweaking %s to %s", tweak.parameter, deserialized)
            else:
                # Consistent set, just return the params
                return params
        raise ValueError("Could not get a consistent set of parameters")

Response: Validate the configuration parameters and return validated parameters.


Instruction:
How would you explain what the following Python 3 function does
def configure(self, generator, axesToMove=None, **kwargs):
        # type: (AGenerator, AAxesToMove, **Any) -> None
        """Validate the params then configure the device ready for run().

        Try to prepare the device as much as possible so that run() is quick to
        start, this may involve potentially long running activities like moving
        motors.

        Normally it will return in Armed state. If the user aborts then it will
        return in Aborted state. If something goes wrong it will return in Fault
        state. If the user disables then it will return in Disabled state.
        """
        params = self.validate(generator, axesToMove, **kwargs)
        try:
            self.transition(ss.CONFIGURING)
            self.do_configure(params)
            self.abortable_transition(ss.ARMED)
        except AbortedError:
            self.abort_queue.put(None)
            raise
        except Exception as e:
            self.go_to_error_state(e)
            raise

Response: Configure the current state of the current state of the current state.


Instruction:
Given the following Python 3 function, write the documentation
def run(self):
        # type: () -> None
        """Run a device where configure() has already be called

        Normally it will return in Ready state. If setup for multiple-runs with
        a single configure() then it will return in Armed state. If the user
        aborts then it will return in Aborted state. If something goes wrong it
        will return in Fault state. If the user disables then it will return in
        Disabled state.
        """
        if self.configured_steps.value < self.total_steps.value:
            next_state = ss.ARMED
        else:
            next_state = ss.READY
        try:
            self.transition(ss.RUNNING)
            hook = RunHook
            going = True
            while going:
                try:
                    self.do_run(hook)
                except AbortedError:
                    self.abort_queue.put(None)
                    # Wait for a response on the resume_queue
                    should_resume = self.resume_queue.get()
                    if should_resume:
                        # we need to resume
                        hook = ResumeHook
                        self.log.debug("Resuming run")
                    else:
                        # we don't need to resume, just drop out
                        raise
                else:
                    going = False
            self.abortable_transition(next_state)
        except AbortedError:
            raise
        except Exception as e:
            self.go_to_error_state(e)
            raise

Response:
Run a device where configure has already been called with
       .


Instruction:
How would you explain what the following Python 3 function does
def abort(self):
        # type: () -> None
        """Abort the current operation and block until aborted

        Normally it will return in Aborted state. If something goes wrong it
        will return in Fault state. If the user disables then it will return in
        Disabled state.
        """
        # Tell _call_do_run not to resume
        if self.resume_queue:
            self.resume_queue.put(False)
        self.try_aborting_function(ss.ABORTING, ss.ABORTED, self.do_abort)

Response:
Abort the current operation and block until aborted
            is set to True.


Instruction:
How would you explain what the following Python 3 function does
def pause(self, lastGoodStep=0):
        # type: (ALastGoodStep) -> None
        """Pause a run() so that resume() can be called later, or seek within
        an Armed or Paused state.

        The original call to run() will not be interrupted by pause(), it will
        wait until the scan completes or is aborted.

        Normally it will return in Paused state. If the user aborts then it will
        return in Aborted state. If something goes wrong it will return in Fault
        state. If the user disables then it will return in Disabled state.
        """
        current_state = self.state.value
        if lastGoodStep <= 0:
            last_good_step = self.completed_steps.value
        else:
            last_good_step = lastGoodStep
        if current_state == ss.RUNNING:
            next_state = ss.PAUSED
        else:
            next_state = current_state
        assert last_good_step < self.total_steps.value, \
            "Cannot seek to after the end of the scan"
        self.try_aborting_function(
            ss.SEEKING, next_state, self.do_pause, last_good_step)

Response: Pause a run so that the user can seek within the scan.


Instruction:
Given the following Python 3 function, write the documentation
def resume(self):
        # type: () -> None
        """Resume a paused scan.

        Normally it will return in Running state. If something goes wrong it
        will return in Fault state.
        """
        self.transition(ss.RUNNING)
        self.resume_queue.put(True)

Response: Resume a paused scan.


Instruction:
Make a summary of the following Python 3 code
def create_info(cls, configure_func):
        # type: (Callable) -> ConfigureParamsInfo
        """Create a `ConfigureParamsInfo` describing the extra parameters
        that should be passed at configure"""
        call_types = getattr(configure_func, "call_types",
                             {})  # type: Dict[str, Anno]
        metas = OrderedDict()
        required = []
        defaults = OrderedDict()
        for k, anno in call_types.items():
            if k not in cls.call_types:
                scls = VMeta.lookup_annotype_converter(anno)
                metas[k] = scls.from_annotype(anno, writeable=True)
                if anno.default is NO_DEFAULT:
                    required.append(k)
                elif anno.default is not None:
                    defaults[k] = anno.default
        return ConfigureParamsInfo(metas, required, defaults)

Response:
Create a ConfigureParamsInfo describing the extra parameters
        that should be passed at configure


Instruction:
Explain what the following Python 3 code does
def register_hooked(self,
                        hooks,  # type: Union[Type[Hook], Sequence[Type[Hook]]]
                        func,  # type: Hooked
                        args_gen=None  # type: Optional[ArgsGen]
                        ):
        # type: (Type[Hook], Callable, Optional[Callable]) -> None
        """Register func to be run when any of the hooks are run by parent

        Args:
            hooks: A Hook class or list of Hook classes of interest
            func: The callable that should be run on that Hook
            args_gen: Optionally specify the argument names that should be
                passed to func. If not given then use func.call_types.keys
        """
        if self.hooked is None:
            self.hooked = {}
        if args_gen is None:
            args_gen = getattr(func, "call_types", {}).keys
        if not isinstance(hooks, Sequence):
            hooks = [hooks]
        for hook_cls in hooks:
            self.hooked[hook_cls] = (func, args_gen)

Response: Register func to be run when any of the hooks are run by parent


Instruction:
Write a Python 3 script for
taking a hook and optionally calls hook. run on a function

Response:
def on_hook(self, hook):
        # type: (Hook) -> None
        """Takes a hook, and optionally calls hook.run on a function"""
        try:
            func, args_gen = self.hooked[type(hook)]
        except (KeyError, TypeError):
            return
        else:
            hook(func, args_gen())


Instruction:
Explain what the following Python 3 code does
def transition_allowed(self, initial_state, target_state):
        # type: (str, str) -> bool
        """Check if a transition between two states is allowed"""
        assert initial_state in self._allowed, \
            "%s is not in %s" % (initial_state, list(self._allowed))
        return target_state in self._allowed[initial_state]

Response: Check if a transition between two states is allowed


Instruction:
Can you generate a brief explanation for the following Python 3 code
def set_allowed(self, initial_state, *allowed_states):
        # type: (str, *str) -> None
        """Add an allowed transition from initial_state to allowed_states"""
        allowed_states = list(allowed_states)
        self._allowed.setdefault(initial_state, set()).update(allowed_states)
        for state in allowed_states + [initial_state]:
            if state not in self.possible_states:
                self.possible_states.append(state)

Response: Add an allowed transition from initial_state to allowed_states


Instruction:
Write a Python 3 script for
defining a string parameter coming from a shell command to be used within this YAML file.

Response:
def cmd_string(name, cmd):
    # type: (AName, ACmd) -> ADefine
    """Define a string parameter coming from a shell command to be used within
    this YAML file. Trailing newlines will be stripped."""
    value = subprocess.check_output(cmd, shell=True).rstrip("\n")
    return Define(name, value)


Instruction:
Given the following Python 3 function, write the documentation
def export_env_string(name, value):
    # type: (AEnvName, AEnvValue) -> ADefine
    """Exports an environment variable with the given value"""
    os.environ[name] = value
    return Define(name, value)

Response: Exports an environment variable with the given value


Instruction:
Make a summary of the following Python 3 code
def module_path(name, path):
    # type: (AModuleName, AModulePath) -> ADefine
    """Load an external malcolm module (e.g. ADCore/etc/malcolm)"""
    define = Define(name, path)
    assert os.path.isdir(path), "%r doesn't exist" % path
    name = "malcolm.modules.%s" % name
    import_package_from_path(name, path)
    return define

Response: Load an external malcolm module.


Instruction:
Write a Python 3 script to
pass response from server to process receive queue

Response:
def on_message(self, message):
        """Pass response from server to process receive queue

        Args:
            message(str): Received message
        """
        # Called in tornado loop
        try:
            self.log.debug("Got message %s", message)
            d = json_decode(message)
            response = deserialize_object(d, Response)
            if isinstance(response, (Return, Error)):
                request = self._request_lookup.pop(response.id)
                if isinstance(response, Error):
                    # Make the message an exception so it can be raised
                    response.message = ResponseError(response.message)
            else:
                request = self._request_lookup[response.id]
            # Transfer the work of the callback to cothread
            cothread.Callback(request.callback, response)
        except Exception:
            # If we don't catch the exception here, tornado will spew odd
            # error messages about 'HTTPRequest' object has no attribute 'path'
            self.log.exception("on_message(%r) failed", message)