Skip to content

Adleman DNA computation of a Hamiltonian path

Adleman's DNA computation of a Hamiltonian path.

  • Class: DNAComputationSystem
  • Import: from skcomplex.systems.computer_science.automata import DNAComputationSystem
  • Field: computer_science/automata
  • Topics: dna computing, molecular computation, hamiltonian path, agents, stochastic
  • References:
    • Adleman 1994
    • Raman 2021

Use this system

The block imports the class and simulates the system with its default parameters and its tuned run settings.

from skcomplex.systems.computer_science.automata import DNAComputationSystem

trajectory = DNAComputationSystem().prepare().simulate()

Parameters

The model parameters take these defaults, and set_params changes them.

Parameter Default
n_strands 2000
edges ((0, 1), (0, 3), (0, 6), (1, 2), (1, 3), (2, 1), (2, 3), ...
start 0
end 6
random_state 0
solver 'auto'
backend 'auto'

Tags

The system with its default parameters has these capability tags, which solvers and analyses check.

Tag Values
Time discrete
Space none
Laws update
Randomness stochastic
Domains vector
Structure variable membership

Class

The source of the class shows how it builds its components from its model parameters.

class DNAComputationSystem(BaseSystem):
    """Adleman's DNA computation of a Hamiltonian path.

    It runs by random ligation of edge oligos in a test tube. Every node of a directed graph is an oligonucleotide, and
    every link an oligo that joins the end of one node to the start of the next, so ligation builds strands that spell
    random paths of the graph. The tube starts with edge oligos drawn uniformly from the links, which meet in random
    pairs and join when the end of one is the start of the other. Adleman's filters then keep the strands that start at
    `start` and end at `end`, that pass through as many nodes as the graph has, and that visit every node, and any
    strand left is a Hamiltonian path. On the graph of Adleman's experiment, with seven nodes and fourteen links,
    solutions appear after some steps and every one of them is the path 0, 1, 2, 3, 4, 5, 6, while a graph without a
    Hamiltonian path leaves no strand. The system has the group `strands` of paths `path`, padded with -1. Its standard
    observable `solutions` is the number of strands that pass the filters for the default nodes of Adleman's graph.

    Args:
        n_strands:
            The number of strands in the tube.

        edges:
            The directed links of the graph, with the nodes numbered from 0.

        start:
            The node the paths start at.

        end:
            The node the paths end at.

        random_state:
            The seed or generator of the initial oligos.

        label:
            The label of the system, which names it when it is nested in another one.

        solver:
            The solver of the problem, or `'auto'` for the one the system chooses.

        backend:
            The backend that evaluates the compiled functions, or `'auto'` for the one the system chooses.

    Raises:
        ParameterError:
            The graph has no links, or the start or the end is not a node of it.

    Examples:
        >>> from skcomplex.systems.computer_science.automata import DNAComputationSystem
        >>> DNAComputationSystem(10).prepare().system_.elements[0].path.shape
        (10, 7)
    """

    field = 'computer_science/automata'
    topics = ('dna computing', 'molecular computation', 'hamiltonian path', 'agents', 'stochastic')
    references = ('Adleman 1994', 'Raman 2021')
    until = 60
    observables = (Observable('solutions', group='strands', variable='path', reduce=_get_adleman_solutions),)

    def __init__(
        self,
        n_strands: int = 2000,
        *,
        edges: Sequence[tuple[int, int]] = ADLEMAN_EDGES,
        start: int = 0,
        end: int = 6,
        random_state: int | np.random.Generator | None = 0,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.n_strands = n_strands
        self.edges = edges
        self.start = start
        self.end = end
        self.random_state = random_state

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of a tube of random edge oligos and their ligation."""
        super()._prepare(context)
        nodes = {node for edge in self.edges for node in edge}
        if not self.edges or self.start not in nodes or self.end not in nodes:
            error_msg = f'The start {self.start!r} and the end {self.end!r} need to be nodes of a graph with links.'
            raise ParameterError(error_msg)
        rng = np.random.default_rng(self.random_state)
        paths = np.full((self.n_strands, len(nodes)), EMPTY)
        paths[:, :2] = np.asarray(self.edges)[rng.integers(len(self.edges), size=self.n_strands)]
        strands = StrandElement('strands', path=paths, size=self.n_strands)
        self.system_ = System(
            self.label,
            elements=[strands],
            interactions=[LigationInteraction('ligation', target='strands', edges=self.edges)],
        )

Components

The system uses these element and interaction classes, each with its nearest class of the core.

Elements:

Interactions:

  • LigationInteraction, from Interaction
class StrandElement(Element):
    """Strand of DNA in the test tube.

    It holds the path of nodes its ligated edge oligos spell, padded with -1.

    Args:
        label:
            The label of the strand or the group.

        path:
            The initial nodes of the path, padded with -1 to the longest path the tube holds, one row per strand.

        size:
            The number of strands, or `None` for one.

    Examples:
        >>> from skcomplex.systems.computer_science.automata import StrandElement
        >>> StrandElement('strand', path=(0, 1, -1)).path
        (0, 1, -1)
    """

    def __init__(
        self,
        label: str,
        *,
        path: object = EMPTY,
        size: int | None = None,
    ) -> None:
        super().__init__(label, size=size)
        self.path = path

class LigationInteraction(Interaction):
    """Random ligation of the strands of a test tube.

    It joins a strand that ends at a node to one that starts there. Every step the strands meet in random pairs. The
    oligo of the node that the first strand ends at and the second starts at holds their ends together, and the ligase
    joins them into one strand, as long as the joined path fits the longest path the tube holds. The second strand is
    consumed, and an edge oligo drawn uniformly from the links of the graph takes its place, since the tube holds a vast
    excess of oligos.

    Args:
        label:
            The label of the interaction.

        target:
            The path of the group of strands.

        edges:
            The directed links of the graph, one edge oligo each.

    Examples:
        >>> from skcomplex.systems.computer_science.automata import LigationInteraction
        >>> LigationInteraction('ligation', target='strands', edges=((0, 1),)).edges
        ((0, 1),)
    """

    draws = True

    law_classes = (UpdateLaw,)

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        edges: Sequence[tuple[int, int]] = ADLEMAN_EDGES,
    ) -> None:
        super().__init__(label)
        self.target = target
        self.edges = edges

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the rule of the ligations of a step, once for the whole tube.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        self.laws_: list[BaseLaw] = [UpdateLaw(context, self._ligate)]

    def _ligate(self, system: SystemView) -> None:
        """Join the strands of random pairs whose ends meet.

        Every consumed strand is replaced with a fresh oligo.
        """
        strands = cast(list[StrandView], system.get_agents('target'))
        rng = system.rng
        order = rng.permutation(len(strands))
        for first, second in zip(order[::2], order[1::2], strict=False):
            head, tail = np.asarray(strands[first].path), np.asarray(strands[second].path)
            head_length, tail_length = int((head >= 0).sum()), int((tail >= 0).sum())
            if head[head_length - 1] != tail[0] or head_length + tail_length - 1 > head.size:
                continue
            joined = head.copy()
            joined[head_length : head_length + tail_length - 1] = tail[1:tail_length]
            strands[first].path = joined
            strands[second].path = self._get_oligo(head.size, rng)

    def _get_oligo(self, size: int, rng: np.random.Generator) -> IntArray:
        """Return a fresh edge oligo drawn uniformly from the links.

        It is a path of two nodes padded to the size.
        """
        path = np.full(size, EMPTY)
        path[:2] = self.edges[int(rng.integers(len(self.edges)))]
        return path

Equations

The equations are those that symbolic returns for the system with its default parameters.