packages feed

srtree 2.0.1.2 → 2.0.1.4

raw patch · 19 files changed

+385/−2850 lines, 19 filesdep −ansi-terminaldep −replinedep −table-layoutdep ~splitPVP: major bump suggested

API removals or changes: PVP suggests a major version bump

Dependencies removed: ansi-terminal, repline, table-layout

Dependency ranges changed: split

API changes (from Hackage documentation)

+ Algorithm.EqSat.Egraph: getBestFitness :: forall (m :: Type -> Type). Monad m => EGraphST m (Maybe Double)
+ Algorithm.EqSat.Egraph: getDL :: forall (m :: Type -> Type). Monad m => EClassId -> EGraphST m (Maybe Double)
+ Algorithm.EqSat.Egraph: getFitness :: forall (m :: Type -> Type). Monad m => EClassId -> EGraphST m (Maybe Double)
+ Algorithm.EqSat.Egraph: getSize :: forall (m :: Type -> Type). Monad m => EClassId -> EGraphST m Int
+ Algorithm.EqSat.Egraph: getTheta :: forall (m :: Type -> Type). Monad m => EClassId -> EGraphST m [PVector]
+ Algorithm.EqSat.Egraph: isSizeOf :: (Int -> Bool) -> EClass -> Bool
+ Algorithm.EqSat.SearchSR: checkToken :: (EClassId -> ENode) -> ENode -> StateT EGraph (StateT StdGen IO) Bool
+ Algorithm.EqSat.SearchSR: doesExist :: ENode -> RndEGraph Bool
+ Algorithm.EqSat.SearchSR: doesNotExist :: ENode -> RndEGraph Bool
+ Algorithm.EqSat.SearchSR: doesNotExistGens :: [Maybe (EClassId -> ENode)] -> ENode -> RndEGraph Bool
+ Algorithm.EqSat.SearchSR: evaluateRndUnevaluated :: (Fix SRTree -> StateT EGraph (StateT StdGen IO) (Double, [PVector])) -> StateT EGraph (StateT StdGen IO) Key
+ Algorithm.EqSat.SearchSR: evaluateUnevaluated :: forall {m :: Type -> Type}. Monad m => (Fix SRTree -> StateT EGraph m (Double, [PVector])) -> StateT EGraph m ()
+ Algorithm.EqSat.SearchSR: fitnessFun :: Int -> Distribution -> DataSet -> DataSet -> Fix SRTree -> PVector -> (Double, PVector)
+ Algorithm.EqSat.SearchSR: fitnessFunRep :: Int -> Int -> Distribution -> DataSet -> DataSet -> Fix SRTree -> RndEGraph (Double, PVector)
+ Algorithm.EqSat.SearchSR: fitnessMV :: Bool -> Int -> Int -> Distribution -> [(DataSet, DataSet)] -> Fix SRTree -> RndEGraph (Double, [PVector])
+ Algorithm.EqSat.SearchSR: getBestExprWithSize :: forall {m :: Type -> Type}. Monad m => Int -> StateT EGraph m [(EClassId, Maybe Double)]
+ Algorithm.EqSat.SearchSR: getParetoDLEcsUpTo :: forall {m :: Type -> Type}. Monad m => Int -> Int -> StateT EGraph m [EClassId]
+ Algorithm.EqSat.SearchSR: getParetoEcsUpTo :: forall {m :: Type -> Type}. Monad m => Int -> Int -> StateT EGraph m [EClassId]
+ Algorithm.EqSat.SearchSR: insertExpr :: Fix SRTree -> (Fix SRTree -> RndEGraph (Double, [PVector])) -> RndEGraph EClassId
+ Algorithm.EqSat.SearchSR: insertRndExpr :: Int -> Rng (Fix SRTree) -> Rng (SRTree ()) -> StateT EGraph (StateT StdGen IO) EClassId
+ Algorithm.EqSat.SearchSR: io :: IO a -> RndEGraph a
+ Algorithm.EqSat.SearchSR: myCost :: SRTree Int -> Int
+ Algorithm.EqSat.SearchSR: paretoFront :: (Fix SRTree -> StateT EGraph (StateT StdGen IO) (Double, [PVector])) -> Int -> (Int -> EClassId -> StateT EGraph (StateT StdGen IO) [String]) -> RndEGraph [[String]]
+ Algorithm.EqSat.SearchSR: pickRndSubTree :: RndEGraph (Maybe EClassId)
+ Algorithm.EqSat.SearchSR: printBest :: forall {m :: Type -> Type} {t} {p} {b}. (Monad m, Num t) => p -> (t -> EClassId -> StateT EGraph m b) -> StateT EGraph m b
+ Algorithm.EqSat.SearchSR: refit :: forall {m :: Type -> Type}. Monad m => (Fix SRTree -> StateT EGraph m (Double, [PVector])) -> EClassId -> StateT EGraph m ()
+ Algorithm.EqSat.SearchSR: rnd :: StateT StdGen IO a -> RndEGraph a
+ Algorithm.EqSat.SearchSR: type RndEGraph a = EGraphST StateT StdGen IO a
+ Algorithm.EqSat.SearchSR: updateIfNothing :: forall {m :: Type -> Type}. Monad m => (Fix SRTree -> StateT EGraph m (Double, [PVector])) -> EClassId -> StateT EGraph m Bool
+ Algorithm.EqSat.SearchSR: while :: Monad f => (t -> Bool) -> t -> (t -> f t) -> f t
+ Data.SRTree.Datasets: getX :: DataSet -> SRMatrix
+ Data.SRTree.Datasets: loadTrainingOnly :: FilePath -> Bool -> IO (SRMatrix, PVector, Maybe PVector)
+ Data.SRTree.Datasets: splitData :: DataSet -> Int -> State StdGen (DataSet, DataSet)
+ Data.SRTree.Datasets: type DataSet = (SRMatrix, PVector, Maybe PVector)
+ Data.SRTree.Random: randomFrom :: [a] -> StateT StdGen IO a
+ Data.SRTree.Random: randomRange :: (Ord val, Random val) => (val, val) -> StateT StdGen IO val
+ Data.SRTree.Random: randomTreeTemplate :: HasEverything p => Int -> RndTree p
+ Data.SRTree.Random: randomVal :: Rng Double
+ Data.SRTree.Random: randomVec :: Int -> Rng PVector
+ Data.SRTree.Random: toss :: StateT StdGen IO Bool
+ Data.SRTree.Random: tossBiased :: Double -> Rng Bool
+ Data.SRTree.Random: type Rng a = StateT StdGen IO a
+ Text.ParseSR: parseNonTerms :: String -> [SRTree ()]
- Data.SRTree.Random: randomTree :: HasEverything p => Int -> RndTree p
+ Data.SRTree.Random: randomTree :: Int -> Int -> Int -> Rng (Fix SRTree) -> Rng (SRTree ()) -> Bool -> Rng (Fix SRTree)

Files

