srtree 3.0.2.0 → 3.1.0.0
raw patch · 5 files changed
+312/−86 lines, 5 filesPVP ok
version bump matches the API change (PVP)
API changes (from Hackage documentation)
+ Algorithm.EqSat.Build: annotateBin :: Op -> [Fix SRTree] -> [(Fix SRTree, Int)]
+ Algorithm.EqSat.Build: annotateNAry :: NOp -> [Fix SRTree] -> [(Fix SRTree, Int)]
+ Algorithm.EqSat.Build: bySize :: [Fix SRTree] -> [(Fix SRTree, Int)]
+ Algorithm.EqSat.Build: chainSize :: [Fix SRTree] -> Int
+ Algorithm.EqSat.Build: crossBySize :: Int -> Int -> [[(a, Int)]] -> [[a]]
+ Algorithm.EqSat.Build: exprSize :: Fix SRTree -> Int
+ Algorithm.EqSat.Build: flattenMul :: Fix SRTree -> [Fix SRTree]
+ Algorithm.EqSat.Build: isRecFactor :: Fix SRTree -> Bool
+ Algorithm.EqSat.Build: maxClassVisits :: Int
+ Algorithm.EqSat.Build: maxExtractNodes :: Int
+ Algorithm.EqSat.Build: sizeBudget :: Int -> Int -> Int
+ Algorithm.EqSat.DB: matchBareVar :: forall (m :: Type -> Type). ClassStore m => Maybe String -> ClassOrVar -> EGraphST m [(Subst, ClassOrVar)]
- Algorithm.EqSat.Build: getNEclassFrom' :: forall (m :: Type -> Type). ClassStore m => Int -> Int -> EClassId -> EGraphST m [[EClassId]]
+ Algorithm.EqSat.Build: getNEclassFrom' :: forall (m :: Type -> Type). ClassStore m => Int -> Int -> IntMap Int -> EClassId -> EGraphST m [[EClassId]]
- Algorithm.EqSat.Build: getNExpressionsFrom :: forall (m :: Type -> Type). ClassStore m => Int -> EClassId -> EGraphST m [Fix SRTree]
+ Algorithm.EqSat.Build: getNExpressionsFrom :: forall (m :: Type -> Type). ClassStore m => Int -> Int -> EClassId -> EGraphST m [Fix SRTree]
- Algorithm.EqSat.Build: getNExpressionsFrom' :: forall (m :: Type -> Type). ClassStore m => Int -> Int -> EClassId -> EGraphST m [Fix SRTree]
+ Algorithm.EqSat.Build: getNExpressionsFrom' :: forall (m :: Type -> Type). ClassStore m => Int -> Int -> Int -> IntMap Int -> EClassId -> EGraphST m [Fix SRTree]
- Algorithm.EqSat.DB: matchSaturated :: forall (m :: Type -> Type). ClassStore m => Pattern -> EGraphST m [(Subst, ClassOrVar)]
+ Algorithm.EqSat.DB: matchSaturated :: forall (m :: Type -> Type). ClassStore m => Rule -> EGraphST m [(Subst, ClassOrVar)]
Files
- ChangeLog.md +33/−0
- src/Algorithm/EqSat.hs +4/−4
- src/Algorithm/EqSat/Build.hs +229/−73
- src/Algorithm/EqSat/DB.hs +45/−8
- srtree.cabal +1/−1
ChangeLog.md view
@@ -1,5 +1,38 @@ # Changelog for srtree +## 3.1.0.0++- **Bare-wildcard rule sources** (`Algorithm.EqSat.DB`): a rule whose source is+ a bare pattern variable (e.g. `v0 -> v0*v0/v0`) now matches every e-class+ (`matchBareVar`); previously the operator-anchored matchers silently matched+ nothing. The rule seen-set is keyed by the whole rule, so two rules sharing a+ source (e.g. `v0 -> v0*v0/v0` and `v0 -> v0+v0-v0`) no longer shadow each+ other's matches.+- **Constant folding no longer corrupts parameter structure**+ (`Algorithm.EqSat.Build`, `foldConsts`): a node whose constant analysis+ collapsed to `ParamIx` was replaced by `EParam`, so `recip(t0)` folded to+ `t0`, `t0 * t1` to `t0`, `t0 / t1` to `t0 * t1`, and rewrite targets such as+ `recip(t0) * ...` silently disappeared at insertion. Only true numeric+ constants fold now.+- **Cycle-safe expression extraction** (`Algorithm.EqSat.Build`): rules that+ merge an e-class with its own descendants (e.g. `v0 -> v0*v0/v0`) create+ cyclic e-classes; `getExpressionFrom`, `getAllExpressionsFrom`,+ `getNExpressionsFrom` and `getNEclassFrom` now carry a per-path e-class+ visit budget (`maxClassVisits`, a class already visited twice on a path is+ cut / replaced by a `Var 0` placeholder) and a global expansion budget+ (`maxExtractNodes`) split into equal slices per e-node and per child, and+ visit cost-best e-nodes first. The depth cap is consumed per nesting level+ (sibling e-nodes share their level).+- **Maximum expression size for enumeration** (`exprSize`, `crossBySize`):+ `getNExpressionsFrom` takes a maximum size (0 = unlimited) counted as the+ printed symbols of the expression (variables, parameters, constants and+ operators each count one; a division is one operator, including the+ printed `1` of a leading `(1 / z)` factor). Size-pruned cross products are+ generated with bounded work instead of materialising the full product.+- **BREAKING**: `getNExpressionsFrom`/`getNExpressionsFrom'` take the maximum+ size argument and a visit map; `getNEclassFrom'` takes a visit map;+ `matchSaturated` takes the whole `Rule` instead of its source pattern.+ ## 3.0.2.0 - **Pattern parser: reject trailing input** (`Text.ParseRule`): a pattern with
src/Algorithm/EqSat.hs view
@@ -319,9 +319,9 @@ matches <- mapM (\(rule, cq) -> map (rule,) <$> case cq of Just q -> do paged <- isPagedGraph if paged- then matchStreamCached (Just (show (source rule))) (source rule)- else matchCachedWith (Just (show (source rule))) q- Nothing -> matchSaturated (source rule)) $ concat filtered+ then matchStreamCached (Just (show rule)) (source rule)+ else matchCachedWith (Just (show rule)) q+ Nothing -> matchSaturated rule) $ concat filtered -- bound the total number of matches applied per iteration so a -- single iteration's apply/rebuild work stays bounded on huge -- graphs (genuine matches; we just process them over more iters).@@ -379,7 +379,7 @@ getNMatches n [] = pure [] getNMatches 0 _ = pure [] getNMatches n ([]:rss) = getNMatches n rss- getNMatches n ((r:rs):rss) = do matches <- map (r,) <$> matchSaturated (source r)+ getNMatches n ((r:rs):rss) = do matches <- map (r,) <$> matchSaturated r let (x, _) = splitAt n matches m = length x if m == n
src/Algorithm/EqSat/Build.hs view
@@ -35,7 +35,7 @@ import GHC.Stack (HasCallStack) import Data.SRTree.Recursion (cataM)-import Data.List (sort)+import Data.List (sort, sortOn, foldl') import Algorithm.EqSat.Info import qualified Data.IntSet as IntSet @@ -106,10 +106,16 @@ add costFun =<< mkENary EMul [negOne, t] -- | Fused 'calculateConsts' + 'foldConstants': fetches each child's constant--- info a single time, detects fully-constant nodes (replaced by EConst/EParam)--- and folds together all-but-one constant children of an ENAry+-- info a single time, detects fully-constant nodes (replaced by EConst) and+-- folds together all-but-one constant children of an ENAry -- (e.g. 2+3+x becomes 5+x). Constants that are already folded single subtrees -- are handled by the same child-constant walk.+--+-- Only true numeric constants ('ConstVal') fold: an analysis result of+-- 'ParamIx' must NOT replace the node with @EParam@ -- that used to corrupt+-- any pure-parameter structure at insertion (e.g. @recip(t0)@ folded to @t0@,+-- @t0 * t1@ to @t0@, @t0 / t1@ to @t0 * t1@), breaking rules such as+-- @t0 * ... -> recip(t0) * ...@. foldConsts :: (ClassStore m, HasCallStack) => CostFun -> ENode -> EGraphST m ENode foldConsts _ en@(ENAry _ m) | IntMap.null m = pure en foldConsts costFun en@(ENAry op m) = do@@ -117,13 +123,11 @@ infos <- mapM (fmap (_consts . _info) . getEClass) xs case foldr1 (\a b -> combineConsts (Bin (toOp op) a b)) infos of ConstVal x -> pure (EConst x)- ParamIx x -> pure (EParam x) _ -> foldENary costFun op m infos foldConsts _ en = do infos <- mapM (fmap (_consts . _info) . getEClass) (eChildren en) case combineConsts (replaceChildren infos (fromENode en)) of ConstVal x -> pure (EConst x)- ParamIx x -> pure (EParam x) _ -> pure en {-# INLINE foldConsts #-} @@ -543,103 +547,255 @@ getBestENode eid = (_best . _info) <$> getEClass eid {-# INLINE getBestENode #-} +-- | Maximum number of times an extraction may expand the same e-class along+-- any root-to-leaf expansion path. Rules such as @v0 -> v0 * v0 / v0@ make an+-- e-class contain itself (a cyclic e-class); without a per-class visit budget+-- the extractions below re-enter the cycle until their depth cap and the work+-- explodes combinatorially (or never terminates). Sibling (non-nested)+-- occurrences of a class are not limited -- only re-entry along one path.+maxClassVisits :: Int+maxClassVisits = 2++-- | Expression size used by the @maxlen@ pruning: the number of symbols of+-- the expression as printed -- every variable, parameter and numeric+-- constant counts one, every operator counts one, and a division is a single+-- operator (@Recip@ inside a product is the division; a product starting with+-- a division also counts the printed @1@ of @(1 / z)@). E.g.+-- @x0 * (t0 / (x1 ^ 2.0))@ has size 7, @x0 + x0 - x0@ has size 7 and+-- @(t0 + t0 + t0) * (x0 / (1 + x1))@ has size 11.+exprSize :: Fix SRTree -> Int+exprSize (Fix (Var _)) = 1+exprSize (Fix (Param _)) = 1+exprSize (Fix (Const _)) = 1+exprSize (Fix (Y _)) = 1+exprSize (Fix (Uni _ t)) = 1 + exprSize t+exprSize (Fix (Bin Mul l r)) = chainSize (flattenMul l ++ flattenMul r)+exprSize (Fix (Bin _ l r)) = 1 + exprSize l + exprSize r++-- | Printed size of a product chain: the symbols of every factor (a @Recip@+-- factor is @/ arg@, i.e. one operator plus its argument), one @*@ per join+-- between rendered units, and the @1@ placeholder when the chain starts with+-- a division.+chainSize :: [Fix SRTree] -> Int+chainSize fs = sum (map exprSize fs) + length plains + 2 * lead - 1+ where+ plains = filter (not . isRecFactor) fs+ lead = if not (null fs) && isRecFactor (head fs) then 1 else 0++isRecFactor :: Fix SRTree -> Bool+isRecFactor (Fix (Uni Recip _)) = True+isRecFactor _ = False++-- | The factors of a left-nested @*@ chain.+flattenMul :: Fix SRTree -> [Fix SRTree]+flattenMul (Fix (Bin Mul l r)) = flattenMul l ++ flattenMul r+flattenMul t = [t]++-- | The size budget for the children of a node whose own overhead is+-- @overhead@ symbols (0 = no limit on the total).+sizeBudget :: Int -> Int -> Int+sizeBudget mlen overhead = if mlen <= 0 then maxBound else max 0 (mlen - overhead)++-- | Cartesian product picking one element per list, keeping only the+-- combinations whose annotated sizes sum to at most @budget@, at most @n@ of+-- them. The lists must be sorted by size ascending (see 'bySize'), so a+-- branch is cut as soon as one element exceeds the remaining budget.+-- The intermediate partial combinations are capped at @maxPartials@, so a+-- size-sparse cross product costs bounded work (k * cap * list length) and+-- never the full product of the input lists.+crossBySize :: Int -> Int -> [[(a, Int)]] -> [[a]]+crossBySize n budget lists =+ take n [ reverse p | (p, _) <- foldl' step [([], budget)] lists ]+ where+ maxPartials = max 100 (2 * n)+ -- raw pairs examined per list per step: bounds the work of a size-sparse+ -- cross product (dense ones stop early anyway)+ maxScan = max 2000 (8 * n)+ step partials xs =+ take maxPartials+ (take maxScan+ [ (a : p, b - sa)+ | (p, b) <- partials+ , (a, sa) <- takeWhile ((<= b) . snd) xs ])++-- | Annotate trees with their 'exprSize' and sort ascending by size. This is+-- the exact per-child cost for any position (in a product chain a @Recip@+-- factor costs its printed @/ arg@, which equals its standalone 'exprSize');+-- the join/@1@ placeholder overhead of a chain is carried by the caller's+-- 'sizeBudget' and the exact 'exprSize' guard on the built tree.+bySize :: [Fix SRTree] -> [(Fix SRTree, Int)]+bySize = sortOn snd . map (\t -> (t, exprSize t))++-- | Annotate the children of a binary node (kept for call-site symmetry).+annotateBin :: Op -> [Fix SRTree] -> [(Fix SRTree, Int)]+annotateBin _ = bySize++-- | The same for the children of an n-ary node.+annotateNAry :: NOp -> [Fix SRTree] -> [(Fix SRTree, Int)]+annotateNAry _ = bySize+ -- | returns one expression rooted at e-class `eId`--- TODO: avoid loopings+-- Cycle-safe: a class already expanded 'maxClassVisits' times on the current+-- path is replaced by a @Var 0@ placeholder (same convention as+-- 'getBestExprBounded'), so cyclic e-classes yield a finite tree instead of+-- looping. getExpressionFrom :: ClassStore m => EClassId -> EGraphST m (Fix SRTree)-getExpressionFrom eId' = do- nodes <- _eNodes <$> getEClass eId'- case Set.toList nodes of- (n:_) -> case n of- EVar ix -> pure $ Fix $ Var ix- EParam ix -> pure $ Fix $ Param ix- EConst x -> pure $ Fix $ Const x- EUni f t -> Fix . Uni f <$> getExpressionFrom t- EBin op l r -> Fix <$> (Bin op <$> getExpressionFrom l <*> getExpressionFrom r)- ENAry op xs -> naryTree op <$> mapM getExpressionFrom (expandedList xs)- [] -> error "getExpressionFrom: empty eclass"+getExpressionFrom = go IntMap.empty+ where+ go visits eId' = do+ let visits' = IntMap.insertWith (+) eId' 1 visits+ if visits' IntMap.! eId' > maxClassVisits+ then pure (Fix (Var 0))+ else do+ nodes <- _eNodes <$> getEClass eId'+ case Set.toList nodes of+ (n:_) -> case n of+ EVar ix -> pure $ Fix $ Var ix+ EParam ix -> pure $ Fix $ Param ix+ EConst x -> pure $ Fix $ Const x+ EUni f t -> Fix . Uni f <$> go visits' t+ EBin op l r -> Fix <$> (Bin op <$> go visits' l <*> go visits' r)+ ENAry op xs -> naryTree op <$> mapM (go visits') (expandedList xs)+ [] -> error "getExpressionFrom: empty eclass" {-# INLINE getExpressionFrom #-} -- | returns all expressions rooted at e-class `eId`--- TODO: check for infinite list+-- Cycle-safe: expansion branches whose path has already visited an e-class+-- 'maxClassVisits' times are cut (returning no trees), so cyclic e-classes+-- contribute a finite family of expressions instead of an infinite list. getAllExpressionsFrom :: ClassStore m => EClassId -> EGraphST m [Fix SRTree]-getAllExpressionsFrom eId' = do- nodes <- Set.toList . _eNodes <$> getEClass eId'- go nodes+getAllExpressionsFrom = go IntMap.empty where- go [] = pure []- go (n:ns) = do+ go visits eId' = do+ let visits' = IntMap.insertWith (+) eId' 1 visits+ if visits' IntMap.! eId' > maxClassVisits+ then pure []+ else do+ nodes <- Set.toList . _eNodes <$> getEClass eId'+ goNodes visits' nodes+ goNodes _ [] = pure []+ goNodes visits (n:ns) = do t <- case n of EVar ix -> pure [Fix $ Var ix] EParam ix -> pure [Fix $ Param ix] EConst x -> pure [Fix $ Const x]- EUni f t -> Prelude.map (Fix . Uni f) <$> getAllExpressionsFrom t- EBin op l r -> do l' <- getAllExpressionsFrom l- r' <- getAllExpressionsFrom r+ EUni f t -> Prelude.map (Fix . Uni f) <$> go visits t+ EBin op l r -> do l' <- go visits l+ r' <- go visits r pure $ [Fix $ Bin op li ri | li <- l', ri <- r']- ENAry op xs -> do ts <- mapM getAllExpressionsFrom (expandedList xs)+ ENAry op xs -> do ts <- mapM (go visits) (expandedList xs) pure [ naryTree op comb | comb <- sequence ts ]- ts <- go ns+ ts <- goNodes visits ns pure (t ++ ts) {-# INLINE getAllExpressionsFrom #-} -getNExpressionsFrom :: ClassStore m => Int -> EClassId -> EGraphST m [Fix SRTree]-getNExpressionsFrom n eId' = getNExpressionsFrom' n 15 eId' +-- | Up to @n@ expressions rooted at @eId'@; trees of size more than @mlen@+-- (@mlen <= 0@ = no limit, size as in 'exprSize') are pruned as they are+-- built.+-- | Cap on the total number of e-class expansions per top-level extraction+-- call. Together with the per-path visit budget ('maxClassVisits') this+-- bounds the search *work* on dense/cyclic graphs, where the per-path budget+-- alone still leaves a combinatorial number of distinct paths; results are+-- truncated rather than letting the search explode.+maxExtractNodes :: Int+maxExtractNodes = 20000 -getNExpressionsFrom' :: ClassStore m => Int -> Int -> EClassId -> EGraphST m [Fix SRTree]-getNExpressionsFrom' _ 0 _ = pure []-getNExpressionsFrom' n d eId' = do- nodes <- Set.toList . _eNodes <$> getEClass eId'- (concat <$> go n d nodes)+getNExpressionsFrom :: ClassStore m => Int -> Int -> EClassId -> EGraphST m [Fix SRTree]+getNExpressionsFrom n mlen eId' = getNExpressionsFrom' n mlen 15 IntMap.empty eId' ++-- | Like 'getNExpressionsFrom', with an explicit depth cap, a per-path+-- e-class visit count (see 'maxClassVisits') and a total expansion budget+-- ('maxExtractNodes'): a class whose path budget is exhausted contributes no+-- trees, cutting cyclic re-entry instead of expanding it to the depth cap.+getNExpressionsFrom' :: ClassStore m => Int -> Int -> Int -> IntMap Int -> EClassId -> EGraphST m [Fix SRTree]+getNExpressionsFrom' n mlen d visits eId' = fst <$> goClass n d maxExtractNodes visits eId' where- isTerm (EVar _) = True- isTerm (EConst _) = True- isTerm (EParam _) = True- isTerm _ = False- toTree (EVar ix) = Fix $ Var ix- toTree (EConst x) = Fix $ Const x- toTree (EParam ix) = Fix $ Param ix- toTree _ = undefined+ small t = mlen <= 0 || exprSize t <= mlen - go n' _ [] = pure []- go n' 0 ts = pure []- go n' d (node:ns) = do- tt <- case node of- EVar ix -> pure [Fix $ Var ix]- EParam ix -> pure [Fix $ Param ix]- EConst x -> pure [Fix $ Const x]- EUni f t -> Prelude.map (Fix . Uni f) <$> getNExpressionsFrom' n' (d-1) t- EBin op l r -> do l' <- getNExpressionsFrom' n' (d-1) l- r' <- getNExpressionsFrom' n' (d-1) r- pure $ Prelude.take n [Fix $ Bin op li ri | li <- l', ri <- r']- ENAry op xs -> do ts <- mapM (getNExpressionsFrom' n' (d-1)) (expandedList xs)- pure $ Prelude.take n [ naryTree op comb | comb <- sequence ts ]+ -- returns the expressions of the class and the remaining global budget+ goClass n' d b v e+ | b <= 0 || d <= 0 = pure ([], b)+ | otherwise = do+ let v' = IntMap.insertWith (+) e 1 v+ if v' IntMap.! e > maxClassVisits+ then pure ([], b)+ else do+ ec <- getEClass e+ let best = _best (_info ec)+ -- the cost-best e-node (usually the natural/terminal one)+ -- first, terminals before deep junk: cycle e-nodes must not+ -- starve the enumeration of the natural trees+ nodes = sortOn (\en -> (if en == best then 0 else 1, length (eChildren en)))+ (Set.toList (_eNodes ec))+ (tts, b') <- goNodes n' d (b - 1) v' nodes+ pure (concat tts, b')++ goNodes _ _ b _ [] = pure ([], b)+ goNodes _ 0 b _ _ = pure ([], b)+ goNodes n' d b v nodes@(node:ns) = do+ -- every e-node gets an equal slice of the expansion budget, so cycle+ -- e-nodes cannot starve the natural ones+ let bSlice = max 1 (b `div` length nodes)+ (tt, _) <- case node of+ EVar ix -> pure ([Fix $ Var ix], bSlice)+ EParam ix -> pure ([Fix $ Param ix], bSlice)+ EConst x -> pure ([Fix $ Const x], bSlice)+ EUni f t -> do (ts, _) <- goClass n' (d-1) bSlice v t+ pure (filter small (Prelude.map (Fix . Uni f) ts), bSlice)+ EBin op l r -> do (l', _) <- goClass n' (d-1) (bSlice `div` 2) v l+ (r', _) <- goClass n' (d-1) (bSlice `div` 2) v r+ pure ( [ t | [li, ri] <- crossBySize n (sizeBudget mlen (if op == Mul then 0 else 1))+ [annotateBin op l', annotateBin op r']+ , let t = Fix (Bin op li ri), small t ]+ , bSlice)+ ENAry op xs -> do let ys = expandedList xs+ (tss, _) <- goClasses n' (d-1) bSlice v ys+ let k = length ys+ pure ( [ t | comb <- crossBySize n (sizeBudget mlen (if op == EMul then 0 else k-1))+ (map (annotateNAry op) tss)+ , let t = naryTree op comb, small t ]+ , bSlice) let n'' = n' - length tt if n'' <= 0- then pure [tt]- else do ts <- go n'' (d-1) ns- pure (tt:ts)+ then pure ([tt], max 0 (b - bSlice))+ else do (ts, b2) <- goNodes n'' d (max 0 (b - bSlice)) v ns -- sibling e-nodes share the depth level+ pure (tt:ts, b2) + goClasses _ _ b _ [] = pure ([], b)+ goClasses n' d b v xs = goC xs+ where+ bEach = max 1 (b `div` length xs) -- equal slice per child+ goC [] = pure ([], b)+ goC (x:rest) = do+ (ts, _) <- goClass n' d bEach v x+ (tss, b'') <- goC rest+ pure (ts : tss, b'')+ getNEclassFrom :: ClassStore m => Int -> EClassId -> EGraphST m [[EClassId]]-getNEclassFrom n eid = getNEclassFrom' n 15 eid+getNEclassFrom n eid = getNEclassFrom' n 15 IntMap.empty eid -getNEclassFrom' :: ClassStore m => Int -> Int -> EClassId -> EGraphST m [[EClassId]]-getNEclassFrom' _ 0 _ = pure []-getNEclassFrom' n d eId' = do- eId <- canonical eId'- nodes <- Set.toList . _eNodes <$> getEClass eId'- (Prelude.map (eId:) <$> go n d nodes)+getNEclassFrom' :: ClassStore m => Int -> Int -> IntMap Int -> EClassId -> EGraphST m [[EClassId]]+getNEclassFrom' _ 0 _ _ = pure []+getNEclassFrom' n d visits eId' = do+ let visits' = IntMap.insertWith (+) eId' 1 visits+ if visits' IntMap.! eId' > maxClassVisits+ then pure []+ else do+ eId <- canonical eId'+ nodes <- Set.toList . _eNodes <$> getEClass eId'+ (Prelude.map (eId:) <$> go n d visits' nodes) where --go :: Int -> Int -> [ENode] -> EGraphST m [[EClassId]]- go n' _ [] = pure []- go n' 0 ts = pure []- go n' d (node:ns) = do+ go n' _ _ [] = pure []+ go n' 0 _ ts = pure []+ go n' d v (node:ns) = do tt <- case node of- EBin op l r -> do l' <- getNEclassFrom' n' (d-1) l- r' <- getNEclassFrom' n' (d-1) r+ EBin op l r -> do l' <- getNEclassFrom' n' (d-1) v l+ r' <- getNEclassFrom' n' (d-1) v r pure $ Prelude.take n [li <> ri | li <- l', ri <- r']- ENAry op xs -> do ts <- mapM (getNEclassFrom' n' (d-1)) xs+ ENAry op xs -> do ts <- mapM (getNEclassFrom' n' (d-1) v) xs pure $ Prelude.take n [ concat comb | comb <- sequence ts ]- EUni f t -> getNEclassFrom' n' (d-1) t -- [[eid2:eid1]]+ EUni f t -> getNEclassFrom' n' (d-1) v t -- [[eid2:eid1]] EVar ix -> pure [[]] EConst x -> pure [[]] EParam ix -> pure [[]]
src/Algorithm/EqSat/DB.hs view
@@ -23,6 +23,7 @@ import GHC.Stack (HasCallStack) import Data.IntMap.Strict (IntMap) import qualified Data.IntMap.Strict as IntMap+import qualified Data.IntSet as IntSet import Data.Map (Map) import qualified Data.Map as Map import Data.List (sortBy)@@ -225,6 +226,10 @@ -- would dominate on rules whose @genericJoin@ yields many matches. 'Nothing' -- disables the seen-set (pure queries). matchCachedWith :: ClassStore m => Maybe String -> (Query, [ClassOrVar], ClassOrVar) -> EGraphST m [(Subst, ClassOrVar)]+-- a bare pattern variable source (e.g. `v0 -> v0 * v0 / v0`) compiles to an+-- empty atom query: there is no root operator to anchor the join on, so it+-- gets its own all-classes matching path.+matchCachedWith mSk ([], _, root) = matchBareVar mSk root matchCachedWith mSk (q, vars, root) = do ss <- genericJoin q vars root seenSk <- case mSk of@@ -249,14 +254,18 @@ -- | Saturation matching: consults/marks the persistent seen-set so each rule's -- per-iteration budget advances to genuinely new matches across ban/unban.-matchSaturated :: ClassStore m => Pattern -> EGraphST m [(Subst, ClassOrVar)]-matchSaturated src = if hasNAry src- then matchNAryWith (Just (show src)) src- else do- paged <- isPagedGraph- if paged- then matchStreamCached (Just (show src)) src- else matchCachedWith (Just (show src)) (compileToQuery src)+-- Keyed by the whole rule (not just its source) so two rules sharing a source+-- pattern (e.g. @v0 -> v0 * v0 / v0@ and @v0 -> v0 + v0 - v0@) do not shadow+-- each other's roots.+matchSaturated :: ClassStore m => Rule -> EGraphST m [(Subst, ClassOrVar)]+matchSaturated r = let src = source r in+ if hasNAry src+ then matchNAryWith (Just (show r)) src+ else do+ paged <- isPagedGraph+ if paged+ then matchStreamCached (Just (show r)) src+ else matchCachedWith (Just (show r)) (compileToQuery src) {-# INLINE matchSaturated #-} -- | True if the pattern (or a nested child) is an n-ary Add/Mul pattern.@@ -355,6 +364,10 @@ -- visits; the persistent mark-on-attempt seen-set makes each rule's budgets -- advance to new roots across the scheduler's ban/unban cycles. matchStreamCached :: ClassStore m => Maybe String -> Pattern -> EGraphST m [(Subst, ClassOrVar)]+-- a bare pattern variable source has no operator to stream roots for+-- ('opOfMay' is Nothing) and would silently match nothing: give it the+-- all-classes matching path instead.+matchStreamCached mSk (VarPat c) = matchBareVar mSk (Right (fromEnum c)) matchStreamCached mSk src = do seen <- case mSk of Nothing -> pure RangeSet.empty@@ -388,6 +401,30 @@ opOfMay (Fixed t) = Just (getOperator t) opOfMay _ = Nothing {-# INLINE opOfMay #-}++-- | Match a bare pattern-variable source (e.g. @v0 -> v0 * v0 / v0@), binding+-- the variable to every e-class in the graph. A bare wildcard has no root+-- operator, so the operator-anchored matchers ('matchStreamCached' /+-- 'matchCachedWith') cannot enumerate candidate roots for it and would+-- silently match nothing. Every e-class is a candidate root; the match is+-- prolific by construction, so it is bounded exactly like the streaming+-- matcher: at most 'ruleMatchBudget' results per call, and the persistent+-- mark-on-attempt seen-set makes the budget advance to new roots across the+-- scheduler's ban/unban cycles.+matchBareVar :: ClassStore m => Maybe String -> ClassOrVar -> EGraphST m [(Subst, ClassOrVar)]+matchBareVar mSk root = do+ seen <- case mSk of+ Nothing -> pure RangeSet.empty+ Just sk -> gets (Map.findWithDefault RangeSet.empty sk . _seenMatches . _eDB)+ let ex = IntSet.fromList [ i | s <- RangeSet.toList seen, Just i <- [readMaybe s :: Maybe EClassId] ]+ roots <- allKeys+ let fresh = take ruleMatchBudget [ e | e <- roots, not (IntSet.member e ex) ]+ case mSk of+ Just sk -> modify' $ over (eDB . seenMatches)+ (Map.insertWith RangeSet.union sk (RangeSet.fromList (map show fresh)))+ Nothing -> pure ()+ pure [ (Map.singleton root (SVOne (Left eid)), Left eid) | eid <- fresh ]+{-# INLINE matchBareVar #-} -- | Recursively match a pattern against the e-class `eid`, threading a -- substitution map, returning every substitution that completes the match.
srtree.cabal view
@@ -5,7 +5,7 @@ -- see: https://github.com/sol/hpack name: srtree-version: 3.0.2.0+version: 3.1.0.0 synopsis: A general library to work with Symbolic Regression expression trees. description: A Symbolic Regression Tree data structure to work with mathematical expressions with support to first order derivative and simplification; license: BSD3