Low Level: egglog.bindings#
This modules contains bindings for the rust egglog library which are meant to be as close to the source as possible. This might result in not the most ergonomic API, if so, we can build higher level abstractions on top of it.
Example:
from egglog.bindings import *
eqsat_basic = """(datatype Math
(Num i64)
(Var String)
(Add Math Math)
(Mul Math Math))
;; expr1 = 2 * (x + 3)
(let expr1 (Mul (Num 2) (Add (Var "x") (Num 3))))
;; expr2 = 6 + 2 * x
(let expr2 (Add (Num 6) (Mul (Num 2) (Var "x"))))
(rewrite (Add a b)
(Add b a))
(rewrite (Mul a (Add b c))
(Add (Mul a b) (Mul a c)))
(rewrite (Add (Num a) (Num b))
(Num (+ a b)))
(rewrite (Mul (Num a) (Num b))
(Num (* a b)))
(run 10)
(check (= expr1 expr2))"""
egraph = EGraph()
commands = egraph.parse_program(eqsat_basic)
egraph.run_program(*commands)
In 8:1-49: (let expr1 (Mul (Num 2) (Add (Var "x") (Num 3))))
Global `expr1` should start with `$`. Enable `--strict-mode` to turn this warning into an error. Suppressing additional warnings of this type.
[RunScheduleOutput(RunReport([IterationReport(RuleSetReport(True, {'(rewrite (Mul a (Add b c)) (Add (Mul a b) (Mul a c)))': [RuleReport(None, datetime.timedelta(microseconds=17), 1)], '(rewrite (Add (Num a) (Num b)) (Num (+ a b)))': [RuleReport(None, datetime.timedelta(microseconds=3), 0)], '(rewrite (Mul (Num a) (Num b)) (Num (* a b)))': [RuleReport(None, datetime.timedelta(microseconds=3), 0)], '(rewrite (Add a b) (Add b a))': [RuleReport(None, datetime.timedelta(microseconds=8), 2)]}, datetime.timedelta(microseconds=43), datetime.timedelta(microseconds=2)), datetime.timedelta(0)), IterationReport(RuleSetReport(True, {'(rewrite (Mul a (Add b c)) (Add (Mul a b) (Mul a c)))': [RuleReport(None, datetime.timedelta(microseconds=3), 1), RuleReport(None, datetime.timedelta(microseconds=1), 0)], '(rewrite (Add (Num a) (Num b)) (Num (+ a b)))': [RuleReport(None, datetime.timedelta(microseconds=2), 0)], '(rewrite (Add a b) (Add b a))': [RuleReport(None, datetime.timedelta(microseconds=2), 3)], '(rewrite (Mul (Num a) (Num b)) (Num (* a b)))': [RuleReport(None, datetime.timedelta(microseconds=7), 1)]}, datetime.timedelta(microseconds=28), datetime.timedelta(microseconds=5)), datetime.timedelta(microseconds=21)), IterationReport(RuleSetReport(False, {'(rewrite (Add a b) (Add b a))': [RuleReport(None, datetime.timedelta(microseconds=3), 2)], '(rewrite (Mul (Num a) (Num b)) (Num (* a b)))': [RuleReport(None, datetime.timedelta(microseconds=9), 1)], '(rewrite (Mul a (Add b c)) (Add (Mul a b) (Mul a c)))': [RuleReport(None, datetime.timedelta(microseconds=2), 0), RuleReport(None, datetime.timedelta(microseconds=2), 0)], '(rewrite (Add (Num a) (Num b)) (Num (+ a b)))': [RuleReport(None, datetime.timedelta(microseconds=3), 0)]}, datetime.timedelta(microseconds=28), datetime.timedelta(microseconds=1)), datetime.timedelta(0))], True, {'(rewrite (Add a b) (Add b a))': datetime.timedelta(microseconds=14), '(rewrite (Mul a (Add b c)) (Add (Mul a b) (Mul a c)))': datetime.timedelta(microseconds=27), '(rewrite (Mul (Num a) (Num b)) (Num (* a b)))': datetime.timedelta(microseconds=20), '(rewrite (Add (Num a) (Num b)) (Num (+ a b)))': datetime.timedelta(microseconds=9)}, {'(rewrite (Mul a (Add b c)) (Add (Mul a b) (Mul a c)))': 2, '(rewrite (Add (Num a) (Num b)) (Num (+ a b)))': 0, '(rewrite (Add a b) (Add b a))': 7, '(rewrite (Mul (Num a) (Num b)) (Num (* a b)))': 2}, {'': datetime.timedelta(microseconds=100)}, {'': datetime.timedelta(microseconds=10)}, {'': datetime.timedelta(microseconds=21)}, False))]
EggSmolError.replayable_by_fail conservatively reports whether the failing
command can be reproduced by wrapping it in Egglog’s (fail ...) command.
Experimental commands may return typed data through
UserDefinedCommandOutput. Command execution first returns a
UserDefinedOutput wrapper; call output.output.as_multi_extract() on its
payload. This returns a MultiExtractOutput for multi-extract results and
None for other custom outputs. Its termdag is shared by all results, while
terms contains one ordered list of variant term IDs per input root.
The commands are a representation which is close the AST of the egglog text language. We can see this by printing the commands:
for command in commands:
print(command)
(datatype Math (Num i64) (Var String) (Add Math Math) (Mul Math Math))
(let expr1 (Mul (Num 2) (Add (Var "x") (Num 3))))
(let expr2 (Add (Num 6) (Mul (Num 2) (Var "x"))))
(rewrite (Add a b) (Add b a))
(rewrite (Mul a (Add b c)) (Add (Mul a b) (Mul a c)))
(rewrite (Add (Num a) (Num b)) (Num (+ a b)))
(rewrite (Mul (Num a) (Num b)) (Num (* a b)))
(run-schedule (repeat 10 (run)))
(check (= expr1 expr2))
Thread safety#
Independent EGraph and Extractor instances can run concurrently. Serialize
access to shared mutable objects, including EGraph and TermDag; overlapping
accesses involving mutation raise an error instead of waiting. Python callbacks
must synchronize shared mutable state. The
high-level API also requires initialization
before concurrent use.
API#
Bindings for egglog rust library
- class egglog.bindings.CSVPrintFunctionMode#
- class egglog.bindings.Constructor(span, name, schema, cost, unextractable, hidden=Ellipsis, let_binding=Ellipsis)#
- cost#
- let_binding#
- name#
- schema#
- span#
- unextractable#
- class egglog.bindings.ContainerRebuildSpec(internal_rebuild_prim, internal_rebuild_proof_prim=Ellipsis)#
- internal_rebuild_prim#
- internal_rebuild_proof_prim#
- class egglog.bindings.CostModel(fold, enode_cost, container_cost, base_value_cost)#
Tree cost model defined by Python functions.
- class egglog.bindings.DagCostModel(identity, enode_cost, container_cost, base_value_cost)#
Additive marginal DAG cost model defined by Python functions.
- class egglog.bindings.DefaultPrintFunctionMode#
- class egglog.bindings.Delete#
- class egglog.bindings.EGraph#
–
Create an empty EGraph.
- commands()#
Returns the text of successfully run commands when recording is enabled.
- eval_expr(expr, *, traceparent=None, tracestate=None)#
- extract_value(value, sort)#
Extract value using its runtime sort. The value must come from eval_expr on this e-graph, and sort must be the sort returned with it. Values from another e-graph or paired with another existing sort are unsupported.
- freeze()#
- lookup_function(name, key)#
- no_decomp()#
Return whether rule decomposition is disabled globally for this EGraph.
- num_threads()#
Return the number of worker threads configured for this EGraph.
- parse_and_run_program(input, /, filename=None, traceparent=None, tracestate=None)#
Parse a program and immediately run the parsed commands on the EGraph.
- parse_program(input, /, filename=None)#
Parse a program into a list of commands.
- run_program(*commands, traceparent=None, tracestate=None)#
Run a series of commands on the EGraph. Returns a list of strings representing the output. An EggSmolError is raised if there is problem parsing or executing.
- serialize(root_eclasses, *, max_functions=None, max_calls_per_function=None, include_temporary_functions=False, traceparent=None, tracestate=None)#
Serialize the EGraph to a SerializedEGraph object.
- set_no_decomp(no_decomp)#
Set whether rule decomposition is disabled for subsequently registered rules.
- set_num_threads(num_threads)#
Set the number of worker threads used by this EGraph.
- set_report_level(level)#
- value_to_bigint(v)#
- value_to_bigrat(v)#
- value_to_bool(v)#
- value_to_f64(v)#
- value_to_function(v)#
- value_to_i64(v)#
- value_to_map(v)#
- value_to_multiset(v)#
- value_to_pyobject(v)#
- value_to_rational(v)#
- value_to_set(v)#
- value_to_string(v)#
- value_to_vec(v)#
- exception egglog.bindings.EggSmolError(context, replayable_by_fail=False)#
- context#
- replayable_by_fail#
Whether replaying the failed command inside (fail …) preserves the command’s partial effects. This is deliberately conservative.
- class egglog.bindings.Extractor(rootsorts, egraph, cost_model, *, traceparent=None, tracestate=None)#
Compatibility facade for the former owned core extractor. The current core extractor borrows its e-graph, so this object stores preparation inputs and prepares locally for each extraction call.
- extract_best(egraph, termdag, value, sort, *, traceparent=None, tracestate=None)#
Extract the best term of a value from a given sort.
value must come from EGraph.eval_expr on the supplied e-graph, and sort must be the sort returned with it. Values from another e-graph or paired with another existing sort are unsupported.
- extract_variants(egraph, termdag, value, nvariants, sort, *, traceparent=None, tracestate=None)#
Extract variants of an e-class.
value must come from EGraph.eval_expr on the supplied e-graph, and sort must be the sort returned with it. Values from another e-graph or paired with another existing sort are unsupported.
- class egglog.bindings.FunctionCommand(span, name, schema, merge, term_constructor=Ellipsis, unextractable=Ellipsis, hidden=Ellipsis, let_binding=Ellipsis)#
- let_binding#
- merge#
- name#
- schema#
- span#
- term_constructor#
- unextractable#
- class egglog.bindings.IterationReport(rule_set_report, rebuild_time)#
- rebuild_time#
- rule_set_report#
- class egglog.bindings.Naive#
- class egglog.bindings.PanicSpan#
- class egglog.bindings.PrintFunction(span, name, length, filename, mode)#
- filename#
- length#
- mode#
- name#
- span#
- class egglog.bindings.PrintFunctionOutput(function, termdag, terms, mode)#
- function#
- mode#
- termdag#
- terms#
- class egglog.bindings.ProofConstructorNames(congr, trans, sym, normalize)#
- congr#
- normalize#
- sym#
- trans#
- class egglog.bindings.Rewrite(span, lhs, rhs, conditions=Ellipsis, name=Ellipsis)#
- conditions#
- lhs#
- name#
- rhs#
- span#
- class egglog.bindings.Rule(span, head, body, name, ruleset, eval_mode=Ellipsis, no_decomp=Ellipsis, include_subsumed=Ellipsis)#
- body#
- eval_mode#
- head#
- include_subsumed#
- name#
- no_decomp#
- ruleset#
- span#
- class egglog.bindings.RuleReport(plan, search_and_apply_time, num_matches)#
- num_matches#
- plan#
- search_and_apply_time#
- class egglog.bindings.RuleSetReport(changed, rule_reports, search_and_apply_time, merge_time)#
- changed#
- merge_time#
- rule_reports#
- search_and_apply_time#
- class egglog.bindings.RunReport(iterations, updated, search_and_apply_time_per_rule, num_matches_per_rule, search_and_apply_time_per_ruleset, merge_time_per_ruleset, rebuild_time_per_ruleset, can_stop=Ellipsis)#
- can_stop#
- iterations#
- merge_time_per_ruleset#
- num_matches_per_rule#
- rebuild_time_per_ruleset#
- search_and_apply_time_per_rule#
- search_and_apply_time_per_ruleset#
- updated#
- class egglog.bindings.Seminaive#
- class egglog.bindings.SerializedEGraph#
- discarded_functions#
- inline_leaves()#
Inline all leaf nodes into their parents.
- map_ops(map)#
Map each op name to a new op name.
- saturate_inline_leaves()#
Inline repeatedly until no more changes are made.
- split_classes(egraph, ops)#
Split all primitive nodes, as well as other ops that match, into separate e-classes
- to_dot()#
Serialize the egraph to a dot string.
- to_json()#
Serialize the egraph to a json string.
- truncated_functions#
- class egglog.bindings.Sort(span, name, presort_and_args, uf=Ellipsis, proof_func=Ellipsis, container_rebuild=Ellipsis, proof_constructors=Ellipsis)#
- container_rebuild#
- name#
- presort_and_args#
- proof_constructors#
- proof_func#
- span#
- uf#
- class egglog.bindings.StageInfo#
- class egglog.bindings.Subsume#
- class egglog.bindings.TermDag#
- app(sym, children)#
Make and return a App with the given head symbol and children, and insert into the DAG if it is not already present.
Panics if any of the children are not already in the DAG.
- expr_to_term(expr)#
Recursively converts the given expression to a term.
This involves inserting every subexpression into this DAG. Because TermDags are hashconsed, the resulting term is guaranteed to maximally share subterms.
- get(id)#
Convert the given id to the corresponding term.
Panics if the id is not valid.
- lit(lit)#
Make a [Term::Lit] with the given literal and return its id, inserting it into the DAG if it is not already present.
- lookup(node)#
Convert the given term to its id.
Panics if the term does not already exist in this [TermDag].
- size()#
Returns the number of nodes in this DAG.
- term_to_expr(term, span)#
Recursively converts the given term to an expression.
Panics if the term contains subterms that are not in the DAG.
- to_string(term)#
Converts the given term to a string.
Panics if the term or any of its subterms are not in the DAG.
- var(sym)#
Make and return a [Term::Var] id with the given symbol, and insert into the DAG if it is not already present.
- class egglog.bindings.TimeOnly#
- class egglog.bindings.Unit#
- class egglog.bindings.UnsafeSeminaive#
- class egglog.bindings.UserDefinedCommandOutput#
- as_multi_extract()#
Return this output as a structured experimental multi-extraction, if it is one.
- class egglog.bindings.Value#
Wrapper around Egglog Value. Represents either a primitive base value or a reference to an e-class.
- class egglog.bindings.Variant(span, name, types, cost=Ellipsis, unextractable=Ellipsis)#
- cost#
- name#
- span#
- types#
- unextractable#
- class egglog.bindings.WithPlan#
- egglog.bindings.extract_best_with_dag_cost_model(egraph, roots, cost_model, *, extractor='tree', traceparent=None, tracestate=None)#
Extract the best term for each root with a custom additive marginal model.
Every value must come from EGraph.eval_expr on the supplied e-graph and be paired with the sort returned with it. Values from another e-graph or paired with another existing sort are unsupported.
- egglog.bindings.setup_tracing(*, exporter, endpoint=None)#