| Safe Haskell | None |
|---|---|
| Language | GHC2024 |
Proarrow.Tools.HypergraphRewrite
Contents
Description
Rewriting of open hypergraphs, modulo Frobenius wiring, with individual rules or a compiled discrimination net sharing matching work across rules. A rule's common boundary is the interface retained when replacing its left side. Fixed-pattern matches are injective on nodes and box occurrences. The left boundary must also be injective; the right boundary may join interface nodes. This is a restricted DPO rewriting operation, not a general pushout-complement search for DPOI.
See Proarrow.Tools.HypergraphRewrite.Completion for Knuth–Bendix-style completion and Proarrow.Tools.HypergraphRewrite.Laws for rule construction from categorical laws.
Synopsis
- data Rule s l
- rule :: forall s l (a :: OPENHG s l) (b :: OPENHG s l). (a ~> b) -> (a ~> b) -> Either String (Rule s l)
- (==>) :: forall s l (a :: OPENHG s l) (b :: OPENHG s l). (a ~> b) -> (a ~> b) -> Either String (Rule s l)
- data Parameter a
- mapParameter :: (a -> a) -> Parameter a -> Parameter a
- zipParameters :: (a -> a -> a) -> Parameter a -> Parameter a -> Parameter a
- parameterRule :: forall f a s (x :: OPENHG s (f (Parameter a))) (y :: OPENHG s (f (Parameter a))). (Traversable f, Eq (f ()), Typeable f, Eq a) => (x ~> y) -> (x ~> y) -> Either String (Rule s (f a))
- subgraphRule :: forall p l s (a :: OPENHG s p) (b :: OPENHG s p). (p -> Either l String) -> (a ~> b) -> (a ~> b) -> Either String (Rule s l)
- withSortParameters :: ([SomeSort s] -> [SomeSort s] -> [SomeSort s] -> Maybe [SomeSort s]) -> Rule s l -> Rule s l
- data Port
- data PortSymmetry
- data PortGraph s l = PortGraph [SomeSort s] [Int] [Box l Port]
- portRule :: DecidableIso s => PortGraph s l -> PortGraph s l -> Either String (Rule s l)
- parameterPortRule :: (DecidableIso s, Traversable f, Eq (f ()), Typeable f, Eq a) => PortGraph s (f (Parameter a)) -> PortGraph s (f (Parameter a)) -> Either String (Rule s (f a))
- parameterPortExample :: (String -> a) -> Rule s (f a) -> Either String (PortGraph s (f a), PortGraph s (f a))
- parameterPortVariants :: (f () -> PortSymmetry) -> Rule s (f a) -> Either String [Rule s (f a)]
- parameterPortRuleWith :: (DecidableIso s, Traversable f, Eq (f ()), Typeable f, Eq a) => PortGraph s (f (Parameter a)) -> (Map String Int -> PortGraph s (f (Parameter a))) -> Either String (Rule s (f a))
- rewrites :: forall {s} l (a :: OPENHG s l) (b :: OPENHG s l). (Eq l, DecidableIso s) => Rule s l -> (a ~> b) -> [(Wires (WireSorts a) :: OPENHG s l) ~> (Wires (WireSorts b) :: OPENHG s l)]
- rewriteBatch :: forall {s} l (as :: [s]) (bs :: [s]). (Eq l, DecidableIso s) => Rule s l -> ((Wires as :: OPENHG s l) ~> (Wires bs :: OPENHG s l)) -> (Int, (Wires as :: OPENHG s l) ~> (Wires bs :: OPENHG s l))
- data CompiledRules key s l
- compileRules :: (Ord key, Eq l, DecidableIso s) => [(key, Rule s l)] -> Either String (CompiledRules key s l)
- compileReducingRules :: (Ord key, Eq l, DecidableIso s) => [(key, Rule s l)] -> Either String (CompiledRules key s l)
- rewritesCompiled :: forall {s} key l (a :: OPENHG s l) (b :: OPENHG s l). (Eq l, DecidableIso s) => CompiledRules key s l -> (a ~> b) -> [(key, (Wires (WireSorts a) :: OPENHG s l) ~> (Wires (WireSorts b) :: OPENHG s l))]
- rewriteBatchCompiled :: forall {s} key l (as :: [s]) (bs :: [s]). (Eq l, DecidableIso s) => CompiledRules key s l -> ((Wires as :: OPENHG s l) ~> (Wires bs :: OPENHG s l)) -> (Int, (Wires as :: OPENHG s l) ~> (Wires bs :: OPENHG s l))
- data RewriteLimits = RewriteLimits {}
- unlimitedRewrites :: RewriteLimits
- data NormalisationStatus
- data NormalisationResult a = NormalisationResult {}
- normalise :: forall {s} key l (as :: [s]) (bs :: [s]). (Eq l, DecidableIso s) => RewriteLimits -> CompiledRules key s l -> ((Wires as :: OPENHG s l) ~> (Wires bs :: OPENHG s l)) -> NormalisationResult ((Wires as :: OPENHG s l) ~> (Wires bs :: OPENHG s l))
Rules
An oriented equation between diagrams with the same input and output sorts.
Construct with rule, parameterRule or subgraphRule. The interface consists of all boundary positions.
rule :: forall s l (a :: OPENHG s l) (b :: OPENHG s l). (a ~> b) -> (a ~> b) -> Either String (Rule s l) Source Github #
Construct a rule. Rejects repeated nodes across the left input and output boundaries, since this implementation requires an injective left interface. For example, a chain of two unary boxes can rewrite to an identity wire; the reverse orientation needs a more general complement construction.
(==>) :: forall s l (a :: OPENHG s l) (b :: OPENHG s l). (a ~> b) -> (a ~> b) -> Either String (Rule s l) infix 1 Source Github #
An oriented rule written left to right. This checks the same boundary
conditions as rule.
data Parameter a Source Github #
A literal value, a named parameter, or a computed replacement value. Repeated names in a rule bind equal values. Arithmetic constructs replacement expressions; computed expressions are rejected on the left of a rule.
Instances
| Num a => Num (Parameter a) Source Github # | |
Defined in Proarrow.Tools.HypergraphRewrite.Internal Methods (+) :: Parameter a -> Parameter a -> Parameter a Github # (-) :: Parameter a -> Parameter a -> Parameter a Github # (*) :: Parameter a -> Parameter a -> Parameter a Github # negate :: Parameter a -> Parameter a Github # abs :: Parameter a -> Parameter a Github # signum :: Parameter a -> Parameter a Github # fromInteger :: Integer -> Parameter a Github # | |
| Fractional a => Fractional (Parameter a) Source Github # | |
mapParameter :: (a -> a) -> Parameter a -> Parameter a Source Github #
Transform a replacement expression, for example to normalise a phase.
zipParameters :: (a -> a -> a) -> Parameter a -> Parameter a -> Parameter a Source Github #
Combine two replacement expressions, for example by adding phases modulo two.
parameterRule :: forall f a s (x :: OPENHG s (f (Parameter a))) (y :: OPENHG s (f (Parameter a))). (Traversable f, Eq (f ()), Typeable f, Eq a) => (x ~> y) -> (x ~> y) -> Either String (Rule s (f a)) Source Github #
Construct a rule with parameters in the Traversable fields of its labels.
Both diagrams have labels f (Parameter a); hosts have labels f a.
Constructors and fields outside the traversal match literally. Literal
matches one value; Variable binds a name shared across the whole rule.
Right-side expressions can use arithmetic and mapParameter. Unbound names
and computed left-side expressions are rejected when constructing the rule.
Rule topology and arity remain fixed. The compiled matcher dispatches on the label with its traversed fields erased, then checks bindings before choosing a batch. Each occurrence gets its own bindings and instantiated replacement.
subgraphRule :: forall p l s (a :: OPENHG s p) (b :: OPENHG s p). (p -> Either l String) -> (a ~> b) -> (a ~> b) -> Either String (Rule s l) Source Github #
Unary arrow parameters with explicit input and output boundaries. The
classifier returns Left for a literal label or Right for a parameter name.
Parameters capture connected regions with no external connections except their two boundaries;
identity captures identify those boundaries. Repeated names require boundary-
preserving graph isomorphism. RHS occurrences copy the captured region with
fresh internal nodes; omitted parameters are discarded.
This restricted higher-order matching follows the fixed-interface approach of Higher-order port-graph rewriting. Concrete boxes share the discrimination net. Capture regions are recovered from connected components after cutting at the matched pattern nodes. Disconnected captures and non-identity captures with coincident endpoints are not supported. Boundary nodes must each have one incident captured port, an input and an output respectively. Matching is structural, not modulo laws. Each complete match must contain at least one box; an unanchored identity cannot match. Structurally identical replacements are skipped. Identity captures may identify pattern nodes only across that parameter's endpoints.
withSortParameters :: ([SomeSort s] -> [SomeSort s] -> [SomeSort s] -> Maybe [SomeSort s]) -> Rule s l -> Rule s l Source Github #
Defer a rule's sort checks to a per-match instantiation. The callback receives the numbered pattern sorts, their matched host sorts, and replacement sorts. Return one instantiated sort per replacement node, or reject the candidate. The callback must validate the pattern sorts against the matched host sorts. Interface sorts are checked against the host before a replacement is accepted. Box selection and node binding still share the compiled discrimination net.
A numbered node, a named sequence of ports, or one element of a captured
sequence. Captures may be empty and preserve order and repeated nodes.
Element is available only on the right of a port rule.
data PortSymmetry Source Github #
Permitted permutations of a box's ports. Inputs and outputs permute independently.
Constructors
| OrderedPorts | |
| SymmetricInputs | |
| SymmetricOutputs | |
| SymmetricPorts |
Instances
| Show PortSymmetry Source Github # | |
Defined in Proarrow.Tools.HypergraphRewrite.Internal | |
| Eq PortSymmetry Source Github # | |
Defined in Proarrow.Tools.HypergraphRewrite.Internal Methods (==) :: PortSymmetry -> PortSymmetry -> Bool Github # (/=) :: PortSymmetry -> PortSymmetry -> Bool Github # | |
data PortGraph s l Source Github #
A port-rule fragment: sorts of numbered nodes, its explicit interface, and boxes. Every captured node is also preserved, including aliases between captures or with explicit interface nodes. RHS numbered nodes are fresh, except where glued to the left through the two explicit interfaces.
portRule :: DecidableIso s => PortGraph s l -> PortGraph s l -> Either String (Rule s l) Source Github #
Match variable port sequences with literal labels. A capture on the left matches a contiguous sequence; use captures before and after a numbered node to find a connection at any port position. Repeated names require equal sequences. Captured nodes cannot be deleted, even when they alias numbered nodes. Existing dangling, sort, injectivity and batch-conflict checks apply.
parameterPortRule :: (DecidableIso s, Traversable f, Eq (f ()), Typeable f, Eq a) => PortGraph s (f (Parameter a)) -> PortGraph s (f (Parameter a)) -> Either String (Rule s (f a)) Source Github #
A port rule with the label parameters of parameterRule. Both its
topology template and parameter names are checked when constructing the rule.
parameterPortExample :: (String -> a) -> Rule s (f a) -> Either String (PortGraph s (f a), PortGraph s (f a)) Source Github #
Instantiate the labels of a fixed parameterized port rule for inspection. The two fragments retain their capture names and numbered interfaces.
parameterPortVariants :: (f () -> PortSymmetry) -> Rule s (f a) -> Either String [Rule s (f a)] Source Github #
Expand a fixed parameterized port rule into ordered matching variants. The classifier sees the label with its parameters erased. Permute only numbered port lists on the left, preserving the boundary and replacement. Lists with captures stay ordered. Symmetric lists enumerate all distinct permutations with the original list first, so use this for small arities.
parameterPortRuleWith :: (DecidableIso s, Traversable f, Eq (f ()), Typeable f, Eq a) => PortGraph s (f (Parameter a)) -> (Map String Int -> PortGraph s (f (Parameter a))) -> Either String (Rule s (f a)) Source Github #
Build a replacement from capture lengths, for example one Hadamard per
captured leg. Element refers to an individual captured port. The builder
receives only lengths, not host node IDs. Replacement node references,
interface sorts, captures and parameter names are checked for each candidate;
an invalid replacement rejects that candidate before batch selection.
Rewriting
rewrites :: forall {s} l (a :: OPENHG s l) (b :: OPENHG s l). (Eq l, DecidableIso s) => Rule s l -> (a ~> b) -> [(Wires (WireSorts a) :: OPENHG s l) ~> (Wires (WireSorts b) :: OPENHG s l)] Source Github #
All valid single-step rewrites, in box and node enumeration order.
Works for closed hosts (empty boundaries) as well as open hosts. No result
deletes a node used by an unmatched box or the host boundary. Unmatched nodes,
including isolated nodes, are retained. Distinct matches may produce isomorphic results;
results are not deduplicated. Matching is a finite exhaustive search.
Compatible label/arity candidates are cached per pattern box, and mapped
ports constrain later boxes through incidence indices. Labels only need Eq.
rewriteBatch :: forall {s} l (as :: [s]) (bs :: [s]). (Eq l, DecidableIso s) => Rule s l -> ((Wires as :: OPENHG s l) ~> (Wires bs :: OPENHG s l)) -> (Int, (Wires as :: OPENHG s l) ~> (Wires bs :: OPENHG s l)) Source Github #
Apply a greedy maximal set of non-conflicting matches of one rule from a
single host snapshot, rebuilding the graph once. Returns the number applied
and the result, or (0, host) when the rule does not match.
Matches are considered in the same order as rewrites. They may share
preserved interface nodes, including adjacent regions connected through those
nodes. They cannot share boxes, or delete a node used by another chosen match.
Each replacement gets fresh nodes and all interfaces are glued simultaneously.
This selects one maximal batch, not a maximum-size batch or all possible batches.
New matches created by replacement are left for a later batch.
data CompiledRules key s l Source Github #
Rules compiled into a discrimination net of box-selection and port-binding tests. Common prefixes share their matching work. Graph-node bindings add repeated-wire, sort, and injectivity checks to the usual discrimination-net construction for many-to-one term matching; see MatchPy: A Pattern Matching Library. A single host index is shared by every rule in one matching pass.
Keys identify rules and give an explicit conflict priority: smaller keys win. The order of the input list does not affect matching or batch selection.
compileRules :: (Ord key, Eq l, DecidableIso s) => [(key, Rule s l)] -> Either String (CompiledRules key s l) Source Github #
Compile uniquely keyed rules. Box traversal favours connected boxes and
then boxes with more fixed ports; fixed arity breaks ties.
This anchors a mux before its constant inputs and fixed edges before captures.
Common tests are inserted into a discrimination trie, including bindings for
isolated nodes and separate searches for disconnected pattern components.
Literal labels dispatch by equality; parameter labels dispatch by constructor
and fixed fields. Bindings are checked separately for each rule at a terminal.
Compilation also compares sorts up to isomorphism. Rules using
withSortParameters defer sort validation to their terminals.
compileReducingRules :: (Ord key, Eq l, DecidableIso s) => [(key, Rule s l)] -> Either String (CompiledRules key s l) Source Github #
Compile rules with a strictly decreasing box-count policy. A candidate is accepted only when its instantiated replacement has fewer boxes than the matched region. This check precedes batch selection, so a rejected candidate cannot block a competing reduction. Parameters and dynamically constructed replacements are checked per match; compilation does not certify that every application of the supplied rules decreases.
Every application removes at least one box, and compatible batches cannot
share boxes. Consequently normalise with unlimitedRewrites terminates on
finite hosts after at most the initial number of boxes in rule applications,
assuming replacement callbacks terminate. Matching is still an exhaustive
finite search and may be expensive. Confluence is not guaranteed.
Equal-sized changes, including relabelling, and growing replacements are
excluded, even if semantically useful. NormalForm means no decreasing
application remains; other applications of the original rules may exist.
>>>import Proarrow.Category.Instance.OpenHypergraph (Box (..))>>>let before = unsafeOpenHypergraph [] [] [] [Box "x" [] []] :: (Wires '[] :: OPENHG () String) ~> Wires '[]>>>let after = unsafeOpenHypergraph [] [] [] [] :: (Wires '[] :: OPENHG () String) ~> Wires '[]>>>let r = either error id (before ==> after)>>>let compiled = either error id (compileReducingRules [((), r)])>>>let result = normalise unlimitedRewrites compiled before>>>(normalisationStatus result, normalisationRewrites result)(NormalForm,1)
rewritesCompiled :: forall {s} key l (a :: OPENHG s l) (b :: OPENHG s l). (Eq l, DecidableIso s) => CompiledRules key s l -> (a ~> b) -> [(key, (Wires (WireSorts a) :: OPENHG s l) ~> (Wires (WireSorts b) :: OPENHG s l))] Source Github #
Enumerate every valid match of every compiled rule, returning its key and
single-step result. Results are ordered by key, then by the original rule's
box and node enumeration order, as in rewrites. Matching work is shared;
overlapping matches and isomorphic results are retained.
rewriteBatchCompiled :: forall {s} key l (as :: [s]) (bs :: [s]). (Eq l, DecidableIso s) => CompiledRules key s l -> ((Wires as :: OPENHG s l) ~> (Wires bs :: OPENHG s l)) -> (Int, (Wires as :: OPENHG s l) ~> (Wires bs :: OPENHG s l)) Source Github #
Match the entire compiled rule set on one snapshot and apply one greedy
maximal batch across rules. Smaller keys have conflict priority; matches of
one rule follow rewrites order. Compatible matches of different rules share
the batch and the result is rebuilt once. Sharing and deletion conditions are
the same as in rewriteBatch. New matches wait for a subsequent batch.
Normalisation
data RewriteLimits Source Github #
Bounds on successful rule applications and batches. Nothing leaves that
count unrestricted; zero permits checking for a normal form but no applications.
These limits do not bound the cost of finding matches.
Constructors
| RewriteLimits | |
Fields | |
Instances
| Show RewriteLimits Source Github # | |
Defined in Proarrow.Tools.HypergraphRewrite.Internal | |
| Eq RewriteLimits Source Github # | |
Defined in Proarrow.Tools.HypergraphRewrite.Internal Methods (==) :: RewriteLimits -> RewriteLimits -> Bool Github # (/=) :: RewriteLimits -> RewriteLimits -> Bool Github # | |
unlimitedRewrites :: RewriteLimits Source Github #
No rewrite or batch limit. Use when the rules are known to terminate, or
with the strictly decreasing policy of compileReducingRules.
data NormalisationStatus Source Github #
Why normalisation stopped. A normal form has no applicable rule, even when a limit was reached exactly. If both limits prevent further rewriting, the rewrite limit takes precedence.
Constructors
| NormalForm | |
| RewriteLimitReached | |
| BatchLimitReached |
Instances
| Show NormalisationStatus Source Github # | |
Defined in Proarrow.Tools.HypergraphRewrite.Internal | |
| Eq NormalisationStatus Source Github # | |
Defined in Proarrow.Tools.HypergraphRewrite.Internal Methods (==) :: NormalisationStatus -> NormalisationStatus -> Bool Github # (/=) :: NormalisationStatus -> NormalisationStatus -> Bool Github # | |
data NormalisationResult a Source Github #
The current graph and counts of successful rule applications and nonempty
batches. Counts and limits are local to this call; the graph can be passed to
normalise again to continue after exhausting a limit.
Constructors
| NormalisationResult | |
normalise :: forall {s} key l (as :: [s]) (bs :: [s]). (Eq l, DecidableIso s) => RewriteLimits -> CompiledRules key s l -> ((Wires as :: OPENHG s l) ~> (Wires bs :: OPENHG s l)) -> NormalisationResult ((Wires as :: OPENHG s l) ~> (Wires bs :: OPENHG s l)) Source Github #
Repeatedly apply compatible batches from the compiled rule set. Matches
created by one batch are considered on the next snapshot. Conflict priorities
are those of compileRules. A rewrite limit can truncate a batch to its first
compatible matches, so neither limit is exceeded.
Stopping at a limit probes for further matches to distinguish exhaustion from
a normal form, without applying another rewrite. Ordinary rules do not compare
graphs: reproducing the left side still counts as an application and needs a
limit. Subgraph rules skip structurally identical replacements. Arbitrary
rule sets may not terminate with unlimitedRewrites;
compileReducingRules excludes all non-decreasing applications.