ChangeLog.md view
@@ -1,5 +1,16 @@ # Changelog for srtree +## 2.0.1.4++- Added `loadTrainingOnly`, `splitData`, and `loadX` to `Data.SRTree.Datasets`+- Added `getFitness`, `getTheta`, `getSize`, `isSizeOf`, `getBestFitness` to `Algorithm.EqSat.Egraph`+- Added `parseNonTerms` to `Text.ParseSR` +- Added module `Algorithm.EqSat.SearchSR` with support functions for SR algorithms with EqSat++## 2.0.1.3++- Fix compatibility with stackage nightly + ## 2.0.1.2  - Fix bug where the parameters were printed as `t[:,ix]` instead of `t[ix]` in `showPython`@@ -16,7 +27,7 @@  ## 2.0.1.0 -- Support to Multiview Symbolic Regression in eggp and EASTER.+- Support to Multiview Symbolic Regression in eggp and symregg. - Support to `--number-params` argument that limits the maximum number of parameters and allow repated parameters in an expression.  ## 2.0.0.4
− apps/eggp/Main.hs
@@ -1,515 +0,0 @@-{-# LANGUAGE  BlockArguments #-}-{-# LANGUAGE  TupleSections #-}-{-# LANGUAGE  MultiWayIf #-}-{-# LANGUAGE  OverloadedStrings #-}-{-# LANGUAGE  BangPatterns #-}-{-# LANGUAGE  TypeSynonymInstances, FlexibleInstances #-}--module Main where --import Algorithm.EqSat.Egraph-import Algorithm.EqSat.Simplify-import Algorithm.EqSat.Build-import Algorithm.EqSat.Queries-import Algorithm.EqSat.Info-import Algorithm.EqSat.DB-import Algorithm.SRTree.Likelihoods-import Algorithm.SRTree.ModelSelection-import Algorithm.SRTree.Opt-import Control.Lens (element, makeLenses, over, (&), (+~), (-~), (.~), (^.))-import Control.Monad (foldM, forM_, forM, when, unless, filterM, (>=>), replicateM, replicateM_)-import Control.Monad.State.Strict-import qualified Data.IntMap.Strict as IM-import qualified Data.Map.Strict as Map-import Data.Massiv.Array as MA hiding (forM_, forM)-import Data.Maybe (fromJust, isNothing, isJust)-import Data.SRTree-import Data.SRTree.Datasets-import Data.SRTree.Eval-import Data.SRTree.Random (randomTree)-import Data.SRTree.Print-import Options.Applicative as Opt hiding (Const)-import Random-import System.Random-import qualified Data.HashSet as Set-import Data.List ( sort, maximumBy, intercalate, sortOn, intersperse, nub )-import Data.IntSet (IntSet)-import qualified Data.IntSet as IntSet-import qualified Data.Sequence as FingerTree-import Data.Function ( on )-import qualified Data.Foldable as Foldable-import qualified Data.IntMap as IntMap-import List.Shuffle ( shuffle )-import Algorithm.SRTree.NonlinearOpt-import Data.Binary ( encode, decode )-import qualified Data.ByteString.Lazy as BS--import Debug.Trace-import Algorithm.EqSat (runEqSat,applySingleMergeOnlyEqSat)--import GHC.IO (unsafePerformIO)-import Control.Scheduler -import Control.Monad.IO.Unlift-import Data.SRTree (convertProtectedOps)--import Util--egraphGP :: [(DataSet, DataSet)] -> [DataSet] -> Args -> StateT EGraph (StateT StdGen IO) ()-egraphGP dataTrainVals dataTests args = do-  when ((not.null) (_loadFrom args)) $ (io $ BS.readFile (_loadFrom args)) >>= \eg -> put (decode eg)--  pop <- replicateM (_nPop args) $ do ec <- insertRndExpr (_maxSize args) rndTerm rndNonTerm >>= canonical-                                      updateIfNothing fitFun ec-                                      pure ec-  insertTerms-  --runEqSat myCost rewritesParams 1-  --cleanDB-  evaluateUnevaluated fitFun-  pop' <- Prelude.mapM canonical pop-  when (_trace args) $ printPop pop'-  let m = (_nPop args) `div` (_maxSize args)--  finalPop <- iterateFor (_gens args) pop' $ \it ps' -> do-    -- ps <- Prelude.mapM canonical ps'-    --let chunks = 1-    --    (parts, r) = _nPop args `divMod` chunks -- chunks of 50-    --    genChunk = Prelude.mapM canonical ps' >>= \ps -> replicateM chunks (tournament ps) >>= Prelude.mapM combine-    --    genPart  = genChunk >>= \chunk -> (runEqSat myCost rewritesSimple 1 >> cleanDB) >> pure chunk-    --newPop' <- (<>) <$> (concat <$> (replicateM parts genPart)) <*> (concat <$> replicateM r genPart)-    --parents <- replicateM (_nPop args - if (_moo args) then (_maxSize args) else 0) (tournament ps)-    --newPop' <- Prelude.mapM combine parents-    --runEqSat myCost rewritesSimple 1 --applySingleMergeOnlyEqSat myCost rewritesSimple-    --cleanDB-    newPop' <- replicateM (_nPop args) (evolve ps')-    --applySingleMergeOnlyEqSat myCost rewritesParams >> cleanDB-    --newPop' <- Prelude.mapM (\eId -> canonical eId >>= \eId' -> (updateIfNothing fitFun eId' >> pure eId')) newPop''-    --Prelude.mapM_ (updateIfNothing fitFun) newPop'--    totSz <- gets (Map.size . _eNodeToEClass) -- (IntMap.size . _eClass)-    let full = totSz > max maxMem (_nPop args)-    --io . print $ totSz-    when full (cleanEGraph >> cleanDB)--    newPop <- if (_moo args)-                then do-                        let n_paretos = (_nPop args) `div` (_maxSize args)-                        pareto <- concat <$> (forM [1 .. _maxSize args] $ \n -> getTopFitEClassWithSize n 2)-                        let remainder = _nPop args - length pareto-                        lft <- if full-                                  then getTopFitEClassThat remainder (const True)-                                  else pure $ Prelude.take remainder newPop'-                        Prelude.mapM canonical (pareto <> lft)-                else if full-                       then getTopFitEClassThat (_nPop args) (const True)-                       else Prelude.mapM canonical newPop'-    when (_trace args) $ printPop newPop-    pure newPop--  io $ putStrLn "id,Expression,theta,size,MSE_train,MSE_val,MSE_test,R2_train,R2_val,R2_test,nll_train,nll_val,nll_test,mdl_train,mdl_val,mdl_test"-  if (_printPareto args)-    then paretoFront fitFun (_maxSize args) printExpr-    else printBest fitFun printExpr-  when ((not.null) (_dumpTo args)) $ get >>= (io . BS.writeFile (_dumpTo args) . encode )-  where-    maxSize = (_maxSize args)-    maxMem = 2000000 -- running 1 iter of eqsat for each new individual will consume ~3GB-    fitFun = fitnessMV shouldReparam (_optRepeat args) (_optIter args) (_distribution args) dataTrainVals-    nonTerms   = parseNonTerms (_nonterminals args)-    (Sz2 _ nFeats) = MA.size (getX .fst . head $ dataTrainVals)-    params         = if _nParams args == -1 then [param 0] else Prelude.map param [0 .. _nParams args - 1]-    shouldReparam  = _nParams args == -1-    relabel        = if shouldReparam then relabelParams else relabelParamsOrder-    terms          = if _distribution args == ROXY-                          then (var 0 : params)-                          else [var ix | ix <- [0 .. nFeats-1]] -- <> params-    uniNonTerms = [t | t <- nonTerms, isUni t]-    binNonTerms = [t | t <- nonTerms, isBin t]-    isUni (Uni _ _)   = True-    isUni _           = False-    isBin (Bin _ _ _) = True-    isBin _           = False--    -- TODO: merge two or more egraphs-    cleanEGraph = do let nParetos = 10 -- (maxMem `div` 5) `div` _maxSize args-                     io . putStrLn $ "cleaning"-                     pareto <- (concat <$> (forM [1 .. _maxSize args] $ \n -> getTopFitEClassWithSize n nParetos))-                                 >>= Prelude.mapM canonical-                     infos  <- forM pareto (\c -> gets (_info . (IntMap.! c) . _eClass))-                     exprs  <- forM pareto getBestExpr-                     put emptyGraph-                     newIds <- fromTrees myCost $ Prelude.map relabel exprs-                     forM_ (Prelude.zip newIds (Prelude.reverse infos)) $ \(eId, info) ->-                         insertFitness eId (fromJust $ _fitness info) (_theta info)--    rndTerm    = do coin <- toss-                    if coin then Random.randomFrom terms else Random.randomFrom params-    rndNonTerm = Random.randomFrom nonTerms--    refitChanged = do ids <- gets (_refits . _eDB) >>= Prelude.mapM canonical . Set.toList >>= pure . nub-                      modify' $ over (eDB . refits) (const Set.empty)-                      forM_ ids $ \ec -> do t <- getBestExpr ec-                                            (f, p) <- fitFun t-                                            insertFitness ec f p--    iterateFor 0 xs f = pure xs-    iterateFor n xs f = do xs' <- f n xs-                           iterateFor (n-1) xs' f--    evolve xs' = do xs <- Prelude.mapM canonical xs'-                    parents <- tournament xs-                    offspring <- combine parents-                    --applySingleMergeOnlyEqSat myCost rewritesParams >> cleanDB-                    if _nParams args == 0-                       then runEqSat myCost rewritesWithConstant 1 >> cleanDB >> refitChanged-                       else runEqSat myCost rewritesParams 1 >> cleanDB >> refitChanged-                    canonical offspring >>= updateIfNothing fitFun-                    canonical offspring-                    --pure offspring--    tournament xs = do p1 <- applyTournament xs >>= canonical-                       p2 <- applyTournament xs >>= canonical-                       pure (p1, p2)--    applyTournament :: [EClassId] -> RndEGraph EClassId-    applyTournament xs = do challengers <- replicateM (_nTournament args) (rnd $ randomFrom xs) >>= traverse canonical-                            fits <- Prelude.map fromJust <$> Prelude.mapM getFitness challengers-                            pure . snd . maximumBy (compare `on` fst) $ Prelude.zip fits challengers--    combine (p1, p2) = (crossover p1 p2 >>= mutate) >>= canonical--    crossover p1 p2 = do sz <- getSize p1-                         coin <- rnd $ tossBiased (_pc args)-                         if sz == 1 || not coin-                            then rnd (randomFrom [p1, p2])-                            else do pos <- rnd $ randomRange (1, sz-1)-                                    cands <- getAllSubClasses p2-                                    tree <- getSubtree pos 0 Nothing [] cands p1-                                    fromTree myCost (relabel tree) >>= canonical--    getSubtree :: Int -> Int -> Maybe (EClassId -> ENode) -> [Maybe (EClassId -> ENode)] -> [EClassId] -> EClassId -> RndEGraph (Fix SRTree)-    getSubtree 0 sz (Just parent) mGrandParents cands p' = do-      p <- canonical p'-      candidates' <- filterM (\c -> (<maxSize-sz) <$> getSize c) cands-      candidates  <- filterM (\c -> doesNotExistGens mGrandParents (parent c)) candidates'-                       >>= traverse canonical-      if null candidates-         then getBestExpr p-         else do subtree <- rnd (randomFrom candidates)-                 getBestExpr subtree-    getSubtree pos sz parent mGrandParents cands p' = do-      p <- canonical p'-      root <- getBestENode p >>= canonize-      case root of-        Param ix -> pure . Fix $ Param ix-        Const x  -> pure . Fix $ Const x-        Var   ix -> pure . Fix $ Var ix-        Uni f t' -> do t <- canonical t'-                       (Fix . Uni f) <$> getSubtree (pos-1) (sz+1) (Just $ Uni f) (parent:mGrandParents) cands t-        Bin op l'' r'' ->-                      do l <- canonical l''-                         r <- canonical r''-                         szLft <- getSize l-                         szRgt <- getSize r-                         if szLft < pos-                           then do l' <- getBestExpr l-                                   r' <- getSubtree (pos-szLft-1) (sz+szLft+1) (Just $ Bin op l) (parent:mGrandParents) cands r-                                   pure . Fix $ Bin op l' r'-                           else do l' <- getSubtree (pos-1) (sz+szRgt+1) (Just (\t -> Bin op t r)) (parent:mGrandParents) cands l-                                   r' <- getBestExpr r-                                   pure . Fix $ Bin op l' r'--    getAllSubClasses p' = do-      p  <- canonical p'-      en <- getBestENode p-      case en of-        Bin _ l r -> do ls <- getAllSubClasses l-                        rs <- getAllSubClasses r-                        pure (p : (ls <> rs))-        Uni _ t   -> (p:) <$> getAllSubClasses t-        _         -> pure [p]--    mutate p = do sz <- getSize p-                  coin <- rnd $ tossBiased (_pm args)-                  if coin-                     then do pos <- rnd $ randomRange (0, sz-1)-                             tree <- mutAt pos maxSize Nothing p-                             fromTree myCost (relabel tree) >>= canonical-                     else pure p--    peel :: Fix SRTree -> SRTree ()-    peel (Fix (Bin op l r)) = Bin op () ()-    peel (Fix (Uni f t)) = Uni f ()-    peel (Fix (Param ix)) = Param ix-    peel (Fix (Var ix)) = Var ix-    peel (Fix (Const x)) = Const x--    mutAt :: Int -> Int -> Maybe (EClassId -> ENode) -> EClassId -> RndEGraph (Fix SRTree)-    mutAt 0 sizeLeft Nothing       _ = (insertRndExpr sizeLeft rndTerm rndNonTerm >>= canonical) >>= getBestExpr -- we chose to mutate the root-    mutAt 0 1        _             _ = rnd $ randomFrom terms -- we don't have size left-    mutAt 0 sizeLeft (Just parent) _ = do -- we reached the mutation place-      ec    <- insertRndExpr sizeLeft rndTerm rndNonTerm >>= canonical -- create a random expression with the size limit-      (Fix tree) <- getBestExpr ec           ---      root  <- getBestENode ec-      exist <- canonize (parent ec) >>= doesExist-      if exist-         -- the expression `parent ec` already exists, try to fix-         then do let children = childrenOf root-                 candidates <- case length children of-                                0  -> filterM (checkToken parent . (replaceChildren children)) (Prelude.map peel terms)-                                1 -> filterM (checkToken parent . (replaceChildren children)) uniNonTerms-                                2 -> filterM (checkToken parent . (replaceChildren children)) binNonTerms-                 if null candidates-                     then pure $ Fix tree -- there's no candidate, so we failed and admit defeat-                     else do newToken <- rnd (randomFrom candidates)-                             pure . Fix $ replaceChildren (childrenOf tree) newToken--         else pure . Fix $ tree--    mutAt pos sizeLeft parent p' = do-        p <- canonical p'-        root <- getBestENode p >>= canonize-        case root of-          Param ix -> pure . Fix $ Param ix-          Const x  -> pure . Fix $ Const x-          Var   ix -> pure . Fix $ Var ix-          Uni f t'  -> canonical t' >>= \t -> (Fix . Uni f) <$> mutAt (pos-1) (sizeLeft-1) (Just $ Uni f) t-          Bin op ln rn -> do l <- canonical ln-                             r <- canonical rn-                             szLft <- getSize l-                             szRgt <- getSize r-                             if szLft < pos-                                then do l' <- getBestExpr l-                                        r' <- mutAt (pos-szLft-1) (sizeLeft-szLft-1) (Just $ Bin op l) r-                                        pure . Fix $ Bin op l' r'-                                else do l' <- mutAt (pos-1) (sizeLeft-szRgt-1) (Just (\t -> Bin op t r)) l-                                        r' <- getBestExpr r-                                        pure . Fix $ Bin op l' r'--    checkToken parent en' = do en <- canonize en'-                               mEc <- gets ((Map.!? en) . _eNodeToEClass)-                               case mEc of-                                    Nothing -> pure True-                                    Just ec -> do ec' <- canonical ec-                                                  ec'' <- canonize (parent ec')-                                                  not <$> doesExist ec''-    doesExist, doesNotExist :: ENode -> RndEGraph Bool-    doesExist en = gets ((Map.member en) . _eNodeToEClass)-    doesNotExist en = gets ((Map.notMember en) . _eNodeToEClass)--    doesNotExistGens :: [Maybe (EClassId -> ENode)] -> ENode -> RndEGraph Bool-    doesNotExistGens []              en = gets ((Map.notMember en) . _eNodeToEClass)-    doesNotExistGens (mGrand:grands) en = do b <- gets ((Map.notMember en) . _eNodeToEClass)-                                             if b-                                               then pure True-                                               else case mGrand of-                                                    Nothing -> pure False-                                                    Just gf -> do ec  <- gets ((Map.! en) . _eNodeToEClass)-                                                                  en' <- canonize (gf ec)-                                                                  doesNotExistGens grands en'--    printExpr :: Int -> EClassId -> RndEGraph ()-    printExpr ix ec = do-        thetas' <- gets (_theta . _info . (IM.! ec) . _eClass)-        bestExpr <- (if _simplify args then simplifyEqSatDefault else id) <$> getBestExpr ec-        let nParams = countParamsUniq bestExpr-            fromSz (MA.Sz x) = x -            nThetas  = Prelude.map (fromSz . MA.size) thetas'-        (_, thetas) <- if Prelude.any (/=nParams) nThetas || _simplify args-                        then fitFun bestExpr-                        else pure (1.0, thetas')--        forM_ (Prelude.zip3 dataTrainVals dataTests thetas) $ \((dataTrain, dataVal), dataTest, theta) -> do-            let (x, y, mYErr) = dataTrain-                (x_val, y_val, mYErr_val) = dataVal-                (x_te, y_te, mYErr_te) = dataTest-                distribution = _distribution args-                best'     = if shouldReparam then relabelParams bestExpr else relabelParamsOrder bestExpr-                expr      = paramsToConst (MA.toList theta) best'-                mse_train = mse x y best' theta-                mse_val   = mse x_val y_val best' theta-                mse_te    = mse x_te y_te best' theta-                r2_train  = r2 x y best' theta-                r2_val    = r2 x_val y_val best' theta-                r2_te     = r2 x_te y_te best' theta-                nll_train  = nll distribution mYErr x y best' theta-                nll_val    = nll distribution mYErr_val x_val y_val best' theta-                nll_te     = nll distribution mYErr_te x_te y_te best' theta-                mdl_train  = mdl distribution mYErr x y theta best'-                mdl_val    = mdl distribution mYErr_val x_val y_val theta best'-                mdl_te     = mdl distribution mYErr_te x_te y_te theta best'-                vals       = intercalate ","-                           $ Prelude.map show [mse_train, mse_val, mse_te-                                              , r2_train, r2_val, r2_te-                                              , nll_train, nll_val, nll_te-                                              , mdl_train, mdl_val, mdl_te]-                thetaStr   = intercalate ";" $ Prelude.map show (MA.toList theta)-                showFun    = if _numpy args then "\"" <> showPython best' <> "\"" else showExpr expr-            io . putStrLn $ show ix <> "," <> showFun <> ","-                          <> thetaStr <> "," <> show (countNodes $ convertProtectedOps expr)-                          <> "," <> vals--    printPop pop = forM_ pop $ \ecN'-> do-            ecN'' <- canonical ecN'-            _tree <- getBestExpr ecN''-            fi <- fromJust <$> getFitness ecN''-            thetas <- getTheta ecN''-            let thetaStr   = intercalate "_" $ Prelude.map (intercalate ";" . Prelude.map show . MA.toList) thetas-                tree = if _simplify args then simplifyEqSatDefault _tree else _tree-                showFun = if _numpy args then showPython else showExpr-            io . putStrLn $ showFun tree <> "," <> thetaStr <> "," <> show fi-            pure ()--    insertTerms =-        forM terms $ \t -> do fromTree myCost t >>= canonical--data Args = Args-  { _dataset      :: String,-    _testData     :: String,-    _gens         :: Int,-    _maxSize      :: Int,-    _split        :: Int,-    _printPareto  :: Bool,-    _trace        :: Bool,-    _distribution :: Distribution,-    _optIter      :: Int,-    _optRepeat    :: Int,-    _nParams      :: Int,-    _nPop         :: Int,-    _nTournament  :: Int,-    _pc           :: Double,-    _pm           :: Double,-    _nonterminals :: String,-    _dumpTo       :: String,-    _loadFrom     :: String,-    _moo          :: Bool,-    _numpy        :: Bool,-    _simplify     :: Bool-  }-  deriving (Show)---- parser of command line arguments-opt :: Parser Args-opt = Args-   <$> strOption-       ( long "dataset"-       <> short 'd'-       <> metavar "INPUT-FILE"-       <> help "CSV dataset." )-  <*> strOption-       ( long "test"-       <> short 't'-       <> value ""-       <> showDefault-       <> help "test data")-   <*> option auto-      ( long "generations"-      <> short 'g'-      <> metavar "GENS"-      <> showDefault-      <> value 100-      <> help "Number of generations." )-  <*> option auto-       ( long "maxSize"-       <> short 's'-       <> help "max-size." )-  <*> option auto-       ( long "split"-       <> short 'k'-       <> value 1 -       <> showDefault-       <> help "k-split ratio training-validation")-  <*> switch-       ( long "print-pareto"-       <> help "print Pareto front instead of best found expression")-  <*> switch-       ( long "trace"-       <> help "print all evaluated expressions.")-  <*> option auto-       ( long "loss"-       <> value MSE-       <> showDefault-       <> help "loss function: MSE, Gaussian, Poisson, Bernoulli.")-  <*> option auto-       ( long "opt-iter"-       <> value 30-       <> showDefault-       <> help "number of iterations in parameter optimization.")-  <*> option auto-       ( long "opt-retries"-       <> value 1-       <> showDefault-       <> help "number of retries of parameter fitting.")-  <*> option auto-       ( long "number-params"-       <> value (-1)-       <> showDefault-       <> help "maximum number of parameters in the model. If this argument is absent, the number is bounded by the maximum size of the expression and there will be no repeated parameter.")-  <*> option auto-       ( long "nPop"-       <> value 100-       <> showDefault-       <> help "population size (Default: 100).")-  <*> option auto-       ( long "tournament-size"-       <> value 2-       <> showDefault-       <> help "tournament size.")-  <*> option auto-       ( long "pc"-       <> value 1.0-       <> showDefault-       <> help "probability of crossover.")-  <*> option auto-       ( long "pm"-       <> value 0.3-       <> showDefault-       <> help "probability of mutation.")-  <*> strOption-       ( long "non-terminals"-       <> value "Add,Sub,Mul,Div,PowerAbs,Recip"-       <> showDefault-       <> help "set of non-terminals to use in the search."-       )-  <*> strOption-       ( long "dump-to"-       <> value ""-       <> showDefault-       <> help "dump final e-graph to a file."-       )-  <*> strOption-       ( long "load-from"-       <> value ""-       <> showDefault-       <> help "load initial e-graph from a file."-       )-  <*> switch-       ( long "moo"-       <> help "replace the current population with the pareto front instead of replacing it with the generated children."-       )-  <*> switch-       ( long "to-numpy"-       <> help "outputs the expressions using a numpy format."-       )-  <*> switch-       ( long "simplify"-       <> help "simplify the expressions before displaying them."-       )-main :: IO ()-main = do-  args <- execParser opts-  g    <- getStdGen-  let datasets = words (_dataset args)-  dataTrains' <- Prelude.mapM (flip loadTrainingOnly True) datasets -- load all datasets -  dataTests   <- if null (_testData args)-                  then pure dataTrains'-                  else Prelude.mapM (flip loadTrainingOnly True) $ words (_testData args)--  let (dataTrainVals, g') = runState (Prelude.mapM (`splitData` (_split args)) dataTrains') g-      alg = evalStateT (egraphGP dataTrainVals dataTests args) emptyGraph-  evalStateT alg g'-  where-    opts = Opt.info (opt <**> helper)-            ( fullDesc <> progDesc "An implementation of GP with modified crossover and mutation\-                                   \ operators designed to exploit equality saturation and e-graphs.\-                                   \ https://arxiv.org/abs/2501.17848\n"-           <> header "eggp - E-graph Genetic Programming for Symbolic Regression." )
− apps/eggp/Random.hs
@@ -1,54 +0,0 @@-module Random where --import System.Random -import Control.Monad.State.Strict-import Control.Monad-import Data.SRTree -import Data.SRTree.Eval-import Data.Massiv.Array as MA--type Rng a = StateT StdGen IO a --toss :: Rng Bool-toss = state random-{-# INLINE toss #-}--tossBiased :: Double -> Rng Bool-tossBiased p = do r <- state random -                  pure (r < p)--randomVal :: Rng Double-randomVal = state random--randomRange :: (Ord val, Random val) => (val, val) -> Rng val-randomRange rng = state (randomR rng)-{-# INLINE randomRange #-}--randomFrom :: [a] -> Rng a-randomFrom funs = do n <- randomRange (0, length funs - 1)-                     pure $ funs !! n-{-# INLINE randomFrom #-}--randomVec :: Int -> Rng PVector-randomVec n = MA.fromList compMode <$> replicateM n (randomRange (-1, 1))--randomTree :: Int -> Int -> Int -> Rng (Fix SRTree) -> Rng (SRTree ()) -> Bool -> Rng (Fix SRTree)-randomTree minDepth maxDepth maxSize genTerm genNonTerm grow -  | noSpaceLeft = genTerm-  | needNonTerm = genRecursion -  | otherwise   = do r <- toss-                     if r -                       then genTerm -                       else genRecursion-  where -    noSpaceLeft = maxDepth <= 1 || maxSize <= 2-    needNonTerm = (minDepth >= 0 || (maxDepth > 2 && not grow)) -- && maxSize > 2--    genRecursion = do -        node <- genNonTerm-        case node of -          Uni f _    -> Fix . Uni f <$> randomTree (minDepth - 1) (maxDepth - 1) (maxSize - 1) genTerm genNonTerm grow -          Bin op _ _ -> do l <- randomTree (minDepth - 1) (maxDepth - 1) (if grow then maxSize - 2 else maxSize `div` 2) genTerm genNonTerm grow-                           r <- randomTree (minDepth - 1) (maxDepth - 1) (maxSize - 1 - countNodes l) genTerm genNonTerm grow -                           pure . Fix  $ Bin op l r-{-# INLINE randomTree #-}
− apps/eggp/Util.hs
@@ -1,266 +0,0 @@-{-# LANGUAGE  BlockArguments #-}-{-# LANGUAGE  TupleSections #-}--module Util where--import qualified Data.Map.Strict as Map-import Data.Massiv.Array as MA hiding (forM_, forM)-import Data.SRTree-import Data.SRTree.Eval-import Algorithm.SRTree.Opt-import Algorithm.EqSat.Egraph-import Algorithm.EqSat.Build-import Algorithm.EqSat.Info--import Algorithm.SRTree.NonlinearOpt-import System.Random-import Random-import Algorithm.SRTree.Likelihoods-import Data.SRTree.Print---import Algorithm.SRTree.ModelSelection---import Algorithm.SRTree.Opt-import qualified Data.IntMap.Strict as IM-import Control.Monad.State.Strict-import Control.Monad ( when, replicateM, forM, forM_ )-import Data.Maybe ( fromJust )-import Data.List ( maximumBy )-import Data.Function ( on )-import List.Shuffle ( shuffle )-import Data.List.Split ( splitOn )-import Data.Char ( toLower )-import qualified Data.IntSet as IntSet-import Data.SRTree.Datasets-import Algorithm.EqSat.Queries--import Debug.Trace--type RndEGraph a = EGraphST (StateT StdGen IO) a-type DataSet = (SRMatrix, PVector, Maybe PVector)--csvHeader :: String-csvHeader = "id,Expression,theta,size,MSE_train,MSE_val,MSE_test,R2_train,R2_val,R2_test,nll_train,nll_val,nll_test,mdl_train,mdl_val,mdl_test"--io :: IO a -> RndEGraph a-io = lift . lift-{-# INLINE io #-}-rnd :: StateT StdGen IO a -> RndEGraph a-rnd = lift-{-# INLINE rnd #-}--myCost :: SRTree Int -> Int-myCost (Var _)     = 1-myCost (Const _)   = 1-myCost (Param _)   = 1-myCost (Bin _ l r) = 2 + l + r-myCost (Uni _ t)   = 3 + t--while :: Monad f => (t -> Bool) -> t -> (t -> f t) -> f ()-while p arg prog = do when (p arg) do arg' <- prog arg-                                      while p arg' prog--fitnessFun :: Int -> Distribution -> DataSet -> DataSet -> Fix SRTree -> PVector -> (Double, PVector)-fitnessFun nIter distribution (x, y, mYErr) (x_val, y_val, mYErr_val) tree thetaOrig =-  if isNaN val -- || isNaN tr-    then (-(1/0), theta) -- infinity-    else (val, theta)-  where-    --tree          = relabelParams _tree-    nParams       = countParamsUniq tree + if distribution == ROXY then 3 else if distribution == Gaussian then 1 else 0-    (theta, _, _) = minimizeNLL' VAR1 distribution mYErr nIter x y tree thetaOrig-    evalF a b c   = negate $ nll distribution c a b tree $ if nParams == 0 then thetaOrig else theta-    --tr            = evalF x y mYErr-    val           = evalF x_val y_val mYErr_val----{-# INLINE fitnessFun #-}--fitnessFunRep :: Int -> Int -> Distribution -> DataSet -> DataSet -> Fix SRTree -> RndEGraph (Double, PVector)-fitnessFunRep nRep nIter distribution dataTrain dataVal tree = do-    let nParams = countParamsUniq tree + if distribution == ROXY then 3 else if distribution == Gaussian then 1 else 0-    thetaOrigs <- replicateM nRep (rnd $ randomVec nParams)-    let fits = maximumBy (compare `on` fst) $ Prelude.map (fitnessFun nIter distribution dataTrain dataVal tree) thetaOrigs-    pure fits---{-# INLINE fitnessFunRep #-}---fitnessMV :: Bool -> Int -> Int -> Distribution -> [(DataSet, DataSet)] -> Fix SRTree -> RndEGraph (Double, [PVector])-fitnessMV shouldReparam nRep nIter distribution dataTrainsVals _tree = do-  let tree = if shouldReparam then relabelParams _tree else relabelParamsOrder _tree-  response <- forM dataTrainsVals $ \(dt, dv) -> fitnessFunRep nRep nIter distribution dt dv tree-  pure (minimum (Prelude.map fst response), Prelude.map snd response)---- helper query functions--- TODO: move to egraph lib-getFitness :: EClassId -> RndEGraph (Maybe Double)-getFitness c = gets (_fitness . _info . (IM.! c) . _eClass)-{-# INLINE getFitness #-}-getTheta :: EClassId -> RndEGraph ([PVector])-getTheta c = gets (_theta . _info . (IM.! c) . _eClass)-{-# INLINE getTheta #-}-getSize :: EClassId -> RndEGraph Int-getSize c = gets (_size . _info . (IM.! c) . _eClass)-{-# INLINE getSize #-}-isSizeOf :: (Int -> Bool) -> EClass -> Bool-isSizeOf p = p . _size . _info-{-# INLINE isSizeOf #-}--getBestFitness :: RndEGraph (Maybe Double)-getBestFitness = do-    bec <- (gets (snd . getGreatest . _fitRangeDB . _eDB) >>= canonical)-    gets (_fitness . _info . (IM.! bec) . _eClass)---- TODO: move to dataset lib-chunksOf :: Int -> [e] -> [[e]]-chunksOf i ls = Prelude.map (Prelude.take i) (build (splitter ls))- where-  splitter :: [e] -> ([e] -> a -> a) -> a -> a-  splitter [] _ n = n-  splitter l c n = l `c` splitter (Prelude.drop i l) c n-  build :: ((a -> [a] -> [a]) -> [a] -> [a]) -> [a]-  build g = g (:) []--splitData :: DataSet ->Int -> State StdGen (DataSet, DataSet)-splitData (x, y, mYErr) k = do-  if k == 1-    then pure ((x, y, mYErr), (x, y, mYErr))-    else do-      ixs' <- (state . shuffle) [0 .. sz-1]-      let ixs = chunksOf k ixs'--      let (x_tr, x_te) = getX ixs x-          (y_tr, y_te) = getY ixs y-          mY = fmap (getY ixs) mYErr-          (y_err_tr, y_err_te) = (fmap fst mY, fmap snd mY)-      pure ((x_tr, y_tr, y_err_tr), (x_te, y_te, y_err_te))-  where-    (MA.Sz sz) = MA.size y-    comp_x     = MA.getComp x-    comp_y     = MA.getComp y--    getX :: [[Int]] -> SRMatrix -> (SRMatrix, SRMatrix)-    getX ixs xs' = let xs = MA.toLists xs' :: [MA.ListItem MA.Ix2 Double]-                    in ( MA.fromLists' comp_x [xs !! ix | ixs_i <- ixs, ix <- Prelude.tail ixs_i]-                       , MA.fromLists' comp_x [xs !! ix | ixs_i <- ixs, let ix = Prelude.head ixs_i]-                       )-    getY :: [[Int]] -> PVector -> (PVector, PVector)-    getY ixs ys  = ( MA.fromList comp_y [ys MA.! ix | ixs_i <- ixs, ix <- Prelude.tail ixs_i]-                   , MA.fromList comp_y [ys MA.! ix | ixs_i <- ixs, let ix = Prelude.head ixs_i]-                   )--getTrain :: ((a, b1, c1, d1), (c2, b2), c3, d2) -> (a, b1, c2)-getTrain ((a, b, _, _), (c, _), _, _) = (a,b,c)--getX :: DataSet -> SRMatrix-getX (a, _, _) = a--getTarget :: DataSet -> PVector-getTarget (_, b, _) = b--getError :: DataSet -> Maybe PVector-getError (_, _, c) = c--loadTrainingOnly fname b = getTrain <$> loadDataset fname b--parseNonTerms :: String -> [SRTree ()]-parseNonTerms = Prelude.map toNonTerm . splitOn ","-  where-    binTerms = Map.fromList [ (Prelude.map toLower (show op), op) | op <- [Add .. AQ]]-    uniTerms = Map.fromList [ (Prelude.map toLower (show f), f) | f <- [Abs .. Cube]]-    toNonTerm xs' = let xs = Prelude.map toLower xs'-                    in case binTerms Map.!? xs of-                          Just op -> Bin op () ()-                          Nothing -> case uniTerms Map.!? xs of-                                          Just f -> Uni f ()-                                          Nothing -> error $ "invalid non-terminal " <> show xs---- RndEGraph utils--- fitFun fitnessFunRep rep iter distribution x y mYErr x_val y_val mYErr_val-insertExpr :: Fix SRTree -> (Fix SRTree -> RndEGraph (Double, [PVector])) -> RndEGraph EClassId-insertExpr t fitFun = do-    ecId <- fromTree myCost t >>= canonical-    (f, p) <- fitFun t-    insertFitness ecId f p-    io . putStrLn $ "Best fit global: " <> show f-    pure ecId-  where powabs l r  = Fix (Bin PowerAbs l r)--updateIfNothing fitFun ec = do-      mf <- getFitness ec-      case mf of-        Nothing -> do-          t <- getBestExpr ec-          (f, p) <- fitFun t-          insertFitness ec f p-          pure True-        Just _ -> pure False--pickRndSubTree :: RndEGraph (Maybe EClassId)-pickRndSubTree = do ecIds <- gets (IntSet.toList . _unevaluated . _eDB)-                    if not (null ecIds)-                          then do rndId' <- rnd $ randomFrom ecIds-                                  rndId  <- canonical rndId'-                                  constType <- gets (_consts . _info . (IM.! rndId) . _eClass)-                                  case constType of-                                    NotConst -> pure $ Just rndId-                                    _        -> pure Nothing-                          else pure Nothing--getParetoEcsUpTo n maxSize = concat <$> forM [1..maxSize] (\i -> getTopFitEClassWithSize i n)--getBestExprWithSize n =-        do ec <- getTopFitEClassWithSize n 1 >>= traverse canonical-           if (not (null ec))-            then do-              bestFit <- getFitness $ head ec-              bestP   <- gets (_theta . _info . (IM.! (head ec)) . _eClass)-              pure [(head ec, bestFit)]-            else pure []--insertRndExpr maxSize rndTerm rndNonTerm =-      do grow <- rnd toss-         n <- rnd (randomFrom [if maxSize > 4 then 4 else 1 .. maxSize])-         t <- rnd $ Random.randomTree 3 8 n rndTerm rndNonTerm grow-         fromTree myCost t >>= canonical--refit fitFun ec = do-  t <- getBestExpr ec-  (f, p) <- fitFun t-  insertFitness ec f p----printBest :: (Int -> EClassId -> RndEGraph ()) -> RndEGraph ()-printBest fitFun printExprFun = do-      bec <- gets (snd . getGreatest . _fitRangeDB . _eDB) >>= canonical-      bestFit <- gets (_fitness. _info . (IM.! bec) . _eClass)-      --refit fitFun bec-      --io.print $ "should be " <> show bestFit-      printExprFun 0 bec----paretoFront :: Int -> (Int -> EClassId -> RndEGraph ()) -> RndEGraph ()-paretoFront fitFun maxSize printExprFun = go 1 0 (-(1.0/0.0))-    where-    go :: Int -> Int -> Double -> RndEGraph ()-    go n ix f-        | n > maxSize = pure ()-        | otherwise   = do-            ecList <- getBestExprWithSize n-            if not (null ecList)-                then do let (ec, mf) = head ecList-                            improved = fromJust mf > f-                        ec' <- canonical ec-                        when improved $ refit fitFun ec' >> printExprFun ix ec'-                        go (n+1) (ix + if improved then 1 else 0) (max f (fromJust mf))-                else go (n+1) ix f--evaluateUnevaluated fitFun = do-          ec <- gets (IntSet.toList . _unevaluated . _eDB)-          forM_ ec $ \c -> do-              t <- getBestExpr c-              (f, p) <- fitFun t-              insertFitness c f p--evaluateRndUnevaluated fitFun = do-          ec <- gets (IntSet.toList . _unevaluated . _eDB)-          c <- rnd . randomFrom $ ec-          t <- getBestExpr c-          (f, p) <- fitFun t-          insertFitness c f p-          pure c
− apps/rEGGression/Commands.hs
@@ -1,434 +0,0 @@-{-# language OverloadedStrings #-}-{-# language TupleSections #-}--module Commands where--import Control.Applicative ((<|>))-import Data.Attoparsec.ByteString.Char8 hiding ( match )-import qualified Data.ByteString.Char8 as B-import Data.Maybe-import Text.Read ( readMaybe )-import Data.Monoid (All(..))-import qualified Data.IntMap.Strict as IntMap-import qualified Data.IntSet as IntSet-import Control.Monad.State.Strict-import Control.Monad ( forM_, filterM )-import Data.Char ( toUpper )-import qualified Data.Map as Map-import qualified Data.HashSet as Set-import qualified Data.Massiv.Array as MA-import Data.List ( nub, sortOn )-import Data.List.Split ( splitOn )--import Data.SRTree-import Data.SRTree.Datasets-import Data.SRTree.Recursion-import Data.SRTree.Eval-import Data.SRTree.Print hiding ( printExpr )-import Text.ParseSR (SRAlgs(..), parseSR, parsePat, Output(..), showOutput)--import Algorithm.SRTree.Likelihoods-import Algorithm.SRTree.Opt--import Algorithm.EqSat-import Algorithm.EqSat.Egraph-import Algorithm.EqSat.Build-import Algorithm.EqSat.Info-import Algorithm.EqSat.Queries-import Algorithm.EqSat.DB-import Algorithm.EqSat.Simplify--import Algorithm.SRTree.ModelSelection--import Data.Binary ( encode, decode )-import qualified Data.ByteString.Lazy as BS--import Util-import Debug.Trace --- * Parsing---- top 5 by fitness|mdl [less than 5 params, less than 10 nodes]-data Command  = Top Int Filter Criteria PatStr-              | Distribution FilterDist (Maybe Limit) CriteriaDist Int Int-              -- below these will not be a parsable command-              | Report EClassId ArgOpt-              | Optimize EClassId Int ArgOpt-              | Insert String ArgOpt-              | Subtrees EClassId-              | Pareto Criteria-              | CountPat String-              | Save String-              | Load String-              | Import String Distribution String Bool--type Filter = EClass -> Bool -- pattern?-type FilterDist = Int -> Bool-data Criteria = ByFitness | ByDL deriving Eq-data CriteriaDist = ByCount | ByAvgFit-data Limit = Limit Int Bool deriving Show-data PatStr = PatStr String Bool | AntiPatStr String Bool | NoPat-type ArgOpt = (Distribution, [DataSet], [DataSet])---- top 10 with <=10|=10 size with <=4 parameters by fitness|dl matching pat--- report id--- optimize id--- insert eq--- subtrees id--- distribution with size <=10 limited at 10 asc|dsc------parseCmd parser = eitherResult . (`feed` "") . parse parser . putEOL . B.strip--stripSp = many' (char ' ')--parseTop = do n <- decimal-              stripSp-              filters  <- many' parseFilter-              stripSp-              criteria <- fromMaybe ByFitness . listToMaybe <$> many' parseCriteria-              stripSp-              pats' <- many' (parsePattern <|> parseAnti)-              pats <- case pats' of-                        [] -> pure $ NoPat-                        (x:_) -> pure $ x-              pure $ Top n (getAll . mconcat filters) criteria pats--parseDist = do filters' <- many' parseFilterDist-               let filters = if null filters'-                               then [(\pat -> All $ pat <= 10)]-                               else filters'-               stripSp-               limit   <- listToMaybe <$> many' parseLimit-               stripSp-               by'     <- listToMaybe <$> many' parseCriteriaDL-               stripSp -               least' <- listToMaybe <$> many' parseLeast-               stripSp -               top'   <- listToMaybe <$> many' parseTopDist-               let by = case by' of -                          Nothing -> ByCount-                          Just b  -> b-                   least = case least' of -                             Nothing -> 1 -                             Just l  -> l -                   top   = case top' of -                             Nothing -> 1000-                             Just t  -> t-               pure $ Distribution (getAll . mconcat filters) limit by least top --parseLeast = stringCI "with at least " >> decimal -parseTopDist = stringCI "from top " >> decimal -parseCriteriaDL = (stringCI "by count" >> pure ByCount)-              <|> (stringCI "by fitness" >> pure ByAvgFit)--parseFilter = do stringCI "with"-                 stripSp-                 field <- parseSz <|> parseCost <|> parseParams-                 stripSp-                 cmp <- parseCmp-                 stripSp-                 pure (\ec -> All $ cmp (field ec))-parseFilterDist = do stringCI "with"-                     stripSp-                     stringCI "size"-                     stripSp-                     cmp <- parseCmp-                     stripSp-                     pure (\pat -> All $ cmp pat)--parseSz = stringCI "size" >> pure (_size . _info)-parseCost = stringCI "cost" >> pure (_cost . _info)-parseParams = stringCI "parameters" >> pure (mbLen . _theta . _info)-   where-      mbLen [] = 0-      mbLen ps = MA.unSz $ MA.size $ Prelude.head ps-parseCmp = do op <- parseLEQ <|> parseLT <|> parseEQ <|> parseGEQ <|> parseGT-              stripSp-              n <- decimal-              pure (`op` n)--parseLT  = string "<"  >> pure (<)-parseLEQ = string "<=" >> pure (<=)-parseEQ  = string "="  >> pure (==)-parseGEQ = string ">="  >> pure (>=)-parseGT  = string ">" >> pure (>)--parsePattern = do stringCI "matching"-                  stripSp-                  b <- option True parseRoot-                  pat <- many' anyChar-                  pure $ PatStr pat b-parseAnti = do stringCI "not matching"-               stripSp-               b <- option True parseRoot-               pat <- many' anyChar-               pure $ AntiPatStr pat b--parseLimit = do stringCI "limited at"-                stripSp-                n <- decimal-                stripSp-                ascOrdsc <- stringCI "asc" <|> stringCI "dsc"-                pure $ Limit n (ascOrdsc == "asc")-parseRoot = do stringCI "root"-               stripSp-               pure False-parseCriteria = parseByFit <|> parseByDL-parseByFit = do stringCI "by fitness"-                pure ByFitness-parseByDL  = do stringCI "by dl"-                pure ByDL--putEOL :: B.ByteString -> B.ByteString-putEOL bs | B.last bs == '\n' = bs-          | otherwise         = B.snoc bs '\n'---- running-run (Top n filters criteria NoPat) = do-   let getFun = if criteria == ByFitness then getTopFitEClassThat else getTopDLEClassThat-   ids <- egraph $ getFun n filters-   printSimpleMultiExprs $ reverse ids--run (Top n filters criteria withPat) = do-   let (pat', getFun, isParents) =-          case withPat of-            PatStr p parent     -> (p, if criteria == ByFitness then getTopFitEClassIn else getTopDLEClassIn, parent)-            AntiPatStr p parent -> (p, if criteria == ByFitness then getTopFitEClassNotIn else getTopDLEClassNotIn, parent)--   let etree = parsePat $ B.pack pat'-   case etree of-     Left _ -> io.putStrLn $ "no parse for " <> pat'-     Right pat -> do-        ecs' <- egraph $ (Prelude.map fromLeft . Prelude.filter isLeft . Prelude.map snd) <$> match pat-        ecs  <- egraph $ Prelude.mapM canonical ecs'-                          >>= removeNotTrivial (lenPat pat)-                          >>= getParents isParents filters--        ids  <- egraph $ getFun n filters ecs-        printSimpleMultiExprs (reverse $ nub ids)--run (Distribution pSz mLimit by least top) = do-  ee <- egraph $ IntSet.toList . IntSet.fromList <$> getTopFitEClassThat top (const True) -- getAllEvaluatedEClasses-  allPats <- egraph $ getAllPatternsFrom pSz Map.empty ee-  let (n, isAsc) = case mLimit of-                     Nothing -> (Map.size allPats, True)-                     Just (Limit sz asc) -> (sz, asc)-      predCount = (if isAsc then fst else negate . fst) . snd-      predAvgFit = (if isAsc then snd else negate . snd) . snd-  printMultiCounts (Prelude.take n-                   $ case by of -                       ByCount -> sortOn predCount-                       ByAvgFit -> sortOn predAvgFit-                   $ Map.toList-                   $ Map.filterWithKey (\k (v,_) -> v >= least && k /= VarPat 'A' && pSz (lenPat k))-                   allPats)--run (Report eid (dist, trainData, testData)) = egraph $ printExpr trainData testData dist eid--run (Optimize eid nIters (dist, trainDatas, testData)) = do -- dist trainData testData-   t <- egraph $ relabelParams <$> getBestExpr eid-   (f, thetas) <- egraph $ fitnessMV nIters dist trainDatas t-   egraph $ insertFitness eid f thetas-   let mdl_train  = Prelude.maximum $ Prelude.map (\(theta, (x, y, mYErr)) -> mdl dist mYErr x y theta t) $ Prelude.zip thetas trainDatas-   egraph $ insertDL eid mdl_train-   printSimpleMultiExprs [eid]--run (Insert expr argOpt) = do-  let etree = parseSR TIR "" False $ B.pack expr-  case etree of-    Left _     -> io.putStrLn $ "no parse for " <> expr-    Right tree -> do eid <- egraph $ fromTree myCost tree-                     run (Optimize eid 100 argOpt)--run (Subtrees eid) = do-   isValid <- egraph $ gets ((IntMap.member eid) . _eClass)-   if isValid-     then do ids <- egraph $ getAllChildBestEClasses eid-             printSimpleMultiExprs ids-     else io.putStrLn $ "Invalid id."--run (Pareto crit) = do-   maxSize <- egraph $ gets (fst . IntMap.findMax . _sizeFitDB . _eDB)-   ecs <- egraph $ case crit of-            ByFitness -> getParetoEcsUpTo True  1 maxSize-            ByDL      -> getParetoEcsUpTo False 1 maxSize-   printSimpleMultiExprs ecs--run (CountPat spat) = do-  let etree = parsePat $ B.pack spat-  case etree of-    Left _     -> io.putStrLn $ "no parse for " <> spat-    Right pat  -> do (p, cnt) <- countPattern pat-                     io . putStrLn $ spat <> " appears in " <> show cnt <> " equations."--run (Save fname) = do-  eg <- egraph get-  io $ BS.writeFile fname (encode eg)--run (Load fname) = do-  eg <- io $ BS.readFile fname-  egraph $ put (decode eg)--run (Import fname dist varnames params) = do-  egraph $ importCSV dist fname varnames params---- * auxiliary functions-importCSV :: Distribution -> String -> String -> Bool -> RndEGraph ()-importCSV dist fname hdr convertParam = cleanDB >> parseEqs >> createDB >> rebuildAllRanges-  where-    alg = getFormat fname--    toTuple :: [String] -> (String, [Double], Double)-    toTuple [eq, t, f] = (eq, Prelude.map Prelude.read $ Prelude.filter (not.null) $ splitOn ";" t, fromMaybe (-1.0/0.0) $ readMaybe f)-    toTuple xss = error $ show xss--    parseEqs :: RndEGraph ()-    parseEqs = do content <- Prelude.map (toTuple . splitOn ",") . lines <$> (liftIO $ readFile fname)-                  forM_ content $ \(eq, params, f) -> do-                    case parseSR alg (B.pack hdr) False (B.pack eq) of-                         Left _ -> liftIO $ putStrLn $ "Skippping " <> eq-                         Right tree' -> do-                           let (tree, ps) = if convertParam then floatConstsToParam tree' else (tree', theta)-                               theta      = if convertParam then if dist==MSE then ps <> params else ps else params-                           eid <- fromTree myCost tree >>= canonical-                           -- TODO: how to import MvSR?-                           insertFitness eid f $ [MA.fromList MA.Seq theta]-                           runEqSat myCost rewritesParams 1-                           cleanDB---parseCSV :: Distribution -> String -> String -> Bool -> IO EGraph-parseCSV dist fname hdr convertParam = execStateT parseEqs emptyGraph-  where-    alg = getFormat fname--    toTuple :: [String] -> (String, [Double], Double)-    toTuple [eq, t, f] = (eq, Prelude.map Prelude.read $ Prelude.filter (not.null) $ splitOn ";" t, fromMaybe (-1.0/0.0) $ readMaybe f)-    toTuple xss = error $ show xss--    parseEqs :: RndEGraph ()-    parseEqs = do content <- Prelude.map (toTuple . splitOn ",") . lines <$> (liftIO $ readFile fname)-                  forM_ content $ \(eq, params, f) -> do-                    case parseSR alg (B.pack hdr) False (B.pack eq) of-                         Left _ -> liftIO $ putStrLn $ "Skippping " <> eq-                         Right tree' -> do-                           let (tree, ps) = if convertParam then floatConstsToParam tree' else (tree', theta)-                               theta      = if convertParam then if dist==MSE then ps <> params else ps else params-                           eid <- fromTree myCost tree >>= canonical-                           -- TODO: how to import MvSR?-                           insertFitness eid f $ [MA.fromList MA.Seq theta]-                           runEqSat myCost rewritesParams 1-                           cleanDB-getFormat :: String -> SRAlgs-getFormat = Prelude.read . Prelude.map toUpper . Prelude.last . splitOn "."----convert :: String -> Output -> String -> IO ()-convert fname out hdr = do-  let alg = getFormat fname-  content <- Prelude.map (toTuple . splitOn ",") . lines <$> readFile fname-  forM_ content $ \(eq, params, f) -> do-    case parseSR alg (B.pack hdr) False (B.pack eq) of-          Left _ -> pure ()-          Right tree -> do-            putStr (showOutput out tree)-            putChar ','-            putStr params-            putChar ','-            putStrLn f-  where-    toTuple :: [String] -> (String, String, String)-    toTuple [eq, t, f] = (eq, t, f)-    toTuple xss = error $ show xss--getParents False _ ecs = pure ecs-getParents True  p ecs = IntSet.toList <$> getParentsOf p (IntSet.fromList ecs) 300000 ecs--isBest (e', en') = do e <- canonical e'-                      best <- gets (_best . _info . (IntMap.! e) . _eClass) >>= canonize-                      en <- canonize en'-                      pure (en == best)--getParentsOf :: (EClass -> Bool) -> IntSet.IntSet -> Int -> [EClassId] -> RndEGraph IntSet.IntSet-getParentsOf p visited n queue | IntSet.size visited >= n || null queue = pure visited-getParentsOf p visited n queue =-   do parents'     <- IntSet.unions <$> Prelude.mapM (\e -> canonical e >>= canonizeParents) queue--      grandParents <- getParentsOf p ((visited <> parents')) n (IntSet.toList parents')-      pure (visited <> grandParents)-   where-      filterUneval uneval = IntSet.filter (`IntSet.notMember` uneval)-      isNew ec (e, en) = ec `Prelude.elem` (childrenOf en) && (e `IntSet.notMember` visited)-      canonizeParents ec = do ecl <- gets ((IntMap.! ec) . _eClass)-                              let parents' = Set.toList . Set.filter (isNew ec) $ _parents ecl-                              parents <- Prelude.map fst <$> filterM isBest parents'-                              pure (IntSet.fromList parents)--isLeft (Left _)   = True-isLeft _          = False-fromLeft (Left x) = x-fromLeft _        = undefined--addTuple (a, b) (c, d) = (a+c, b+d)--getAllPatternsFrom :: (Int -> Bool) -> Map.Map Pattern (Int, Double) -> [EClassId] -> EGraphST IO (Map.Map Pattern (Int, Double))-getAllPatternsFrom pSz counts []     = pure $ Map.map (\(v1, v2) -> (v1, v2/fromIntegral v1)) counts-getAllPatternsFrom pSz counts (x:xs) = do fit' <- getFitness x -                                          case fit' of -                                            Nothing -> getAllPatternsFrom pSz counts xs-                                            Just fit -> do-                                                         pats <- Map.map (,fit) <$> getAllPatterns pSz x-                                                         getAllPatternsFrom pSz (Map.unionWith addTuple pats counts) xs--relabelVarPat :: Pattern -> Pattern-relabelVarPat t = alg t `evalState` 65-   where-      alg :: Pattern -> State Int Pattern-      alg (VarPat _) = do ix <- Control.Monad.State.Strict.get; Control.Monad.State.Strict.modify (+1); pure (VarPat $ toEnum ix)-      alg (Fixed (Uni f t')) = do t <- alg t'; pure $ Fixed (Uni f t)-      alg (Fixed (Bin op l' r')) = do l <- alg l'; r <- alg r'; pure $ Fixed (Bin op l r)-      alg pt                   = pure pt--lenPat :: Pattern -> Int-lenPat (Fixed (Uni _ t)) = 1 + lenPat t-lenPat (Fixed (Bin _ l r)) = 1 + lenPat l + lenPat r-lenPat _ = 1--countPattern pat = do-  ecs' <- egraph $ (Prelude.map fromLeft . Prelude.filter isLeft . Prelude.map snd) <$> match pat-  ecs <- egraph $ Prelude.mapM canonical ecs'-                    >>= getEvaluated-  pure (pat, IntSet.size ecs)--getEvaluated ecs = getParentsOf (const True) (IntSet.fromList ecs) 500000 ecs--getAllPatterns :: Monad m => (Int -> Bool) -> EClassId -> EGraphST m (Map.Map Pattern Int)-getAllPatterns pSz eid = do-   eid' <- canonical eid-   best <- gets (_best . _info . (IntMap.! eid') . _eClass)-   case best of-      Var ix     -> pure $ Map.fromList [(VarPat 'A', 1), (Fixed (Var ix), 1)]-      Param ix   -> pure $ Map.fromList [(VarPat 'A', 1), (Fixed (Param ix), 1)]-      Const x    -> pure $ Map.fromList [(VarPat 'A', 1), (Fixed (Const x), 1)]-      Uni f t    -> do pats <- Map.filterWithKey (\k _ -> (pSz . lenPat) k) <$> getAllPatterns pSz t-                       pure $ Map.insertWith (+) (VarPat 'A') 1 -                            $ Map.mapKeysWith (+) (\t' -> Fixed (Uni f t')) pats-      Bin op l r | l==r -> do pats <- Map.filterWithKey (\k _ -> (pSz . lenPat) k) <$> getAllPatterns pSz l-                              pure $ Map.insertWith (+) (VarPat 'A') 1 $ Map.mapKeysWith (+) (\t' -> Fixed (Bin op t' t')) pats-                  | otherwise -> do patsL <- Map.filterWithKey (\k _ -> (pSz . lenPat) k) <$> getAllPatterns pSz l-                                    patsR <- Map.filterWithKey (\k _ -> (pSz . lenPat) k) <$> getAllPatterns pSz r-                                    pure $ Map.fromList $ (VarPat 'A', 1) : [(relabelVarPat $ Fixed (Bin op l' r'), min vl vr) | (l', vl) <- Map.toList patsL, (r', vr) <- Map.toList patsR]--isNotTrivial :: Monad m => Int -> EClassId -> EGraphST m Bool-isNotTrivial n ec = do-  c <- gets (_consts . _info . (IntMap.! ec) . _eClass)-  m <- gets (_size . _info . (IntMap.! ec) . _eClass)-  pure (c == NotConst && m >= n)-removeNotTrivial :: Monad m => Int -> [EClassId] -> EGraphST m [EClassId]-removeNotTrivial n [] = pure []-removeNotTrivial n (ec:ecs) = do-  b <- isNotTrivial n ec-  ecs' <- removeNotTrivial n ecs-  pure $ if b then (ec:ecs') else ecs'
− apps/rEGGression/Main.hs
@@ -1,340 +0,0 @@-{-# LANGUAGE  BlockArguments #-}-{-# LANGUAGE  TupleSections #-}-{-# LANGUAGE  MultiWayIf #-}-{-# LANGUAGE  OverloadedStrings #-}-{-# LANGUAGE  FlexibleContexts #-}-{-# LANGUAGE FlexibleInstances #-}-{-# LANGUAGE TypeSynonymInstances #-}-{-# LANGUAGE TypeApplications #-}--module Main where --import Algorithm.SRTree.Likelihoods-import Algorithm.SRTree.Opt-import Control.Monad.State.Strict--import Algorithm.EqSat.Egraph-import Algorithm.EqSat.Build-import Algorithm.EqSat.Info-import Algorithm.EqSat.Queries-import Algorithm.EqSat.DB-import Algorithm.EqSat.Simplify--import qualified Data.IntMap as IM-import Data.Massiv.Array as MA hiding (forM_, forM, Continue, convert)-import Data.Maybe (fromJust, isNothing, isJust)-import Data.SRTree-import Data.SRTree.Recursion-import Data.SRTree.Datasets-import Data.SRTree.Eval-import Data.SRTree.Random (randomTree)-import Data.SRTree.Print hiding ( printExpr )-import Options.Applicative as Opt hiding (Const, columns)-import System.Random-import qualified Data.HashSet as Set-import Data.List ( sort, sortOn )-import Data.List.Split ( splitOn )-import qualified Data.Map as Map-import Data.Map ( Map )-import qualified Data.IntMap.Strict as IntMap-import Data.Char ( toLower, toUpper )-import Debug.Trace-import Algorithm.EqSat (runEqSat)--import System.Console.Repline hiding (Repl)-import Util-import Commands-import Data.List ( isPrefixOf, intercalate, nub )-import Text.Read-import Control.Monad ( forM, when, forM_ )-import Data.Binary ( encode, decode )-import qualified Data.ByteString.Lazy as BS-import Data.Maybe ( fromMaybe )-import Text.ParseSR (SRAlgs(..), parseSR, parsePat, Output(..), showOutput)-import qualified Data.ByteString.Char8 as B-import qualified Data.IntSet as IntSet-import qualified Data.Set as SSet--data Args = Args-  { _dataset       :: String,-    _testData      :: String,-    _distribution  :: Distribution,-    _dumpTo        :: String,-    _loadFrom      :: String,-    _parseCSV      :: String,-    _convertFromTo :: String,-    _parseParams   :: Bool,-    _to            :: Output,-    _calcDL        :: Bool-  }-  deriving (Show)---- parser of command line arguments-opt :: Parser Args-opt = Args-  <$> strOption-       ( long "dataset"-       <> short 'd'-       <> metavar "INPUT-FILE"-       <> help "CSV dataset." )-  <*> strOption-       ( long "test"-       <> short 't'-       <> value ""-       <> showDefault-       <> help "test data")-  <*> option auto-       ( long "distribution"-       <> value Gaussian-       <> showDefault-       <> help "distribution of the data.")-  <*> strOption-       ( long "dump-to"-       <> value ""-       <> showDefault-       <> help "dump final e-graph to a file."-       )-  <*> strOption-       ( long "load-from"-       <> value ""-       <> showDefault-       <> help "load initial e-graph from a file."-       )-  <*> strOption-       ( long "parse-csv"-       <> value ""-       <> showDefault-       <> help "parse-csv CSV file with the format expression,parameters,fitness. The fitness value should be maximization and the parameters a ; separated list (there must be an additional parameter for sigma in the Gaussian distribution). The format of the equation is determined by the extension of the file, supported extensions are operon, pysr, tir, itea, hl (heuristiclab), gomea, feat, etc."-       )-  <*> strOption-       ( long "convert"-       <> value ""-       <> showDefault-       <> help "convert FROM TO, converts equation format from a given format (see 'parse-csv') to either 'math' or 'numpy'. The 'math' format is compatible with the tir format, so you can use this to standardize the equations from multiple sources into a single file. The output will be written to stdout."-       )-  <*> switch-       ( long "parse-parameters"-       <> help "Extract the numerical parameters from the expression. In this case the csv file should be formatted as \"equation,error,fitness, where 'error' is the error term used in Gaussia likelihood, it can be empty if using other distributions.\""-       )-  <*> option auto-       ( long "to"-       <> value MATH-       <> showDefault-       <> help "Format to convert to."-       )-  <*> switch-       ( long "calculate-dl"-       <> help "(re)calculate DL."-       )--runIfRight cmd = case cmd of-                    Left err -> io.print $ "wrong command format."-                    Right c  -> run c--topCmd :: [String] -> Repl ()-topCmd []    = helpCmd ["top"]-topCmd args  = do-  let cmd = parseCmd parseTop (B.pack $ unwords args)-  runIfRight cmd--distCmd :: [String] -> Repl ()-distCmd []   = helpCmd ["distribution"]-distCmd args = do-  let cmd = parseCmd parseDist (B.pack $ unwords args)-  runIfRight cmd--reportCmd :: Distribution -> [DataSet] -> [DataSet] -> [String] -> Repl ()-reportCmd _ _ _ [] = helpCmd ["report"]-reportCmd dist trainData testData args =-  case readMaybe @Int (head args) of-    Nothing -> io.putStrLn $ "The id must be an integer."-    Just n  -> run (Report n (dist, trainData, testData))--optimizeCmd :: Distribution -> [DataSet] -> [DataSet] -> [String] -> Repl ()-optimizeCmd _ _ _ [] = helpCmd ["optimize"]-optimizeCmd dist trainData testData args =-  case readMaybe @Int (head args) of-    Nothing -> io.putStrLn $ "The id must be an integer."-    Just n  -> do let nIters = if length args > 1 then fromMaybe 100 (readMaybe @Int (args !! 1)) else 100-                  run (Optimize n nIters (dist, trainData, trainData))--subtreesCmd :: [String] -> Repl ()-subtreesCmd [] = helpCmd ["subtrees"]-subtreesCmd (arg:_) = case readMaybe @Int arg of-                        Nothing -> io.putStrLn $ "The argument must be an integer."-                        Just n  -> run (Subtrees n)--insertCmd :: Distribution -> [DataSet] -> [DataSet] -> [String] -> Repl ()-insertCmd dist trainData testData [] = helpCmd ["insert"]-insertCmd dist trainData testData args = do-  let etree = parseSR TIR "" False $ B.pack (unwords args)-  case etree of-    Left _     -> io.putStrLn $ "no parse for " <> unwords args-    Right tree -> do ec <- egraph $ fromTree myCost tree-                     run (Optimize ec 100 (dist, trainData, trainData))--paretoCmd :: [String] -> Repl ()-paretoCmd []   = run (Pareto ByFitness)-paretoCmd args = case (Prelude.map toLower $ unwords args) of-                    "by fitness" -> run (Pareto ByFitness )-                    "by dl"      -> run (Pareto ByDL)-                    _            -> helpCmd ["pareto"]--countPatCmd :: [String] -> Repl ()-countPatCmd []   = helpCmd ["count-pattern"]-countPatCmd args = run (CountPat (unwords args))--saveCmd :: [String] -> Repl ()-saveCmd [] = helpCmd ["save"]-saveCmd args = run (Save (unwords args))--loadCmd :: [String] -> Repl ()-loadCmd [] = helpCmd ["load"]-loadCmd args = run (Load (unwords args))--importCmd :: Distribution -> String -> [String] -> Repl ()-importCmd dist varnames (fname:params:_) = run (Import fname dist varnames (Prelude.read params))-importCmd dist varnames _   = helpCmd ["import"]---commands = ["help", "top", "report", "optimize", "subtrees", "insert", "count-pattern", "distribution", "pareto", "save", "load", "import"]--topHlp = "top N [FILTER...] [CRITERIA] [[not] matching [root] PATTERN] \n \-         \ \n \-         \ FILTER: with [size|cost|parameters] [<|<=|=|>|>=] N \n \-         \ CRITERIA: [by fitness | by dl]  \n \-         \ \n \-         \ where \"dl\" is the description length, \"cost\" is the default cost function \n \-         \ and \"parameters\" refer to the number of parameters. The cost function  \n \-         \ assigns a cost of 1 to terminals, 2 to binary operators and 3 to \n \-         \ nonlinear functions. \n \-         \ \n \-         \ Example: \n \-         \ \n \-         \ top 10 with size <= 10 with parameters > 2 by fitness matching v0 * x0 + t0 \n \-         \ \n \-         \ This will return the 10 best expressions by fitness with size less than \n \-         \ or equal to 10 and more than 2 parameters containing any sub-expression  \n \-         \ in the format f(x) * x0 + t0. \n \-         \ To create a pattern for matching you can use x0 .. xn to represent a variable \n \-         \  t0 .. tn to represent a numerical parameter, and v0 .. vn to represent wildcards. \n \-         \ Notice that v0 * x0 + v0 will pattern expressions such as (sin(t0) + x0) * x0 + (sin(t0) + x0) \n \-         \ but not (sin(t0) + x0) * x0 + t0, since both occurrences of v0 will match the same expression. \n \-         \ (see `help count-pattern` for more details) \-         \ The keyword \"root\" will matches only expressions starting with this pattern."--distHlp = "distribution [FILTER] [LIMIT] \n\n \-          \ FILTER: with size [<|<=|=|>|>=] N \n \-          \ LIMIT: limited at N [asc|dsc] \n\n \-          \ Shows the distribution of all the patterns in the set of evaluated expressions.\n \-          \ The list can be filtered by the size of the pattern and limited by the top most frequent (dsc) \n \-          \ or least frequent (asc) patterns. \n\n \-          \ See `help count-pattern` for details on the syntax of pattern."--countHlp = "count-pattern PAT \n\n \-           \ Count the number of occurrence of the pattern PAT in the e-graph. \n\n \-           \ A pattern follows the same syntax of an expression: \n\n\-           \ EXPR := FUN(EXPR) | EXPR OP EXPR | TERM \n\-           \ FUN := abs | sin | cos | tan | sinh | cosh | tanh | asin | acos | atan | asinh | acosh | atanh | sqrt | sqrtabs | cbrt | square | log | logabs | exp | recip | cube \n\-           \ OP := + | - | * | / | aq | ^ | |^| \n\-           \ TERM := xN | tN | vN \n\n\-           \ where: \n \-           \ - aq is the analytical quotient (x aq y = x / sqrt(1 + y^2)) \n \-           \ - x |^| y = abs(x) ^ y \n \-           \ - xN is the N-th input variable \n \-           \ - tN is the N-th numerical parameter \n \-           \ - vN is the N-th pattern variable (see below) \n\n \-           \ The pattern variable works as a wildcard matching any expression. \n \-           \ If we use the same pattern variable multiple times in the expression, \n \-           \ the pattern must be the same in every occurrence. \n\n \-           \ Examples: \n\n \-           \ v0 + x0 will match anything added to x0\n \-           \ v0 + v1 * x0 will match anything added to any expression multiplied by x0. \-           \ For example: t0 ^ 2 + exp(t1 + x1) * x0. \n \-           \ v0 + v0 * x0 will match any expression added with this same expression multiplied by x0. \-           \ For example: t0 ^ 2 + (t0 ^ 2) * x0."--hlpMap = Map.fromList $ Prelude.zip commands-                            [ "help <cmd>: shows a brief explanation for the command."-                            , topHlp-                            , "report N: displays a detailed report for the expression with id N."-                            , "optimize N: (re)optimize expression with id N."-                            , "subtrees N: shows the subtrees for the tree rotted with id N."-                            , "insert EXPR: inserts a new expression EXPR and evaluates."-                            , countHlp-                            , distHlp-                            , "pareto [by fitness| by dl]: shows the pareto front where the first objective is the criteria (default: fitness) and the second objective is model size."-                            , "save FILE: save current e-graph to a file named FILE."-                            , "load FILE: load current e-graph from a file named FILE."-                            ]---- Evaluation-cmd :: Map String ([String] -> Repl ()) -> String -> Repl ()-cmd cmdMap input = do let (cmd':args) = words input-                      case cmdMap Map.!? cmd' of-                        Nothing -> io.putStrLn $ "Command not found!!!"-                        Just f  -> f args--helpCmd :: [String] -> Repl ()-helpCmd []    = io . putStrLn $ "Usage: help <command-name>."-helpCmd (x:_) = case hlpMap Map.!? x of-                  Nothing -> io.putStrLn $ "Command not found!!!"-                  Just hlp -> io.putStrLn $ hlp--- Completion-comp :: (Monad m, MonadState EGraph m) => WordCompleter m-comp n = pure $ filter (isPrefixOf n) commands--ini :: Repl ()-ini = do (io . putStrLn) "Welcome to r🥚ression.\nPress Ctrl-D to exit.\nPress <TAB> to see the commands."-         pure ()--final :: Repl ExitDecision-final = do io.print $ "good-bye!"-           return Exit--- TODO: DL is sorted by min not max as the fitness-main :: IO ()-main = do-  args <- execParser opts-  g <- getStdGen-  let datasets = words (_dataset args)-  dataTrainsWP <- Prelude.mapM (flip loadTrainingOnly True) datasets-  let dataTrains = Prelude.map fst dataTrainsWP-      varnames   = snd . head $ dataTrainsWP--  dataTests  <- if null (_testData args)-                  then pure dataTrains-                  else Prelude.map fst <$> (Prelude.mapM (flip loadTrainingOnly True) $ words (_testData args))-  eg <- if (not.null) (_loadFrom args)-           then decode <$> BS.readFile (_loadFrom args)-           else if (not. null) (_parseCSV args)-                 then parseCSV (_distribution args) (_parseCSV args) varnames (_parseParams args)-                 else pure emptyGraph-  let --alg = evalStateT (repl dataTrain dataVal dataTest args) emptyGraph-      dist = _distribution args-      funs = [ helpCmd-             , topCmd-             , reportCmd dist dataTrains dataTests-             , optimizeCmd dist dataTrains dataTests-             , subtreesCmd-             , insertCmd dist dataTrains dataTests-             , countPatCmd-             , distCmd-             , paretoCmd-             , saveCmd-             , loadCmd-             , importCmd dist varnames-             ]-      cmdMap = Map.fromList $ Prelude.zip commands funs--      repl = evalRepl (const $ pure ">>> ") (cmd cmdMap) [] Nothing Nothing (Word comp) ini final-      crDB = if _calcDL args then (createDBBest >> fillDL dist dataTrains >> rebuildAllRanges) else (createDBBest >> rebuildAllRanges)-  if (not.null) (_convertFromTo args)-     then convert (_convertFromTo args) (_to args) varnames-     else do when (_calcDL args) $ putStrLn "Calculating DL..."-             eg' <- execStateT crDB eg-             evalStateT repl eg'-  where-    opts = Opt.info (opt <**> helper)-            ( fullDesc <> progDesc "Exploration and query system for a database of regression models using e-graphs."-           <> header "r🥚ression - Nonlinear regression models exploration and query system with e-graphs (egg)." )-
− apps/rEGGression/Random.hs
@@ -1,33 +0,0 @@-module Random where --import System.Random -import Control.Monad.State.Strict-import Control.Monad-import Data.SRTree -import Data.SRTree.Eval-import Data.Massiv.Array as MA--type Rng a = IO a--toss :: Rng Bool-toss = randomIO-{-# INLINE toss #-}--tossBiased :: Double -> Rng Bool-tossBiased p = do r <- randomIO-                  pure (r < p)--randomVal :: Rng Double-randomVal = randomIO--randomRange :: (Ord val, Random val) => (val, val) -> Rng val-randomRange rng = (randomRIO rng)-{-# INLINE randomRange #-}--randomFrom :: [a] -> Rng a-randomFrom funs = do n <- randomRange (0, length funs - 1)-                     pure $ funs !! n-{-# INLINE randomFrom #-}--randomVec :: Int -> Rng PVector-randomVec n = MA.fromList compMode <$> replicateM n (randomRange (-1, 1))
− apps/rEGGression/Util.hs
@@ -1,287 +0,0 @@-{-# LANGUAGE  BlockArguments #-}-{-# LANGUAGE  TupleSections #-}--module Util where--import qualified Data.Map.Strict as Map-import Data.Massiv.Array as MA hiding (forM_, forM)-import Data.SRTree-import Data.SRTree.Eval-import Algorithm.SRTree.Opt-import Algorithm.EqSat.Egraph-import Algorithm.EqSat.Build-import Algorithm.EqSat.Info-import Algorithm.EqSat ( recalculateBest )--import Algorithm.SRTree.NonlinearOpt-import System.Random-import Random-import Algorithm.SRTree.Likelihoods-import Algorithm.SRTree.ModelSelection-import Data.SRTree.Print---import Algorithm.SRTree.ModelSelection---import Algorithm.SRTree.Opt-import qualified Data.IntMap.Strict as IM-import Control.Monad.State.Strict-import Control.Monad ( when, replicateM, forM, forM_ )-import Data.Maybe ( fromJust )-import Data.List ( maximumBy, intercalate )-import Data.Function ( on )-import List.Shuffle ( shuffle )-import Data.List.Split ( splitOn )-import Data.Char ( toLower )-import qualified Data.IntSet as IntSet-import Data.SRTree.Datasets-import Algorithm.EqSat.Queries-import Algorithm.EqSat.DB-import Data.List (nub)-import System.Console.Repline hiding (Repl)-import Text.Printf-import Text.Layout.Table hiding (top)-import Text.Layout.Table.Cell.Formatted-import Text.Layout.Table.Cell-import System.Console.ANSI.Codes---type RndEGraph = StateT EGraph IO-type DataSet = (SRMatrix, PVector, Maybe PVector)-data Info = Info {_training :: DataSet, _test :: DataSet, _dist :: Distribution}-type Repl = HaskelineT (StateT EGraph IO)--csvHeader :: String-csvHeader = "id,Expression,theta,size,MSE_train,MSE_val,MSE_test,R2_train,R2_val,R2_test,nll_train,nll_val,nll_test,mdl_train,mdl_val,mdl_test"--io :: IO a -> Repl a-io = lift . lift-{-# INLINE io #-}-egraph :: RndEGraph a -> Repl a-egraph = lift--myCost :: SRTree Int -> Int-myCost (Var _)     = 1-myCost (Const _)   = 1-myCost (Param _)   = 1-myCost (Bin _ l r) = 2 + l + r-myCost (Uni _ t)   = 3 + t--fitnessFun :: Int -> Distribution -> DataSet -> Fix SRTree -> PVector -> (Double, PVector)-fitnessFun nIter distribution (x, y, mYErr) _tree thetaOrig =-  if isNaN tr-    then (-(1/0), theta) -- infinity-    else (tr, theta)-  where-    tree          = relabelParams _tree-    nParams       = countParams tree + if distribution == ROXY then 3 else if distribution == Gaussian then 1 else 0-    (theta, _, _) = minimizeNLL' VAR1 distribution mYErr nIter x y tree thetaOrig-    evalF a b c   = negate $ nll distribution c a b tree $ if nParams == 0 then thetaOrig else theta-    tr            = evalF x y mYErr--{-# INLINE fitnessFun #-}--fitnessFunRep :: Int -> Distribution -> DataSet -> Fix SRTree -> RndEGraph (Double, PVector)-fitnessFunRep nIter distribution dataTrain _tree = do-    let tree = relabelParams _tree-        nParams = countParams tree + if distribution == ROXY then 3 else if distribution == Gaussian then 1 else 0--    thetaOrigs <- lift (randomVec nParams)-    --lift $ print thetaOrigs-    pure (fitnessFun nIter distribution dataTrain tree thetaOrigs)-{-# INLINE fitnessFunRep #-}--fitnessMV :: Int -> Distribution -> [DataSet] -> Fix SRTree -> RndEGraph (Double, [PVector])-fitnessMV nIter distribution dataTrainsVals _tree = do-  response <- forM dataTrainsVals $ \dt -> fitnessFunRep nIter distribution dt _tree-  pure (minimum (Prelude.map fst response), Prelude.map snd response)----- helper query functions--- TODO: move to egraph lib-getFitness :: EClassId -> RndEGraph (Maybe Double)-getFitness c = gets (_fitness . _info . (IM.! c) . _eClass)-{-# INLINE getFitness #-}-getTheta :: EClassId -> RndEGraph ([PVector])-getTheta c = gets (_theta . _info . (IM.! c) . _eClass)-{-# INLINE getTheta #-}-getSize :: EClassId -> RndEGraph Int-getSize c = gets (_size . _info . (IM.! c) . _eClass)-{-# INLINE getSize #-}-isSizeOf :: (Int -> Bool) -> EClass -> Bool-isSizeOf p = p . _size . _info-{-# INLINE isSizeOf #-}-getDL :: EClassId -> RndEGraph (Maybe Double)-getDL c = gets (_dl . _info . (IM.! c) . _eClass)-{-# INLINE getDL #-}--getBestFitness :: RndEGraph (Maybe Double)-getBestFitness = do-    bec <- (gets (snd . getGreatest . _fitRangeDB . _eDB) >>= canonical)-    gets (_fitness . _info . (IM.! bec) . _eClass)--getTrain :: ((a, b1, c1, d1), (c2, b2), c3, d2) -> ((a, b1, c2), c3)-getTrain ((a, b, _, _), (c, _), varnames, _) = ((a,b,c), varnames)--getX :: DataSet -> SRMatrix-getX (a, _, _) = a--getTarget :: DataSet -> PVector-getTarget (_, b, _) = b--getError :: DataSet -> Maybe PVector-getError (_, _, c) = c--loadTrainingOnly fname b = getTrain <$> loadDataset fname b--mvFun fun thetas datasets = Prelude.map (\(theta, (x,y,e)) -> fun x y e theta)-                          $ Prelude.zip thetas datasets--printExpr :: [DataSet] -> [DataSet] -> Distribution -> EClassId -> RndEGraph ()-printExpr dataTrain dataTest distribution ec = do-        thetas <- getTheta ec--        bestExpr <- getBestExpr ec-        let --(x, y, mYErr) = dataTrain-            --(x_te, y_te, mYErr_te) = dataTest-            best'       = relabelParams bestExpr--            mseMV x y e theta = printf "%.4e" $ mse x y best' theta-            r2MV  x y e theta = printf "%.4e" $ r2 x y best' theta-            nllMV x y e theta = printf "%.4e" $ nll distribution e x y best' theta-            mdlMV x y e theta = printf "%.4e" $ mdl distribution e x y theta best'--            -- expr        = paramsToConst (MA.toList theta) best'-            mse_trains  = intercalate "; " $ mvFun mseMV thetas dataTrain-            mse_tes     = intercalate "; " $ mvFun mseMV thetas dataTest-            r2_trains   = intercalate "; " $ mvFun r2MV thetas dataTrain-            r2_tes      = intercalate "; " $ mvFun r2MV thetas dataTest-            nll_trains  = intercalate "; " $ mvFun nllMV thetas dataTrain-            nll_tes     = intercalate "; " $ mvFun nllMV thetas dataTest-            mdl_trains  = intercalate "; " $ mvFun mdlMV thetas dataTrain-            mdl_tes     = intercalate "; " $ mvFun mdlMV thetas dataTest-            thetaStr    = intercalate "; " $ Prelude.map (intercalate ", " . Prelude.map show . MA.toList) thetas-        insertDL ec $ Prelude.maximum $ Prelude.map (\(theta, (x, y, mYerr)) -> mdl distribution mYerr x y theta best') $ Prelude.zip thetas dataTrain -        lift . putStr $ "Evaluation metrics for expression (" <> (show ec) <> "): "-        lift . putStr $ setSGRCode [SetConsoleIntensity BoldIntensity]-        lift . putStrLn $ showExpr best'-        lift . putStr $ setSGRCode [Reset]-        lift . putStrLn $ "# of nodes\t" <> show (countNodes $ convertProtectedOps best')-        lift . putStrLn $ "params:\t[" <> thetaStr <> "]"--        let rows = [ rowG ["MSE", mse_trains, mse_tes]-                   , rowG ["R^2", r2_trains, r2_tes]-                   , rowG ["nll", nll_trains, nll_tes]-                   , rowG ["DL",  mdl_trains, mdl_tes]-                   ]-            columnsReport = [def, numCol, numCol]-            headerReport = titlesH $ Prelude.map bold ["Metric", "Training", "Test"]-        lift . putStrLn $ tableString (columnHeaderTableS columnsReport unicodeS headerReport rows)--printsimpleExpr eid = do t   <- egraph $ relabelParams <$> getBestExpr eid-                         fit <- egraph $ getFitness eid-                         sz  <- egraph $ getSize eid-                         p   <- egraph $ getTheta eid-                         dl  <- egraph $ getDL eid-                         let fit' = case fit of-                                      Nothing -> "--"-                                      Just f  -> printf "%.4e" f-                             p' = case p of-                                    [] -> "--"-                                    pss -> intercalate ";" $ Prelude.map (\ps -> "[" <> intercalate ", " (Prelude.map (printf "%.4e") (MA.toList ps)) <> "]") pss-                             dl' = case dl of-                                    Nothing -> "--"-                                    Just d  -> printf "%.4e" d--                         pure $ colsAllG center [[show eid], justifyText 50 $ showExpr t, [fit'], justifyText 50 p', [show sz], [dl']]--printCounts (pat, (cnt, avgfit)) = do-  let spat = showPat pat-  pure $ colsAllG center [justifyText 50 spat, [show cnt], [printf "%.4e" avgfit]]-  where-    showPat (Fixed (Var ix)) = 'x' : show ix-    showPat (Fixed (Param ix)) = 't' : show ix-    showPat (Fixed (Const x))  = show x-    showPat (Fixed (Bin op l r)) = concat ["(", showPat l, " ", showOp op, " ", showPat r, ")"]-    showPat (Fixed (Uni f t)) = concat [show f, "(", showPat t, ")"]-    showPat (VarPat ix) = 'v' : show (fromEnum ix-65)--printSimpleMultiExprs eids = do rows <- forM (nub eids) printsimpleExpr-                                io.putStrLn $ tableString (columnHeaderTableS columns unicodeS headerSimple rows)--printMultiCounts cnts = do rows <- forM cnts printCounts-                           io.putStrLn $ tableString (columnHeaderTableS [fixedLeftCol 50, numCol, numCol] unicodeS headerCount rows)--bold s = formatted (setSGRCode [SetConsoleIntensity BoldIntensity]) (plain s) (setSGRCode [Reset])--headerSimple :: HeaderSpec LineStyle (Formatted String)-headerSimple = titlesH $ Prelude.map (bold) ["Id", "Expression", "Fitness", "Parameters", "Size", "DL"]-columns = [numCol, fixedLeftCol 50, numCol, fixedLeftCol 50, numCol, numCol]-headerCount :: HeaderSpec LineStyle (Formatted String)-headerCount = titlesH $ Prelude.map bold ["Pattern", "Count", "Avg. Fitness"]---- RndEGraph utils--- fitFun fitnessFunRep rep iter distribution x y mYErr x_val y_val mYErr_val-insertExpr :: Fix SRTree -> (Fix SRTree -> RndEGraph (Double, [PVector])) -> RndEGraph EClassId-insertExpr t fitFun = do-    ecId <- fromTree myCost t >>= canonical-    (f, p) <- fitFun t-    insertFitness ecId f p-    pure ecId-  where powabs l r  = Fix (Bin PowerAbs l r)--updateIfNothing fitFun ec = do-      mf <- getFitness ec-      case mf of-        Nothing -> do-          t <- getBestExpr ec-          (f, p) <- fitFun t-          insertFitness ec f p-          pure True-        Just _ -> pure False--getParetoEcsUpTo b n maxSize = concat <$> forM [1..maxSize] (\i -> getTopEClassWithSize b i n)--getBestExprWithSize n =-        do ec <- getTopFitEClassWithSize n 1 >>= traverse canonical-           if (not (null ec))-            then do-              bestFit <- getFitness $ head ec-              bestP   <- gets (_theta . _info . (IM.! (head ec)) . _eClass)-              (:[]) . (,bestP) . (,bestFit) . (,ec) <$> getBestExpr (head ec)-            else pure []--printBest :: (Int -> EClassId -> RndEGraph ()) -> RndEGraph ()-printBest printExprFun = do-      bec <- gets (snd . getGreatest . _fitRangeDB . _eDB) >>= canonical-      printExprFun 0 bec--paretoFront :: Int -> (Int -> EClassId -> RndEGraph ()) -> RndEGraph ()-paretoFront maxSize printExprFun = go 1 0 (-(1.0/0.0))-    where-    go :: Int -> Int -> Double -> RndEGraph ()-    go n ix f-        | n > maxSize = pure ()-        | otherwise   = do-            ecList <- getBestExprWithSize n-            if not (null ecList)-                then do let (((_, ec), mf), _) = head ecList-                            improved = fromJust mf > f-                        ec' <- traverse canonical ec-                        when improved $ printExprFun ix (head ec')-                        go (n+1) (ix + if improved then 1 else 0) (max f (fromJust mf))-                else go (n+1) ix f--evaluateUnevaluated fitFun = do-          ec <- gets (IntSet.toList . _unevaluated . _eDB)-          forM_ ec $ \c -> do-              t <- getBestExpr c-              (f, p) <- fitFun t-              insertFitness c f p--fillDL dist datasets = do-  ecs <- getAllEvaluatedEClasses-  forM_ ecs $ \ec -> do-    thetas <- getTheta ec-    bestExpr <- relabelParams <$> getBestExpr ec-    if MA.size (head thetas) /= countParams bestExpr-       then (lift . putStrLn) $ "Wrong number of parameters in " <> showExpr bestExpr <> ": " <> show (head thetas) <> "   " <> show ec-       else do let mdl_trains = Prelude.map (\(theta, (x, y, mYerr)) -> mdl dist mYerr x y theta bestExpr) $ Prelude.zip thetas datasets-               insertDL ec $ Prelude.maximum mdl_trains
− apps/symregg/Main.hs
@@ -1,481 +0,0 @@-{-# LANGUAGE  BlockArguments #-}-{-# LANGUAGE  TupleSections #-}-{-# LANGUAGE  MultiWayIf #-}-{-# LANGUAGE  OverloadedStrings #-}-{-# LANGUAGE  BangPatterns #-}-{-# LANGUAGE  TypeSynonymInstances, FlexibleInstances #-}--module Main where --import Algorithm.EqSat.Egraph-import Algorithm.EqSat.Simplify-import Algorithm.EqSat.Build-import Algorithm.EqSat.Queries-import Algorithm.EqSat.Info-import Algorithm.EqSat.DB-import Algorithm.SRTree.Likelihoods-import Algorithm.SRTree.ModelSelection-import Control.Monad ( forM_, forM, when, filterM )-import Control.Monad.State.Strict-import qualified Data.IntMap.Strict as IM-import Data.Massiv.Array as MA hiding (forM_, forM)-import Data.Maybe ( fromJust, isNothing )-import Data.SRTree-import Data.SRTree.Print ( showExpr )-import Options.Applicative as Opt hiding (Const)-import Random-import System.Random-import Data.List ( intercalate )-import qualified Data.IntSet as IntSet-import Algorithm.EqSat (runEqSat)-import Data.Binary ( encode, decode )-import qualified Data.ByteString.Lazy as BS-import Debug.Trace-import qualified Data.HashSet as Set-import Control.Lens (over)-import qualified Data.Map.Strict as Map--import Util--data Alg = OnlyRandom | BestFirst deriving (Show, Read, Eq)--egraphSearch :: [(DataSet, DataSet)] -> [DataSet] -> Args -> StateT EGraph (StateT StdGen IO) ()--- terms nEvals maxSize printPareto printTrace slowIter slowRep =-egraphSearch dataTrainVals dataTests args = do-  if null (_loadFrom args)-    then do ecFst <- insertRndExpr (_maxSize args) rndTerm rndNonTerm2-            --ecFst <- insertBestExpr -- use only to debug-            updateIfNothing fitFun ecFst-            insertTerms-            evaluateUnevaluated fitFun-            runEqSat myCost (if _nParams args == 0 then rewritesWithConstant else rewritesParams) 1-            cleanDB-    else (io $ BS.readFile (_loadFrom args)) >>= \eg -> put (decode eg)-  nCls <- gets (IM.size . _eClass)-  nUnev <- gets (IntSet.size . _unevaluated . _eDB)-  let nEvs = nCls - nUnev--  while ((<(_gens args)) . snd) (10, nEvs) $-    \(radius, nEvs) ->-      do-       nCls  <- gets (IM.size . _eClass)-       --nUnev <- gets (IntSet.size . _unevaluated . _eDB)-       --let nEvs = nCls - nUnev -- WARNING: see if it affects results--       ecN <- case (_alg args) of-                    OnlyRandom -> do let ratio = fromIntegral nEvs / fromIntegral nCls-                                     b <- rnd (tossBiased ratio)-                                     ec <- if b && ratio > 0.99-                                              then insertRndExpr (_maxSize args) rndTerm rndNonTerm2 >>= canonical-                                              else do mEc <- pickRndSubTree -- evaluateRndUnevaluated fitFun >>= canonical-                                                      case mEc of-                                                           Nothing ->insertRndExpr (_maxSize args) rndTerm rndNonTerm2 >>= canonical-                                                           Just ec' -> pure ec'-                                     pure ec-                    BestFirst  -> do-                      ecsPareto <- getParetoEcsUpTo 50 (_maxSize args)-                      ecPareto     <- combineFrom ecsPareto >>= canonical-                      curFitPareto <- getFitness ecPareto--                      if isNothing curFitPareto-                        then pure ecPareto-                        else do ecsBest    <- getTopFitEClassThat 100 (isSizeOf (<(_maxSize args)))-                                ecBest     <- combineFrom ecsBest >>= canonical-                                curFitBest <- getFitness ecBest-                                if isNothing curFitBest-                                  then pure ecBest-                                  else do ee <- pickRndSubTree-                                          case ee of-                                            Nothing -> insertRndExpr (_maxSize args) rndTerm rndNonTerm2 >>= canonical-                                            Just c  -> pure c--       -- when upd $-       ecN' <- canonical ecN-       upd <- updateIfNothing fitFun ecN'-       when upd $ runEqSat myCost (if _nParams args == 0 then rewritesWithConstant else rewritesParams) 1 >> cleanDB >> refitChanged---       when (upd && (_trace args))-         do-            ecN'' <- canonical ecN'-            _tree <- getBestExpr ecN''-            fi <- negate . fromJust <$> getFitness ecN''-            thetas <- getTheta ecN''-            let thetaStr   = intercalate "_" $ Prelude.map (intercalate ";" . Prelude.map show . MA.toList) thetas-            io . putStrLn $ showExpr _tree <> "," <> thetaStr <> "," <> show fi-            pure ()-       let radius' = if (not upd) then (max 10 $ min (500 `div` (_maxSize args)) (radius+1)) else (max 10 $ radius-1)-           nEvs'    = nEvs + if upd then 1 else 0-       pure (radius', nEvs')-  io $ putStrLn csvHeader-  if (_printPareto args)-    then paretoFront (_maxSize args) printExpr-    else printBest printExpr-  when ((not.null) (_dumpTo args)) $ get >>= (io . BS.writeFile (_dumpTo args) . encode )-  where-    maxSize = _maxSize args-    relabel        = if (_nParams args == -1) then relabelParams else relabelParamsOrder-    fitFun = fitnessMV (_optRepeat args) (_optIter args) (_distribution args) dataTrainVals--    refitChanged = do ids <- gets (_refits . _eDB) >>= Prelude.mapM canonical . Set.toList-                      modify' $ over (eDB . refits) (const Set.empty)-                      forM_ ids $ \ec -> do t <- getBestExpr ec-                                            (f, p) <- fitFun t-                                            insertFitness ec f p--    combineFrom [] = pure 0-    combineFrom ecs = do-      p1  <- rnd (randomFrom ecs) >>= canonical-      p2  <- rnd (randomFrom ecs) >>= canonical-      coin <- rnd toss-      if coin-         then crossover p1 p2 >>= canonical-         else mutate p1 >>= canonical--    combineFrom' [] = pure 0 -- this is the first terminal and it will always be already evaluated-    combineFrom' ecs = do-        nt  <- rnd rndNonTerm-        p1  <- rnd (randomFrom ecs)-        p2  <- rnd (randomFrom ecs)-        l1  <- rnd (randomFrom [2..(_maxSize args)-2]) -- sz 10: [2..8]--        e1  <- randomChildFrom p1 l1 >>= canonical-        ml  <- gets (_size . _info . (IM.! e1) . _eClass)-        l2  <- rnd (randomFrom [1..((_maxSize args) - ml - 1)]) -- maxSize - maxSize + 2 - 2= 0 -- sz 10: [1..7] (2) / [1..1] (8)-        e2  <- randomChildFrom p2 l2 >>= canonical-        case nt of-          Uni Id ()    -> canonical e1-          Uni f ()     -> add myCost (Uni f e1) >>= canonical-          Bin op () () -> do b <- rnd toss-                             if b-                              then add myCost (Bin op e1 e2) >>= canonical-                              else add myCost (Bin op e2 e1) >>= canonical-          _            -> canonical e1 -- it is a terminal, should it happen?--    randomChildFrom ec' maxL = do-      p <- rnd toss -- whether to go deeper or return this level-      ec <- canonical ec'-      l <- gets (_size . _info . (IM.! ec) . _eClass )--      if p || l > maxL-          then do --enodes <- gets (_eNodes . (IM.! ec) . _eClass)-                  enode  <- gets (_best . _info . (IM.! ec) . _eClass) -- we should return the best otherwise we may build larger exprs-                  case enode of-                      Uni _ eci     -> randomChildFrom eci maxL-                      Bin _ ecl ecr -> do coin <- rnd toss-                                          if coin-                                            then randomChildFrom ecl maxL-                                            else randomChildFrom ecr maxL-                      _ -> pure ec -- this shouldn't happen unless maxL==0-          else pure ec--    nonTerms   = parseNonTerms (_nonterminals args)-    --[ Bin Add () (), Bin Sub () (), Bin Mul () (), Bin Div () (), Bin PowerAbs () (),  Uni Recip ()]-    (Sz2 _ nFeats) = MA.size (getX . fst . head $ dataTrainVals)-    terms          = if _distribution args == ROXY-                          then [var 0, param 0]-                          else [var ix | ix <- [0 .. nFeats-1]]-                               <> if _nParams args == -1-                                     then [param 0]-                                     else Prelude.map param [0 .. _nParams args - 1]-    rndTerm    = Random.randomFrom terms-    rndNonTerm = Random.randomFrom $ (Uni Id ()) : nonTerms-    rndNonTerm2 = Random.randomFrom nonTerms-    uniNonTerms = Prelude.filter isUni nonTerms-    binNonTerms = Prelude.filter isBin nonTerms-    isUni (Uni _ _) = True-    isUni _         = False-    isBin (Bin _ _ _) = True-    isBin _           = False--    insertTerms =-        forM terms $ \t -> do fromTree myCost t >>= canonical--    printExpr :: Int -> EClassId -> RndEGraph ()-    printExpr ix ec = do -        thetas' <- gets (_theta . _info . (IM.! ec) . _eClass)-        bestExpr <- getBestExpr ec-        let nParams = countParams bestExpr-            fromSz (MA.Sz x) = x -            nThetas = Prelude.map (fromSz . MA.size) thetas'-        (_, thetas) <- if Prelude.any (/=nParams) nThetas-                        then fitFun bestExpr-                        else pure (1.0, thetas')--        forM_ (Prelude.zip3 dataTrainVals dataTests thetas) $ \((dataTrain, dataVal), dataTest, theta) -> do-            let (x, y, mYErr) = dataTrain-                (x_val, y_val, mYErr_val) = dataVal-                (x_te, y_te, mYErr_te) = dataTest-                distribution = _distribution args-                best'     = relabelParams bestExpr-                expr      = paramsToConst (MA.toList theta) best'-                mse_train = mse x y best' theta-                mse_val   = mse x_val y_val best' theta-                mse_te    = mse x_te y_te best' theta-                r2_train  = r2 x y best' theta-                r2_val    = r2 x_val y_val best' theta-                r2_te     = r2 x_te y_te best' theta-                nll_train  = nll distribution mYErr x y best' theta-                nll_val    = nll distribution mYErr_val x_val y_val best' theta-                nll_te     = nll distribution mYErr_te x_te y_te best' theta-                mdl_train  = mdl distribution mYErr x y theta best'-                mdl_val    = mdl distribution mYErr_val x_val y_val theta best'-                mdl_te     = mdl distribution mYErr_te x_te y_te theta best'-                vals       = intercalate ","-                           $ Prelude.map show [mse_train, mse_val, mse_te-                                              , r2_train, r2_val, r2_te-                                              , nll_train, nll_val, nll_te-                                              , mdl_train, mdl_val, mdl_te]-                thetaStr   = intercalate ";" $ Prelude.map show (MA.toList theta)-            io . putStrLn $ show ix <> "," <> showExpr expr <> ","-                          <> thetaStr <> "," <> show (countNodes $ convertProtectedOps expr)-                          <> "," <> vals--    -- From eggp-    crossover p1 p2 = do sz <- getSize p1-                         if sz == 1-                          then rnd (randomFrom [p1, p2])-                          else do pos <- rnd $ randomRange (1, sz-1)-                                  cands <- getAllSubClasses p2-                                  tree <- getSubtree pos 0 Nothing [] cands p1-                                  fromTree myCost (relabel tree) >>= canonical--    getSubtree :: Int -> Int -> Maybe (EClassId -> ENode) -> [Maybe (EClassId -> ENode)] -> [EClassId] -> EClassId -> RndEGraph (Fix SRTree)-    getSubtree 0 sz (Just parent) mGrandParents cands p' = do-      p <- canonical p'-      candidates' <- filterM (\c -> (<maxSize-sz) <$> getSize c) cands-      candidates  <- filterM (\c -> doesNotExistGens mGrandParents (parent c)) candidates'-                        >>= traverse canonical-      if null candidates-          then getBestExpr p-          else do subtree <- rnd (randomFrom candidates)-                  getBestExpr subtree-    getSubtree pos sz parent mGrandParents cands p' = do-      p <- canonical p'-      root <- getBestENode p >>= canonize-      case root of-        Param ix -> pure . Fix $ Param ix-        Const x  -> pure . Fix $ Const x-        Var   ix -> pure . Fix $ Var ix-        Uni f t' -> do t <- canonical t'-                       (Fix . Uni f) <$> getSubtree (pos-1) (sz+1) (Just $ Uni f) (parent:mGrandParents) cands t-        Bin op l'' r'' ->-                      do  l <- canonical l''-                          r <- canonical r''-                          szLft <- getSize l-                          szRgt <- getSize r-                          if szLft < pos-                            then do l' <- getBestExpr l-                                    r' <- getSubtree (pos-szLft-1) (sz+szLft+1) (Just $ Bin op l) (parent:mGrandParents) cands r-                                    pure . Fix $ Bin op l' r'-                            else do l' <- getSubtree (pos-1) (sz+szRgt+1) (Just (\t -> Bin op t r)) (parent:mGrandParents) cands l-                                    r' <- getBestExpr r-                                    pure . Fix $ Bin op l' r'--    getAllSubClasses p' = do-      p  <- canonical p'-      en <- getBestENode p-      case en of-        Bin _ l r -> do ls <- getAllSubClasses l-                        rs <- getAllSubClasses r-                        pure (p : (ls <> rs))-        Uni _ t   -> (p:) <$> getAllSubClasses t-        _         -> pure [p]--    mutate p = do sz <- getSize p-                  pos <- rnd $ randomRange (0, sz-1)-                  tree <- mutAt pos maxSize Nothing p-                  fromTree myCost (relabel tree) >>= canonical--    peel :: Fix SRTree -> SRTree ()-    peel (Fix (Bin op l r)) = Bin op () ()-    peel (Fix (Uni f t)) = Uni f ()-    peel (Fix (Param ix)) = Param ix-    peel (Fix (Var ix)) = Var ix-    peel (Fix (Const x)) = Const x--    mutAt :: Int -> Int -> Maybe (EClassId -> ENode) -> EClassId -> RndEGraph (Fix SRTree)-    mutAt 0 sizeLeft Nothing       _ = (insertRndExpr sizeLeft rndTerm rndNonTerm >>= canonical) >>= getBestExpr -- we chose to mutate the root-    mutAt 0 1        _             _ = rnd $ randomFrom terms -- we don't have size left-    mutAt 0 sizeLeft (Just parent) _ = do -- we reached the mutation place-      ec    <- insertRndExpr sizeLeft rndTerm rndNonTerm >>= canonical -- create a random expression with the size limit-      (Fix tree) <- getBestExpr ec           ---      root  <- getBestENode ec-      exist <- canonize (parent ec) >>= doesExist-      if exist-          -- the expression `parent ec` already exists, try to fix-          then do let children = childrenOf root-                  candidates <- case length children of-                                0  -> filterM (checkToken parent . (replaceChildren children)) (Prelude.map peel terms)-                                1 -> filterM (checkToken parent . (replaceChildren children)) uniNonTerms-                                2 -> filterM (checkToken parent . (replaceChildren children)) binNonTerms-                  if null candidates-                      then pure $ Fix tree -- there's no candidate, so we failed and admit defeat-                      else do newToken <- rnd (randomFrom candidates)-                              pure . Fix $ replaceChildren (childrenOf tree) newToken--          else pure . Fix $ tree--    mutAt pos sizeLeft parent p' = do-        p <- canonical p'-        root <- getBestENode p >>= canonize-        case root of-          Param ix -> pure . Fix $ Param ix-          Const x  -> pure . Fix $ Const x-          Var   ix -> pure . Fix $ Var ix-          Uni f t'  -> canonical t' >>= \t -> (Fix . Uni f) <$> mutAt (pos-1) (sizeLeft-1) (Just $ Uni f) t-          Bin op ln rn -> do  l <- canonical ln-                              r <- canonical rn-                              szLft <- getSize l-                              szRgt <- getSize r-                              if szLft < pos-                                then do l' <- getBestExpr l-                                        r' <- mutAt (pos-szLft-1) (sizeLeft-szLft-1) (Just $ Bin op l) r-                                        pure . Fix $ Bin op l' r'-                                else do l' <- mutAt (pos-1) (sizeLeft-szRgt-1) (Just (\t -> Bin op t r)) l-                                        r' <- getBestExpr r-                                        pure . Fix $ Bin op l' r'--    checkToken parent en' = do  en <- canonize en'-                                mEc <- gets ((Map.!? en) . _eNodeToEClass)-                                case mEc of-                                    Nothing -> pure True-                                    Just ec -> do ec' <- canonical ec-                                                  ec'' <- canonize (parent ec')-                                                  not <$> doesExist ec''-    doesExist, doesNotExist :: ENode -> RndEGraph Bool-    doesExist en = gets ((Map.member en) . _eNodeToEClass)-    doesNotExist en = gets ((Map.notMember en) . _eNodeToEClass)--    doesNotExistGens :: [Maybe (EClassId -> ENode)] -> ENode -> RndEGraph Bool-    doesNotExistGens []              en = gets ((Map.notMember en) . _eNodeToEClass)-    doesNotExistGens (mGrand:grands) en = do  b <- gets ((Map.notMember en) . _eNodeToEClass)-                                              if b-                                                then pure True-                                                else case mGrand of-                                                    Nothing -> pure False-                                                    Just gf -> do ec  <- gets ((Map.! en) . _eNodeToEClass)-                                                                  en' <- canonize (gf ec)-                                                                  doesNotExistGens grands en'--data Args = Args-  { _dataset      :: String,-    _testData     :: String,-    _gens         :: Int,-    _alg          :: Alg,-    _maxSize      :: Int,-    _split        :: Int,-    _printPareto  :: Bool,-    _trace        :: Bool,-    _distribution :: Distribution,-    _optIter      :: Int,-    _optRepeat    :: Int,-    _nParams      :: Int,-    _nonterminals :: String,-    _dumpTo       :: String,-    _loadFrom     :: String-  }-  deriving (Show)---- parser of command line arguments-opt :: Parser Args-opt = Args-   <$> strOption-       ( long "dataset"-       <> short 'd'-       <> metavar "INPUT-FILE"-       <> help "CSV dataset." )-  <*> strOption-       ( long "test"-       <> short 't'-       <> value ""-       <> showDefault-       <> help "test data")-   <*> option auto-      ( long "generations"-      <> short 'g'-      <> metavar "GENS"-      <> showDefault-      <> value 100-      <> help "Number of generations." )-   <*> option auto-       ( long "algorithm"-       <> short 'a'-       <> metavar "ALG"-       <> help "Algorithm." )-  <*> option auto-       ( long "maxSize"-       <> short 's'-       <> help "max-size." )-  <*> option auto-       ( long "split"-       <> short 'k'-       <> value 1 -       <> showDefault-       <> help "k-split ratio training-validation")-  <*> switch-       ( long "print-pareto"-       <> help "print Pareto front instead of best found expression")-  <*> switch-       ( long "trace"-       <> help "print all evaluated expressions.")-  <*> option auto-       ( long "loss"-       <> value MSE-       <> showDefault-       <> help "distribution of the data.")-  <*> option auto-       ( long "opt-iter"-       <> value 30-       <> showDefault-       <> help "number of iterations in parameter optimization.")-  <*> option auto-       ( long "opt-retries"-       <> value 1-       <> showDefault-       <> help "number of retries of parameter fitting.")-  <*> option auto-       ( long "number-params"-       <> value (-1)-       <> showDefault-       <> help "maximum number of parameters in the model. If this argument is absent, the number is bounded by the maximum size of the expression and there will be no repeated parameter.")-  <*> strOption-       ( long "non-terminals"-       <> value "Add,Sub,Mul,Div,PowerAbs,Recip"-       <> showDefault-       <> help "set of non-terminals to use in the search."-       )-  <*> strOption-       ( long "dump-to"-       <> value ""-       <> showDefault-       <> help "dump final e-graph to a file."-       )-  <*> strOption-       ( long "load-from"-       <> value ""-       <> showDefault-       <> help "load initial e-graph from a file."-       )--main :: IO ()-main = do-  args <- execParser opts-  g    <- getStdGen-  let datasets = words (_dataset args)-  dataTrains' <- Prelude.mapM (flip loadTrainingOnly True) datasets -- load all datasets -  dataTests   <- if null (_testData args)-                  then pure dataTrains'-                  else Prelude.mapM (flip loadTrainingOnly True) $ words (_testData args)--  let (dataTrainVals, g') = runState (Prelude.mapM (`splitData` (_split args)) dataTrains') g-      alg = evalStateT (egraphSearch dataTrainVals dataTests args) emptyGraph-  evalStateT alg g'--  where-    opts = Opt.info (opt <**> helper)-            ( fullDesc <> progDesc "Symbolic Regression search algorithm\-                                   \ exploiting the potentials of equality saturation\-                                   \ and e-graphs."-           <> header "SymRegg - symbolic regression with e-graphs."-            )
− apps/symregg/Random.hs
@@ -1,54 +0,0 @@-module Random where --import System.Random -import Control.Monad.State.Strict-import Control.Monad-import Data.SRTree -import Data.SRTree.Eval-import Data.Massiv.Array as MA--type Rng a = StateT StdGen IO a --toss :: Rng Bool-toss = state random-{-# INLINE toss #-}--tossBiased :: Double -> Rng Bool-tossBiased p = do r <- state random -                  pure (r < p)--randomVal :: Rng Double-randomVal = state random--randomRange :: (Ord val, Random val) => (val, val) -> Rng val-randomRange rng = state (randomR rng)-{-# INLINE randomRange #-}--randomFrom :: [a] -> Rng a-randomFrom funs = do n <- randomRange (0, length funs - 1)-                     pure $ funs !! n-{-# INLINE randomFrom #-}--randomVec :: Int -> Rng PVector-randomVec n = MA.fromList compMode <$> replicateM n (randomRange (-1, 1))--randomTree :: Int -> Int -> Int -> Rng (Fix SRTree) -> Rng (SRTree ()) -> Bool -> Rng (Fix SRTree)-randomTree minDepth maxDepth maxSize genTerm genNonTerm grow -  | noSpaceLeft = genTerm-  | needNonTerm = genRecursion -  | otherwise   = do r <- toss-                     if r -                       then genTerm -                       else genRecursion-  where -    noSpaceLeft = maxDepth <= 1 || maxSize <= 2-    needNonTerm = (minDepth >= 0 || (maxDepth > 2 && not grow)) -- && maxSize > 2--    genRecursion = do -        node <- genNonTerm-        case node of -          Uni f _    -> Fix . Uni f <$> randomTree (minDepth - 1) (maxDepth - 1) (maxSize - 1) genTerm genNonTerm grow -          Bin op _ _ -> do l <- randomTree (minDepth - 1) (maxDepth - 1) (if grow then maxSize - 2 else maxSize `div` 2) genTerm genNonTerm grow-                           r <- randomTree (minDepth - 1) (maxDepth - 1) (maxSize - 1 - countNodes l) genTerm genNonTerm grow -                           pure . Fix  $ Bin op l r-{-# INLINE randomTree #-}
− apps/symregg/Util.hs
@@ -1,255 +0,0 @@-{-# LANGUAGE  BlockArguments #-}-{-# LANGUAGE  TupleSections #-}--module Util where--import qualified Data.Map.Strict as Map-import Data.Massiv.Array as MA hiding (forM_, forM)-import Data.SRTree-import Data.SRTree.Eval-import Algorithm.SRTree.Opt-import Algorithm.EqSat.Egraph-import Algorithm.EqSat.Build-import Algorithm.EqSat.Info--import Algorithm.SRTree.NonlinearOpt-import System.Random-import Random-import Algorithm.SRTree.Likelihoods---import Algorithm.SRTree.ModelSelection---import Algorithm.SRTree.Opt-import qualified Data.IntMap.Strict as IM-import Control.Monad.State.Strict-import Control.Monad ( when, replicateM, forM, forM_, filterM )-import Data.Maybe ( fromJust )-import Data.List ( maximumBy )-import Data.Function ( on )-import List.Shuffle ( shuffle )-import Data.List.Split ( splitOn )-import Data.Char ( toLower )-import qualified Data.IntSet as IntSet-import Data.SRTree.Datasets-import Algorithm.EqSat.Queries--type RndEGraph a = EGraphST (StateT StdGen IO) a-type DataSet = (SRMatrix, PVector, Maybe PVector)--csvHeader :: String-csvHeader = "id,Expression,theta,size,MSE_train,MSE_val,MSE_test,R2_train,R2_val,R2_test,nll_train,nll_val,nll_test,mdl_train,mdl_val,mdl_test"--io :: IO a -> RndEGraph a-io = lift . lift-{-# INLINE io #-}-rnd :: StateT StdGen IO a -> RndEGraph a-rnd = lift-{-# INLINE rnd #-}--myCost :: SRTree Int -> Int-myCost (Var _)     = 1-myCost (Const _)   = 1-myCost (Param _)   = 1-myCost (Bin _ l r) = 2 + l + r-myCost (Uni _ t)   = 3 + t--while :: Monad f => (t -> Bool) -> t -> (t -> f t) -> f ()-while p arg prog = do when (p arg) do arg' <- prog arg-                                      while p arg' prog--fitnessFun :: Int -> Distribution -> DataSet -> DataSet -> Fix SRTree -> PVector -> (Double, PVector)-fitnessFun nIter distribution (x, y, mYErr) (x_val, y_val, mYErr_val) _tree thetaOrig =-  if isNaN val || isNaN tr-    then (-(1/0), theta) -- infinity-    else (val, theta) -- (min tr val, theta)-  where-    tree          = relabelParams _tree-    nParams       = countParams tree + if distribution == ROXY then 3 else if distribution == Gaussian then 1 else 0-    (theta, _, _) = minimizeNLL' VAR1 distribution mYErr nIter x y tree thetaOrig-    evalF a b c   = negate $ nll distribution c a b tree $ if nParams == 0 then thetaOrig else theta-    tr            = evalF x y mYErr-    val           = evalF x_val y_val mYErr_val--{-# INLINE fitnessFun #-}--fitnessFunRep :: Int -> Int -> Distribution -> DataSet -> DataSet -> Fix SRTree -> RndEGraph (Double, PVector)-fitnessFunRep nRep nIter distribution dataTrain dataVal _tree = do-    let tree = relabelParams _tree-        nParams = countParams tree + if distribution == ROXY then 3 else if distribution == Gaussian then 1 else 0-    thetaOrigs <- replicateM nRep (rnd $ randomVec nParams)-    let fits = Prelude.map (fitnessFun nIter distribution dataTrain dataVal _tree) thetaOrigs-    pure (maximumBy (compare `on` fst) fits)-{-# INLINE fitnessFunRep #-}--fitnessMV :: Int -> Int -> Distribution -> [(DataSet, DataSet)] -> Fix SRTree -> RndEGraph (Double, [PVector])-fitnessMV nRep nIter distribution dataTrainsVals _tree = do-  response <- forM dataTrainsVals $ \(dt, dv) -> fitnessFunRep nRep nIter distribution dt dv _tree-  pure (minimum (Prelude.map fst response), Prelude.map snd response)---- helper query functions--- TODO: move to egraph lib-getFitness :: EClassId -> RndEGraph (Maybe Double)-getFitness c = gets (_fitness . _info . (IM.! c) . _eClass)-{-# INLINE getFitness #-}-getTheta :: EClassId -> RndEGraph [PVector]-getTheta c = gets (_theta . _info . (IM.! c) . _eClass)-{-# INLINE getTheta #-}-getSize :: EClassId -> RndEGraph Int-getSize c = gets (_size . _info . (IM.! c) . _eClass)-{-# INLINE getSize #-}-isSizeOf :: (Int -> Bool) -> EClass -> Bool-isSizeOf p = p . _size . _info-{-# INLINE isSizeOf #-}--getBestFitness :: RndEGraph (Maybe Double)-getBestFitness = do-    bec <- (gets (snd . getGreatest . _fitRangeDB . _eDB) >>= canonical)-    gets (_fitness . _info . (IM.! bec) . _eClass)---- TODO: move to dataset lib-chunksOf :: Int -> [e] -> [[e]]-chunksOf i ls = Prelude.map (Prelude.take i) (build (splitter ls))- where-  splitter :: [e] -> ([e] -> a -> a) -> a -> a-  splitter [] _ n = n-  splitter l c n = l `c` splitter (Prelude.drop i l) c n-  build :: ((a -> [a] -> [a]) -> [a] -> [a]) -> [a]-  build g = g (:) []--splitData :: DataSet ->Int -> State StdGen (DataSet, DataSet)-splitData (x, y, mYErr) k = do-  if k == 1-    then pure ((x, y, mYErr), (x, y, mYErr))-    else do-      ixs' <- (state . shuffle) [0 .. sz-1]-      let ixs = chunksOf k ixs'--      let (x_tr, x_te) = getX ixs x-          (y_tr, y_te) = getY ixs y-          mY = fmap (getY ixs) mYErr-          (y_err_tr, y_err_te) = (fmap fst mY, fmap snd mY)-      pure ((x_tr, y_tr, y_err_tr), (x_te, y_te, y_err_te))-  where-    (MA.Sz sz) = MA.size y-    comp_x     = MA.getComp x-    comp_y     = MA.getComp y--    getX :: [[Int]] -> SRMatrix -> (SRMatrix, SRMatrix)-    getX ixs xs' = let xs = MA.toLists xs' :: [MA.ListItem MA.Ix2 Double]-                    in ( MA.fromLists' comp_x [xs !! ix | ixs_i <- ixs, ix <- Prelude.tail ixs_i]-                       , MA.fromLists' comp_x [xs !! ix | ixs_i <- ixs, let ix = Prelude.head ixs_i]-                       )-    getY :: [[Int]] -> PVector -> (PVector, PVector)-    getY ixs ys  = ( MA.fromList comp_y [ys MA.! ix | ixs_i <- ixs, ix <- Prelude.tail ixs_i]-                   , MA.fromList comp_y [ys MA.! ix | ixs_i <- ixs, let ix = Prelude.head ixs_i]-                   )--getTrain :: ((a, b1, c1, d1), (c2, b2), c3, d2) -> (a, b1, c2)-getTrain ((a, b, _, _), (c, _), _, _) = (a,b,c)--getX :: DataSet -> SRMatrix-getX (a, _, _) = a--getTarget :: DataSet -> PVector-getTarget (_, b, _) = b--getError :: DataSet -> Maybe PVector-getError (_, _, c) = c--loadTrainingOnly fname b = getTrain <$> loadDataset fname b--parseNonTerms :: String -> [SRTree ()]-parseNonTerms = Prelude.map toNonTerm . splitOn ","-  where-    binTerms = Map.fromList [ (Prelude.map toLower (show op), op) | op <- [Add .. AQ]]-    uniTerms = Map.fromList [ (Prelude.map toLower (show f), f) | f <- [Abs .. Cube]]-    toNonTerm xs' = let xs = Prelude.map toLower xs'-                    in case binTerms Map.!? xs of-                          Just op -> Bin op () ()-                          Nothing -> case uniTerms Map.!? xs of-                                          Just f -> Uni f ()-                                          Nothing -> error $ "invalid non-terminal " <> show xs---- RndEGraph utils--- fitFun fitnessFunRep rep iter distribution x y mYErr x_val y_val mYErr_val-insertExpr :: Fix SRTree -> (Fix SRTree -> RndEGraph (Double, [PVector])) -> RndEGraph EClassId-insertExpr t fitFun = do-    ecId <- fromTree myCost t >>= canonical-    (f, p) <- fitFun t-    insertFitness ecId f p-    io . putStrLn $ "Best fit global: " <> show f-    pure ecId-  where powabs l r  = Fix (Bin PowerAbs l r)--updateIfNothing fitFun ec = do-      mf <- getFitness ec-      case mf of-        Nothing -> do-          t <- getBestExpr ec-          (f, p) <- fitFun t-          insertFitness ec f p-          pure True-        Just _ -> pure False--pickRndSubTree :: RndEGraph (Maybe EClassId)-pickRndSubTree = do ecIds <- gets (IntSet.toList . _unevaluated . _eDB)-                    if not (null ecIds)-                          then do rndId' <- rnd $ randomFrom ecIds-                                  rndId  <- canonical rndId'-                                  constType <- gets (_consts . _info . (IM.! rndId) . _eClass)-                                  case constType of-                                    NotConst -> pure $ Just rndId-                                    _        -> pure Nothing-                          else pure Nothing--getParetoEcsUpTo n maxSize = concat <$> forM [1..maxSize] (\i -> getTopFitEClassWithSize i n)--getBestExprWithSize n =-        do ec <- getTopFitEClassWithSize n 1 >>= traverse canonical-           if (not (null ec))-            then do-              bestFit <- getFitness $ head ec-              bestP   <- gets (_theta . _info . (IM.! (head ec)) . _eClass)-              (:[]) . (,bestP) . (,bestFit) . (,ec) <$> getBestExpr (head ec)-            else pure []--insertRndExpr maxSize rndTerm rndNonTerm =-      do grow <- rnd toss-         n <- rnd (randomFrom [if maxSize > 4 then 4 else 1 .. maxSize])-         t <- rnd $ Random.randomTree 3 8 n rndTerm rndNonTerm grow-         fromTree myCost t >>= canonical--printBest :: (Int -> EClassId -> RndEGraph ()) -> RndEGraph ()-printBest printExprFun = do-      bec <- gets (snd . getGreatest . _fitRangeDB . _eDB) >>= canonical-      printExprFun 0 bec--paretoFront :: Int -> (Int -> EClassId -> RndEGraph ()) -> RndEGraph ()-paretoFront maxSize printExprFun = go 1 0 (-(1.0/0.0))-    where-    go :: Int -> Int -> Double -> RndEGraph ()-    go n ix f-        | n > maxSize = pure ()-        | otherwise   = do-            ecList <- getBestExprWithSize n-            if not (null ecList)-                then do let (((_, ec), mf), _) = head ecList-                            improved = fromJust mf > f-                        ec' <- traverse canonical ec-                        when improved $ printExprFun ix (head ec')-                        go (n+1) (ix + if improved then 1 else 0) (max f (fromJust mf))-                else go (n+1) ix f--evaluateUnevaluated fitFun = do-          ec <- gets (IntSet.toList . _unevaluated . _eDB)-          forM_ ec $ \c -> do-              t <- getBestExpr c-              (f, p) <- fitFun t-              insertFitness c f p--evaluateRndUnevaluated fitFun = do-          ec <- gets (IntSet.toList . _unevaluated . _eDB)-          c <- rnd . randomFrom $ ec-          t <- getBestExpr c-          (f, p) <- fitFun t-          insertFitness c f p-          pure c-
apps/tinygp/Main.hs view
@@ -9,6 +9,7 @@ import Data.Massiv.Array  import Util import Algorithm.SRTree.Likelihoods+import Data.SRTree.Datasets  -- Data type to store command line arguments data Args = Args
apps/tinygp/Util.hs view
@@ -31,6 +31,7 @@ import Algorithm.EqSat.Queries  +    {- type DataSet = (SRMatrix, PVector, Maybe PVector)  @@ -47,7 +48,7 @@ getError (_, _, c) = c  loadTrainingOnly fname b = getTrain <$> loadDataset fname b-+-}  parseNonTerms = Prelude.map toNonTerm . splitOn ","   where
src/Algorithm/EqSat/Egraph.hs view
@@ -335,3 +335,23 @@                    ConstVal _ -> pure True                    _          -> pure False {-# INLINE isConst #-}++getFitness :: Monad m => EClassId -> EGraphST m (Maybe Double)+getFitness c = gets (_fitness . _info . (IntMap.! c) . _eClass)+{-# INLINE getFitness #-}+getTheta :: Monad m => EClassId -> EGraphST m ([PVector])+getTheta c = gets (_theta . _info . (IntMap.! c) . _eClass)+{-# INLINE getTheta #-}+getSize :: Monad m => EClassId -> EGraphST m Int+getSize c = gets (_size . _info . (IntMap.! c) . _eClass)+{-# INLINE getSize #-}+isSizeOf :: (Int -> Bool) -> EClass -> Bool+isSizeOf p = p . _size . _info+{-# INLINE isSizeOf #-}+getBestFitness :: Monad m => EGraphST m (Maybe Double)+getBestFitness = do+    bec <- (gets (snd . getGreatest . _fitRangeDB . _eDB) >>= canonical)+    gets (_fitness . _info . (IntMap.! bec) . _eClass)+getDL :: Monad m => EClassId -> EGraphST m (Maybe Double)+getDL c = gets (_dl . _info . (IntMap.! c) . _eClass)+{-# INLINE getDL #-}
+ src/Algorithm/EqSat/SearchSR.hs view
@@ -0,0 +1,220 @@+-----------------------------------------------------------------------------+-- |+-- Module      :  Algorithm.EqSat.Search+-- Copyright   :  (c) Fabricio Olivetti 2021 - 2024+-- License     :  BSD3+-- Maintainer  :  fabricio.olivetti@gmail.com+-- Stability   :  experimental+-- Portability :+--+-- Support functions for search symbolic expressions with e-graphs+--+-----------------------------------------------------------------------------++module Algorithm.EqSat.SearchSR where++import Data.SRTree+import Data.SRTree.Datasets+import System.Random+import Control.Monad.State.Strict+import Algorithm.EqSat.Egraph+import Algorithm.SRTree.Likelihoods+import qualified Data.IntMap as IM+import qualified Data.IntSet as IntSet+import qualified Data.SRTree.Random as Random+import Data.Function ( on )+import Algorithm.SRTree.Likelihoods+import Algorithm.SRTree.NonlinearOpt+import Control.Monad ( when, replicateM, forM, forM_ )+import Algorithm.EqSat.Egraph+import Algorithm.SRTree.Opt+import Algorithm.EqSat.Info+import Algorithm.EqSat.Build+import Data.Maybe ( fromJust )+import Data.SRTree.Random+import Algorithm.EqSat.Queries+import Data.List ( maximumBy )+import qualified Data.Map.Strict as Map++-- Environment of an e-graph with support to random generator and IO+type RndEGraph a = EGraphST (StateT StdGen IO) a++io :: IO a -> RndEGraph a+io = lift . lift+{-# INLINE io #-}+rnd :: StateT StdGen IO a -> RndEGraph a+rnd = lift+{-# INLINE rnd #-}++myCost :: SRTree Int -> Int+myCost (Var _)     = 1+myCost (Const _)   = 1+myCost (Param _)   = 1+myCost (Bin _ l r) = 2 + l + r+myCost (Uni _ t)   = 3 + t++while :: Monad f => (t -> Bool) -> t -> (t -> f t) -> f t+while p arg prog = do if (p arg)+                      then do arg' <- prog arg+                              while p arg' prog+                      else pure arg++fitnessFun :: Int -> Distribution -> DataSet -> DataSet -> Fix SRTree -> PVector -> (Double, PVector)+fitnessFun nIter distribution (x, y, mYErr) (x_val, y_val, mYErr_val) tree thetaOrig =+  if isNaN val -- || isNaN tr+    then (-(1/0), theta) -- infinity+    else (val, theta)+  where+    --tree          = relabelParams _tree+    nParams       = countParamsUniq tree + if distribution == ROXY then 3 else if distribution == Gaussian then 1 else 0+    (theta, _, _) = minimizeNLL' VAR1 distribution mYErr nIter x y tree thetaOrig+    evalF a b c   = negate $ nll distribution c a b tree $ if nParams == 0 then thetaOrig else theta+    --tr            = evalF x y mYErr+    val           = evalF x_val y_val mYErr_val++--{-# INLINE fitnessFun #-}++fitnessFunRep :: Int -> Int -> Distribution -> DataSet -> DataSet -> Fix SRTree -> RndEGraph (Double, PVector)+fitnessFunRep nRep nIter distribution dataTrain dataVal tree = do+    let nParams = countParamsUniq tree + if distribution == ROXY then 3 else if distribution == Gaussian then 1 else 0+    thetaOrigs <- replicateM nRep (rnd $ randomVec nParams)+    let fits = maximumBy (compare `on` fst) $ Prelude.map (fitnessFun nIter distribution dataTrain dataVal tree) thetaOrigs+    pure fits+--{-# INLINE fitnessFunRep #-}+++fitnessMV :: Bool -> Int -> Int -> Distribution -> [(DataSet, DataSet)] -> Fix SRTree -> RndEGraph (Double, [PVector])+fitnessMV shouldReparam nRep nIter distribution dataTrainsVals _tree = do+  let tree = if shouldReparam then relabelParams _tree else relabelParamsOrder _tree+  response <- forM dataTrainsVals $ \(dt, dv) -> fitnessFunRep nRep nIter distribution dt dv tree+  pure (minimum (Prelude.map fst response), Prelude.map snd response)++++++-- RndEGraph utils+-- fitFun fitnessFunRep rep iter distribution x y mYErr x_val y_val mYErr_val+insertExpr :: Fix SRTree -> (Fix SRTree -> RndEGraph (Double, [PVector])) -> RndEGraph EClassId+insertExpr t fitFun = do+    ecId <- fromTree myCost t >>= canonical+    (f, p) <- fitFun t+    insertFitness ecId f p+    pure ecId+  where powabs l r  = Fix (Bin PowerAbs l r)++updateIfNothing fitFun ec = do+      mf <- getFitness ec+      case mf of+        Nothing -> do+          t <- getBestExpr ec+          (f, p) <- fitFun t+          insertFitness ec f p+          pure True+        Just _ -> pure False++pickRndSubTree :: RndEGraph (Maybe EClassId)+pickRndSubTree = do ecIds <- gets (IntSet.toList . _unevaluated . _eDB)+                    if not (null ecIds)+                          then do rndId' <- rnd $ randomFrom ecIds+                                  rndId  <- canonical rndId'+                                  constType <- gets (_consts . _info . (IM.! rndId) . _eClass)+                                  case constType of+                                    NotConst -> pure $ Just rndId+                                    _        -> pure Nothing+                          else pure Nothing++getParetoEcsUpTo n maxSize = concat <$> forM [1..maxSize] (\i -> getTopFitEClassWithSize i n)+getParetoDLEcsUpTo n maxSize = concat <$> forM [1..maxSize] (\i -> getTopDLEClassWithSize i n)++getBestExprWithSize n =+        do ec <- getTopFitEClassWithSize n 1 >>= traverse canonical+           if (not (null ec))+            then do+              bestFit <- getFitness $ head ec+              bestP   <- gets (_theta . _info . (IM.! (head ec)) . _eClass)+              pure [(head ec, bestFit)]+            else pure []++insertRndExpr maxSize rndTerm rndNonTerm =+      do grow <- rnd toss+         n <- rnd (randomFrom [if maxSize > 4 then 4 else 1 .. maxSize])+         t <- rnd $ Random.randomTree 3 8 n rndTerm rndNonTerm grow+         fromTree myCost t >>= canonical++refit fitFun ec = do+  t <- getBestExpr ec+  (f, p) <- fitFun t+  insertFitness ec f p++--printBest :: (Int -> EClassId -> RndEGraph ()) -> RndEGraph ()+printBest fitFun printExprFun = do+      bec <- gets (snd . getGreatest . _fitRangeDB . _eDB) >>= canonical+      bestFit <- gets (_fitness. _info . (IM.! bec) . _eClass)+      --refit fitFun bec+      --io.print $ "should be " <> show bestFit+      printExprFun 0 bec++--paretoFront :: Int -> (Int -> EClassId -> RndEGraph ()) -> RndEGraph ()+paretoFront fitFun maxSize printExprFun = go 1 0 (-(1.0/0.0))+    where+    go :: Int -> Int -> Double -> RndEGraph [[String]]+    go n ix f+        | n > maxSize = pure []+        | otherwise   = do+            ecList <- getBestExprWithSize n+            if not (null ecList)+                then do let (ec, mf) = head ecList+                            f' = fromJust mf+                            improved = f' > f && (not . isNaN) f' && (not . isInfinite) f'+                        ec' <- canonical ec+                        if improved+                                then do refit fitFun ec'+                                        t <- printExprFun ix ec'+                                        ts <- go (n+1) (ix + if improved then 1 else 0) (max f (fromJust mf))+                                        pure (t:ts)+                                else go (n+1) (ix + if improved then 1 else 0) (max f (fromJust mf))+                else go (n+1) ix f++evaluateUnevaluated fitFun = do+          ec <- gets (IntSet.toList . _unevaluated . _eDB)+          forM_ ec $ \c -> do+              t <- getBestExpr c+              (f, p) <- fitFun t+              insertFitness c f p++evaluateRndUnevaluated fitFun = do+          ec <- gets (IntSet.toList . _unevaluated . _eDB)+          c <- rnd . randomFrom $ ec+          t <- getBestExpr c+          (f, p) <- fitFun t+          insertFitness c f p+          pure c++-- | check whether an e-node exists or does not exist in the e-graph+doesExist, doesNotExist :: ENode -> RndEGraph Bool+doesExist en = gets ((Map.member en) . _eNodeToEClass)+doesNotExist en = gets ((Map.notMember en) . _eNodeToEClass)++-- | check whether the partial tree defined by a list of ancestors will create+-- a non-existent expression when combined with a certain e-node.+doesNotExistGens :: [Maybe (EClassId -> ENode)] -> ENode -> RndEGraph Bool+doesNotExistGens []              en = gets ((Map.notMember en) . _eNodeToEClass)+doesNotExistGens (mGrand:grands) en = do  b <- gets ((Map.notMember en) . _eNodeToEClass)+                                          if b+                                            then pure True+                                            else case mGrand of+                                                Nothing -> pure False+                                                Just gf -> do ec  <- gets ((Map.! en) . _eNodeToEClass)+                                                              en' <- canonize (gf ec)+                                                              doesNotExistGens grands en'++-- | check whether combining a partial tree `parent` with the e-node `en'`+-- will create a new expression+checkToken parent en' = do  en <- canonize en'+                            mEc <- gets ((Map.!? en) . _eNodeToEClass)+                            case mEc of+                                Nothing -> pure True+                                Just ec -> do ec' <- canonical ec+                                              ec'' <- canonize (parent ec')+                                              not <$> doesExist ec''
src/Data/SRTree/Datasets.hs view
@@ -14,7 +14,7 @@ -- this module exports only the `loadDataset` function. -- ------------------------------------------------------------------------------module Data.SRTree.Datasets ( loadDataset )+module Data.SRTree.Datasets ( loadDataset, loadTrainingOnly, getX, splitData, DataSet(..) )     where  import Codec.Compression.GZip (decompress)@@ -35,7 +35,15 @@ import Data.Vector qualified as V import System.FilePath (takeExtension) import Text.Read (readMaybe)+import Data.Massiv.Array as MA hiding (forM_, forM, map, take, tail, zip, replicate, all, read)+import Control.Monad.State.Strict+import System.Random+import List.Shuffle ( shuffle ) ++-- a dataset is a triple (X, y, y_error)+type DataSet = (SRMatrix, PVector, Maybe PVector)+ -- | Loads a list of list of bytestrings to a matrix of double loadMtx :: [[B.ByteString]] -> Array S Ix2 Double loadMtx = M.fromLists' compMode . map (map (read . B.unpack))@@ -221,3 +229,53 @@     y_err_val   = if iy_err == -1 then Nothing else Just $ M.computeAs S $ M.throwEither $ M.deleteColumnsM st (Sz1 $ end - st + 1) y_err {-# inline processData #-} +chunksOf :: Int -> [e] -> [[e]]+chunksOf i ls = Prelude.map (Prelude.take i) (build (splitter ls))+ where+  splitter :: [e] -> ([e] -> a -> a) -> a -> a+  splitter [] _ n = n+  splitter l c n = l `c` splitter (Prelude.drop i l) c n+  build :: ((a -> [a] -> [a]) -> [a] -> [a]) -> [a]+  build g = g (:) []++splitData :: DataSet ->Int -> State StdGen (DataSet, DataSet)+splitData (x, y, mYErr) k = do+  if k == 1+    then pure ((x, y, mYErr), (x, y, mYErr))+    else do+      ixs' <- (state . shuffle) [0 .. sz-1]+      let ixs = chunksOf k ixs'++      let (x_tr, x_te) = getX ixs x+          (y_tr, y_te) = getY ixs y+          mY = fmap (getY ixs) mYErr+          (y_err_tr, y_err_te) = (fmap fst mY, fmap snd mY)+      pure ((x_tr, y_tr, y_err_tr), (x_te, y_te, y_err_te))+  where+    (MA.Sz sz) = MA.size y+    comp_x     = MA.getComp x+    comp_y     = MA.getComp y++    getX :: [[Int]] -> SRMatrix -> (SRMatrix, SRMatrix)+    getX ixs xs' = let xs = MA.toLists xs' :: [MA.ListItem MA.Ix2 Double]+                    in ( MA.fromLists' comp_x [xs !! ix | ixs_i <- ixs, ix <- Prelude.tail ixs_i]+                       , MA.fromLists' comp_x [xs !! ix | ixs_i <- ixs, let ix = Prelude.head ixs_i]+                       )+    getY :: [[Int]] -> PVector -> (PVector, PVector)+    getY ixs ys  = ( MA.fromList comp_y [ys MA.! ix | ixs_i <- ixs, ix <- Prelude.tail ixs_i]+                   , MA.fromList comp_y [ys MA.! ix | ixs_i <- ixs, let ix = Prelude.head ixs_i]+                   )++getTrain :: ((a, b1, c1, d1), (c2, b2), c3, d2) -> (a, b1, c2)+getTrain ((a, b, _, _), (c, _), _, _) = (a,b,c)++getX :: DataSet -> SRMatrix+getX (a, _, _) = a++getTarget :: DataSet -> PVector+getTarget (_, b, _) = b++getError :: DataSet -> Maybe PVector+getError (_, _, c) = c++loadTrainingOnly fname b = getTrain <$> loadDataset fname b
src/Data/SRTree/Random.hs view
@@ -18,14 +18,22 @@          , HasEverything          , FullParams(..)          , RndTree+         , Rng(..)          , randomVar          , randomConst          , randomPow          , randomFunction          , randomNode          , randomNonTerminal+         , randomRange+         , randomTreeTemplate          , randomTree          , randomTreeBalanced+         , toss+         , tossBiased+         , randomVal+         , randomVec+         , randomFrom          )          where @@ -34,7 +42,11 @@ import Data.Maybe (fromJust) import Data.SRTree.Internal import System.Random (Random (random, randomR), StdGen, mkStdGen)+import Data.Massiv.Array as MA hiding (forM_, forM, P)+import Data.SRTree.Eval+import Control.Monad + -- * Class definition of properties that a certain parameter type has. -- -- HasVars: does `p` provides a list of the variable indices?@@ -65,11 +77,20 @@ instance HasFuns FullParams where   _funs (P _ _ _ fs) = fs +type Rng a = StateT StdGen IO a+ -- auxiliary function to sample between False and True toss :: StateT StdGen IO Bool toss = state random {-# INLINE toss #-} +tossBiased :: Double -> Rng Bool+tossBiased p = do r <- state random+                  pure (r < p)++randomVal :: Rng Double+randomVal = state random+ -- returns a random element of a list randomFrom :: [a] -> StateT StdGen IO a randomFrom funs = do n <- randomRange (0, length funs - 1)@@ -152,18 +173,18 @@ -- >>> tree <- evalStateT treeGen (mkStdGen 52) -- >>> showExpr tree -- "(-2.7631152121655838 / Exp((x0 / ((x0 * -7.681722660704317) - Log(3.378309080134594)))))"-randomTree :: HasEverything p => Int -> RndTree p-randomTree 0      = do+randomTreeTemplate :: HasEverything p => Int -> RndTree p+randomTreeTemplate 0      = do   coin <- lift toss   if coin     then randomVar     else randomConst-randomTree budget = do +randomTreeTemplate budget = do   node  <- randomNode   fromJust <$> case arity node of     0 -> pure $ Just node-    1 -> replaceChild node <$> randomTree (budget - 1)-    2 -> replaceFixChildren node <$> randomTree (budget `div` 2) <*> randomTree (budget `div` 2)+    1 -> replaceChild node <$> randomTreeTemplate (budget - 1)+    2 -> replaceFixChildren node <$> randomTreeTemplate (budget `div` 2) <*> randomTreeTemplate (budget `div` 2)      -- | Returns a random tree with a approximately a number `n` of nodes, the parameter `p` must have every property. --@@ -182,3 +203,28 @@   fromJust <$> case arity node of     1 -> replaceChild node <$> randomTreeBalanced (n - 1)     2 -> replaceFixChildren node <$> randomTreeBalanced (n `div` 2) <*> randomTreeBalanced (n `div` 2)    +++randomVec :: Int -> Rng PVector+randomVec n = MA.fromList compMode <$> replicateM n (randomRange (-1, 1))++randomTree :: Int -> Int -> Int -> Rng (Fix SRTree) -> Rng (SRTree ()) -> Bool -> Rng (Fix SRTree)+randomTree minDepth maxDepth maxSize genTerm genNonTerm grow+  | noSpaceLeft = genTerm+  | needNonTerm = genRecursion+  | otherwise   = do r <- toss+                     if r+                       then genTerm+                       else genRecursion+  where+    noSpaceLeft = maxDepth <= 1 || maxSize <= 2+    needNonTerm = (minDepth >= 0 || (maxDepth > 2 && not grow)) -- && maxSize > 2++    genRecursion = do+        node <- genNonTerm+        case node of+          Uni f _    -> Fix . Uni f <$> randomTree (minDepth - 1) (maxDepth - 1) (maxSize - 1) genTerm genNonTerm grow+          Bin op _ _ -> do l <- randomTree (minDepth - 1) (maxDepth - 1) (if grow then maxSize - 2 else maxSize `div` 2) genTerm genNonTerm grow+                           r <- randomTree (minDepth - 1) (maxDepth - 1) (maxSize - 1 - countNodes l) genTerm genNonTerm grow+                           pure . Fix  $ Bin op l r+{-# INLINE randomTree #-}
src/Text/ParseSR.hs view
@@ -11,7 +11,7 @@ -- Functions to parse a string representing an expression -- ------------------------------------------------------------------------------module Text.ParseSR ( parseSR, parsePat, showOutput, SRAlgs(..), Output(..) )+module Text.ParseSR ( parseSR, parsePat, parseNonTerms, showOutput, SRAlgs(..), Output(..) )     where  import Control.Applicative ((<|>))@@ -23,6 +23,9 @@ import Data.SRTree import Algorithm.EqSat.DB import qualified Data.SRTree.Print as P+import qualified Data.Map.Strict as Map+import Data.List.Split ( splitOn )+ import Debug.Trace (trace)  -- * Data types@@ -383,3 +386,17 @@      getParserVar k v = (string k <|> enveloped k) >> pure (Fix $ Var v)     enveloped s      = (char ' ' <|> char '(') >> string s >> (char ' ' <|> char ')') >> pure ""+++-- * Parse the non-terminal nodes into a SRTree () value+parseNonTerms :: String -> [SRTree ()]+parseNonTerms = Prelude.map toNonTerm . splitOn ","+  where+    binTerms = Map.fromList [ (Prelude.map toLower (show op), op) | op <- [Add .. AQ]]+    uniTerms = Map.fromList [ (Prelude.map toLower (show f), f) | f <- [Abs .. Cube]]+    toNonTerm xs' = let xs = Prelude.map toLower xs'+                    in case binTerms Map.!? xs of+                          Just op -> Bin op () ()+                          Nothing -> case uniTerms Map.!? xs of+                                          Just f -> Uni f ()+                                          Nothing -> error $ "invalid non-terminal " <> show xs
srtree.cabal view
@@ -5,7 +5,7 @@ -- see: https://github.com/sol/hpack  name:           srtree-version:        2.0.1.2+version:        2.0.1.4 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; category:       Math, Data, Data Structures@@ -33,6 +33,7 @@       Algorithm.EqSat.Egraph       Algorithm.EqSat.Info       Algorithm.EqSat.Queries+      Algorithm.EqSat.SearchSR       Algorithm.EqSat.Simplify       Algorithm.Massiv.Utils       Algorithm.SRTree.AD@@ -87,88 +88,6 @@     , zlib >=0.6.3 && <0.8   default-language: Haskell2010 -executable eggp-  main-is: Main.hs-  other-modules:-      Random-      Util-      Paths_srtree-  hs-source-dirs:-      apps/eggp-  ghc-options: -threaded -rtsopts -with-rtsopts=-N-  build-depends:-      attoparsec >=0.14.4 && <0.15-    , attoparsec-expr >=0.1.1.2 && <0.2-    , base >=4.19 && <5-    , binary >=0.8.9.1 && <0.9-    , bytestring >=0.11 && <0.13-    , containers >=0.6.7 && <0.8-    , dlist ==1.0.*-    , exceptions >=0.10.7 && <0.11-    , filepath >=1.4.0.0 && <1.6-    , hashable >=1.4.4.0 && <1.6-    , ieee754 >=0.8.0 && <0.9-    , lens >=5.2.3 && <5.4-    , list-shuffle >=1.0.0.1 && <1.1-    , massiv >=1.0.4.1 && <1.1-    , mtl >=2.2 && <2.4-    , optparse-applicative >=0.17 && <0.19-    , random >=1.2 && <1.4-    , scheduler >=2.0.0.1 && <3-    , split >=0.2.5 && <0.3-    , srtree-    , statistics >=0.16.2.1 && <0.17-    , transformers >=0.6.1.0 && <0.7-    , unliftio >=0.2.10 && <1-    , unliftio-core >=0.2.1 && <1-    , unordered-containers ==0.2.*-    , vector >=0.12 && <0.14-    , zlib >=0.6.3 && <0.8-  default-language: Haskell2010--executable reggression-  main-is: Main.hs-  other-modules:-      Commands-      Random-      Util-      Paths_srtree-  hs-source-dirs:-      apps/rEGGression-  ghc-options: -threaded -rtsopts -with-rtsopts=-N-  build-depends:-      ansi-terminal >=1.1.2 && <1.2-    , attoparsec >=0.14.4 && <0.15-    , attoparsec-expr >=0.1.1.2 && <0.2-    , base >=4.19 && <5-    , binary >=0.8.9.1 && <0.9-    , bytestring >=0.11 && <0.13-    , containers >=0.6.7 && <0.8-    , dlist ==1.0.*-    , exceptions >=0.10.7 && <0.11-    , filepath >=1.4.0.0 && <1.6-    , hashable >=1.4.4.0 && <1.6-    , ieee754 >=0.8.0 && <0.9-    , lens >=5.2.3 && <5.4-    , list-shuffle >=1.0.0.1 && <1.1-    , massiv >=1.0.4.1 && <1.1-    , mtl >=2.2 && <2.4-    , optparse-applicative >=0.17 && <0.19-    , random >=1.2 && <1.4-    , repline >=0.4.2.0 && <0.5-    , scheduler >=2.0.0.1 && <3-    , split >=0.2.5 && <0.3-    , srtree-    , statistics >=0.16.2.1 && <0.17-    , table-layout >=1.0.0.1 && <1.1-    , transformers >=0.6.1.0 && <0.7-    , unliftio >=0.2.10 && <1-    , unliftio-core >=0.2.1 && <1-    , unordered-containers ==0.2.*-    , vector >=0.12 && <0.14-    , zlib >=0.6.3 && <0.8-  default-language: Haskell2010- executable srsimplify   main-is: Main.hs   other-modules:@@ -236,45 +155,6 @@     , random >=1.2 && <1.4     , scheduler >=2.0.0.1 && <3     , split >=0.2.5 && <0.3-    , srtree-    , statistics >=0.16.2.1 && <0.17-    , transformers >=0.6.1.0 && <0.7-    , unliftio >=0.2.10 && <1-    , unliftio-core >=0.2.1 && <1-    , unordered-containers ==0.2.*-    , vector >=0.12 && <0.14-    , zlib >=0.6.3 && <0.8-  default-language: Haskell2010--executable symregg-  main-is: Main.hs-  other-modules:-      Random-      Util-      Paths_srtree-  hs-source-dirs:-      apps/symregg-  ghc-options: -threaded -rtsopts -with-rtsopts=-N -Wall-  build-depends:-      attoparsec >=0.14.4 && <0.15-    , attoparsec-expr >=0.1.1.2 && <0.2-    , base >=4.19 && <5-    , binary >=0.8.9.1 && <0.9-    , bytestring >=0.11 && <0.13-    , containers >=0.6.7 && <0.8-    , dlist ==1.0.*-    , exceptions >=0.10.7 && <0.11-    , filepath >=1.4.0.0 && <1.6-    , hashable >=1.4.4.0 && <1.6-    , ieee754 >=0.8.0 && <0.9-    , lens >=5.2.3 && <5.4-    , list-shuffle >=1.0.0.1 && <1.1-    , massiv >=1.0.4.1 && <1.1-    , mtl >=2.2 && <2.4-    , optparse-applicative >=0.17 && <0.19-    , random >=1.2 && <1.4-    , scheduler >=2.0.0.1 && <3-    , split >=0.2.5     , srtree     , statistics >=0.16.2.1 && <0.17     , transformers >=0.6.1.0 && <0.7