Basic Usage

This tutorial shows how to load and apply mathematical rules.

Loading Rules

Rules are stored in JSON files. You can load them at compile-time using the @load_osr macro:

using OpenSymbolicRules

# Assuming you have cloned the Algebra rule repository
alg_rules = @load_osr_profile("path/to/Algebra")

The loader verifies that every mathematical operator used by the selected rule files has an openmath:<content-dictionary>#<symbol> declaration in its semantics object. Constraint predicates are intentionally exempt.

Simplifying Expressions

Once loaded, you can apply rules to SymbolicUtils.jl expressions using the simplify function.

using SymbolicUtils
@syms x Power(a, b) Multiply(a, b)

# Create an expression: (x^2)^3
expr = Power(Power(x, 2), 3)

# Simplify it
res = simplify(expr, alg_rules)
# -> Power(x, Multiply(2, 3))

Step-by-Step Tracing

For educational purposes, you can trace the intermediate steps:

res, steps = simplify(expr, alg_rules; mode=:trace)

for step in steps
    println("Before: ", step.before)
    println("After:  ", step.after)
    println("Rule used: ", step.rule.name)
end

Rules loaded from JSON retain their stable OSR name (identity:id) and their description. For streaming output, logging, or a graphical interface, pass a callback instead of relying on the library to print:

simplify(expr, alg_rules; on_step=step -> @info "rewrite" rule=step.rule.name)

Loading an OSR rule-set profile

@load_osr_profile compiles the ordered manifest of a rule-set repository. The repository can be a sibling checkout of this package or any local clone with a rules/meta.json manifest:

calculus_rules = @load_osr_profile("../../Calculus")

The package provides the OpenMath heads used by the current Calculus profile, including circular, hyperbolic, and inverse functions. No caller-side symbolic declarations are required merely to load that profile.

Piecewise expressions

A rewrite that is only valid on part of a domain keeps its validity conditions instead of discarding them. Piecewise holds a list of branches, each a Piece carrying a value and its condition, optionally closed by an Otherwise:

["Piecewise", ["List",
  ["Piece", "x_", ["IsPositive", "x_"]],
  ["Otherwise", ["Multiply", -1, "x_"]]
]]
@syms x
absolute = Piecewise([Piece(x, IsPositive(x)), Otherwise(Multiply(-1, x))])
piecewise_pieces(absolute) # the branches, with `nothing` as the Otherwise condition

select_piece reduces a piecewise to the value of the branch that applies. Branches are examined in order, and a branch is taken once its condition is decided true and every earlier one is decided false. An undecided condition stops the search, because a later branch may not overtake one that might yet apply:

select_piece(absolute)                                  # unchanged: nothing is known about x
assuming(IsPositive(x)) do select_piece(absolute) end   # x

decide_condition is the three-valued judgement behind it: true, false, or nothing when undecided. A condition is decided when it is a Boolean literal, when it is a relation over closed arithmetic expressions, or when it is an active hypothesis; And, Or, and Not combine those answers, so a conjunction with one false operand is false even when the other is unknown.

A symbolic predicate answering false means "not proved", which is why an unproved condition leaves the piecewise intact rather than skipping the branch.

Canonical form

canonical puts an expression in a deterministic normal form, and canonically_equal compares two through it.

canonical(Power(x, Add(3, -1)))   # Power(x, 2)
canonical(Add(x, 0))              # x
canonically_equal(Add(x, y), Add(y, x))   # true

Normalizing is not evaluating. It folds what is already closed, writes a rational whose denominator is one as that integer, drops an identity operand, and orders the summands of a sum — addition commuting wherever it is defined. It never decides anything the expression left open, and a head the package does not evaluate keeps its place with its operands normalized.

It deliberately leaves two things alone. The factors of a product are not reordered: an OSR expression carries no shape information, so a factor may be a matrix and the order is part of the meaning. And x^0 is not turned into 1, which holds only where x is nonzero. canonically_equal is therefore a structural test after normalization, not a proof of mathematical equality.

Differentiating and taking limits

differentiate and limit take the expression first and assemble the canonical OSR form themselves. There is no second expression tree: what goes in and what comes out is the one representation the rules are written against.

@syms x
rules = @load_osr_profile("path/to/Calculus")

differentiate(Sin(x), x, rules)              # Cos(x)
differentiate(Add(Sin(x), Cos(x)), x, rules) # Add(Cos(x), Multiply(-1, Sin(x)))
limit(Divide(Sin(x), x), x, 0, rules)        # 1

Derivative binds its variable in a Lambda, as the OpenMath fns1#lambda symbol prescribes, so differentiate(f, x, rules) builds Derivative(Lambda(x, f)), rewrites it, and returns the body of the lambda it reaches. Limit carries its point, its approach and a lambda-bound expression.

An operation the rule set cannot carry out stays a Derivative or a Limit term rather than becoming a closed form nobody reached, and evaluated_derivative and evaluated_limit say which came back.

Reading a result

An expression on its own cannot say whether it was proved, assumed, or simply not carried out — and an unknown result read as a proved equality is the one mistake this package is built to avoid. mode = :status returns the reading beside the value, the way simplify(...; mode = :trace) returns the steps:

differentiate(Sin(x), x, rules)                  # Cos(x)
differentiate(Sin(x), x, rules; mode = :status)  # differentiate: proved
                                                 #   Cos(x)
differentiate(Opaque(x), x, rules; mode = :status)
# differentiate: unevaluated
#   Derivative(Lambda(x, Opaque(x)))
statusmeaning
:proveda closed form the rules established outright
:conditionala closed form, valid where the recorded assumptions hold
:unevaluatedthe operation is still standing in the value
:inapplicablethe operation does not apply to this argument
:divergentthe operation has no finite value here

A rewrite that fired under a hypothesis is :conditional on it, and assumptions returns the facts it was reached under. status and value read the other two fields.

Applying a lambda

The OSR expression grammar requires a head to be a name (OSR-X-004), so a lambda cannot stand in head position and an application needs a head of its own: Apply(Lambda(x, body), argument). beta_reduce carries one out, through the same capture-avoiding substitution osr_substitute performs.

A rule set that differentiates term by term needs this. A structural rule such as the sum rule returns a lambda whose body applies the lambdas the base rules return, so rewriting and reduction have to alternate: reduction cannot run until rewriting has produced the lambdas, and rewriting cannot continue past an application until reduction has collapsed it. differentiate alternates them to a fixed point.

Proving an equivalence

prove searches for a rewrite path between two expressions and returns the proof that records it:

@syms x
rules = @load_osr_profile("path/to/Trigonometry")

proof = prove(Add(Power(Sin(x), 2), Power(Cos(x), 2)), 1, rules)
verified(proof) # true
OSRProof: verified
  left:  Add(Power(Sin(x), 2), Power(Cos(x), 2))
    Add(Power(Sin(x), 2), Power(Cos(x), 2))  =  1   [1.1:1] Pythagorean Identity
    ⇒ 1
  right: 1
    ⇒ 1
  both sides reduce to 1

An equation written with ~ can be proved directly, and hypotheses are carried into the proof:

prove(Add(Power(Sin(x), 2), Power(Cos(x), 2)) ~ 1, rules)
prove(Power(x, 0), 1, power_rules; assumptions=[IsNonzero(x)])

Both sides are normalised with the rule set and the normal forms are compared up to a renaming of bound variables, so the search succeeds exactly when the two sides are joinable. Each recorded step is local, which is what a rewrite tactic in a proof assistant consumes; every OSR rule is an oriented instance of an equation, so the steps on the right read backwards complete the derivation.

The search is sound but incomplete. A verified proof means every step is a rule application whose constraints held where it fired. A failure means the rule set offered no path, which is not a proof of inequivalence — a rule set that is not confluent can fail to join two equivalent expressions — so the result reads "not proved" rather than "unequal".

Assumptions and Safe Rewrites

Rules carrying a predicate are applied only when it is established. For example, NonzeroQ is mapped to is_nonzero: it accepts a nonzero literal, or a symbolic term explicitly declared nonzero. This prevents the invalid unconditional rewrite 0^0 = 1. Likewise, NotEqual does not infer a mathematical inequality from two structurally different symbolic terms.

@syms x Power(a, b)
power_rules = @load_osr("path/to/1.1-basic-exponents.json")

simplify(Power(x, 0), power_rules)                         # unchanged
simplify(Power(x, 0), power_rules; assumptions=[IsNonzero(x)]) # 1

What a hypothesis establishes

A hypothesis proves every property its domain implies, not only the one it was written as. Membership can be declared with a DomainSets.jl domain, an IntervalSets.jl interval, or a Julia type:

assuming(x ∈ 2..5) do
    is_positive(x) # true
    is_nonzero(x)  # true
    is_real(x)     # true
    is_integer(x)  # false — an interval of reals proves nothing about integrality
end

assuming(x ∈ Integers()) do
    is_integer(x) # true
    is_real(x)    # true
end

A bound at zero only excludes zero when it is open, so x ∈ 0..Inf is not a proof of positivity while x ∈ OpenInterval(0, Inf) is. The relational hypotheses IsPositive, IsNegative, IsNonzero, IsInteger, GreaterThan, and LessThan work the same way: GreaterThan(x, 5) proves positivity, GreaterThan(x, -3) only proves that x is real.

Each hypothesis is weighed on its own, so the context is sound but does not combine two hypotheses into a third: x ∈ ℤ proves integrality and x > 0 proves positivity, yet neither alone proves that x is a positive integer.

When Symbolics.jl is loaded, its ∈ builds a VarDomainPairing instead of the package's ElementOf. Such a hypothesis is read as an OSR fact on entry, so assuming(x ∈ 2..5) behaves the same either way.

Wildcards

A rule's pattern declares its wildcards; its result and its constraints refer to the bindings the pattern made.

SpellingMeaningCompiles to
~xslot~x
x_blank~x
x_integertyped blank~x::IntegerQ
xs__sequence of at least one expression~~xs, guarded non-empty
xs___sequence, possibly empty~~xs
x_symboltyped blank, variables only~x::is_symbol
a.optional operand~!a, defaulted by the enclosing operation
m.3optional operand, explicit default~!m, defaulting to 3

A typed blank accepts the domains integer, rational, real, complex, number, and symbol; any other domain is a rule-file error rather than a silently inert rule.

symbol matches a variable and nothing else. A rule that binds a variable of the problem — the variable of an integral, a derivative, a sum, or a limit — is valid only when that operand really is a variable, so ["Int", "f_", "x_symbol"] matches an integral of a variable and not an integral of an expression. A rule that drops the restriction is unsound rather than incomplete: x_^m_. without it matches a constant integrand and returns a closed form that is not its antiderivative.

Optional operands

OSR spells an optional operand a., as in RUBI's (a. + b.*x)^m.. Matching one needs the identity element of the enclosing operation, so the enclosing head supplies the default: plus contributes zero, times contributes one, and power contributes one to its exponent. A power's base is not optional — an absent base has no meaning — and a head with no identity element supplies no default, so an optional operand in either position is a rule-file error rather than a rule that could never fire. An explicit default in the spelling itself, as in m.3, wins over the one the operation would supply.

One rule therefore covers every degenerate shape at once:

{
  "pattern": ["Power", ["Add", "a.", ["Multiply", "b.", "x"]], "m."],
  "result": ["List", "a.", "b.", "m."]
}

matches (2 + 3x)^4 binding [2, 3, 4], and also the bare x, binding [0, 1, 1].

A result and a constraint refer to the binding the pattern made, whether it came from a matched operand or from the default, so a defaulted operand is still weighed by the guard.

Referring to a binding

A rule's pattern declares its wildcards; its result and its constraints refer to the bindings it made. Either spelling works there — m_, m., or the bare name m — which is how the RUBI dataset is written:

{
  "pattern": ["Power", "x_", "m."],
  "constraints": [["NeQ", "m", -1]],
  "result": ["Multiply", ["Power", "x", ["Add", "m", 1]],
                         ["Power", ["Add", "m", 1], -1]]
}

A name the pattern never bound stays a free symbol, so a result may still name a variable of the surrounding problem.

Heads a rule file declares

The loader resolves each operator of a rule file to an operation. When the loading module binds the name to something that can act as one, that binding is used, which is how a host supplies its own implementation of a head. Otherwise the head is registered as a symbolic function in OpenSymbolicRules.UninterpretedHeads and referred to there, so the rule produces an unevaluated term rather than failing when it fires.

A Julia type is never used as a head. Int names an indefinite integral in the RUBI corpus and a machine integer in Base; building a term whose operation is Base.Int raises the moment the rule fires, and no integral-aware code recognises it in the meantime. Registering the head instead keeps the declared meaning and introduces no name into the caller's scope.

Wildcards in operator position

A pattern variable may stand where an operator does, which is how a single RUBI rule matches any of the six trigonometric heads:

{"pattern": ["f_", ["Add", "e", ["Multiply", "f", "x"]]]}

Such a head names a binding rather than an operation, so it carries no OpenMath symbol and the result may reapply the head it matched.

The constraint predicate library

A rule's constraints array is compiled into a Julia guard. Each entry names a predicate and applies it to OSR expressions:

"constraints": [
  ["FreeQ", "~m", "x"],
  ["Not", ["EqQ", "~m", -1]],
  ["Or", ["IntegerQ", "~m"], ["And", ["GtQ", "~a", 0], ["GtQ", "~c", 0]]]
]

Not, And, Or, and If are combinators: they nest constraints and compile to Julia control flow, never to a symbolic term. Every other entry is a predicate application, and all entries of the array must hold.

A Condition pairs a pattern with the test that admits it — OSR's spelling of a guarded pattern, as it appears inside MatchQ. Its first argument is an expression and its second is a constraint. Like List, it belongs to the rule language rather than to a mathematical domain, so a rule file binds no OpenMath symbol for it; the operators inside the guarded pattern are domain vocabulary and must still be declared.

The library implements the predicates below, covering 97% of the constraint applications in the RUBI dataset:

GroupPredicates
ComparisonEqQ, NeQ, GtQ, LtQ, GeQ, LeQ
Integer-qualifiedIntegerQ, IntegersQ, IGtQ, ILtQ, IGeQ, ILeQ
Numeric domainRationalQ, FractionQ, HalfIntegerQ, PosQ, NegQ, FalseQ, NumericQ, RealQ, ComplexQ
StructuralFreeQ, AtomQ, SumQ, ProductQ, PowerQ, MemberQ

FreeQ accepts a collection on either side. A quantifier binds a list, so a side condition about its scope can ask about the whole binder, and RUBI's FreeQ[{a, b, m}, x] spelling asks about every element of a list. PolynomialQ, PolyQ, LinearQ, and QuadraticQ read a collection the same way: LinearQ[{u, v}, x] asks whether every element is linear in x. | Polynomial | PolynomialQ, PolyQ, LinearQ, QuadraticQ | | Written shape | LinearMatchQ, BinomialQ, BinomialMatchQ, QuadraticMatchQ, TrinomialQ, TrinomialMatchQ, GeneralizedBinomialQ, GeneralizedTrinomialQ | | Classification | TrigQ, HyperbolicQ, InertTrigQ, InverseFunctionFreeQ, ComplexFreeQ, IntegralFreeQ, TrueQ, IndependentQ, OddQ, PerfectSquareQ |

GtQ, LtQ, GeQ, and LeQ accept RUBI's chained form, so GtQ(u, v, w) means u > v > w.

Two readings of an undecided inequality

RUBI reads NeQ[u, v] as not provably equal, so NeQ[m, -1] holds for a symbolic m: the rule it guards is valid wherever m is not -1, and the case m == -1 is caught by an earlier rule of the ordered profile. This package reads it as provably distinct, which is sound but declines those rules — and they are most of the corpus.

The alternative reading is selectable and off by default:

neq_reading()                      # :proved_distinct
neq_reading!(:not_proved_equal)    # RUBI's reading

Turning it on weakens the guarantee that a guard which holds is a guard that was proved: the rewrites it admits are conditional on an assumption nobody recorded. It exists because the choice has a measurable cost, and the conformance report takes --neq not_proved_equal so the cost can be read off rather than argued. Either reading still refuses to call provably equal things different.

EqQ and NeQ decide a polynomial identity exactly. Two expressions whose difference is the zero polynomial over the symbols they mention are equal for every value of those symbols, so EqQ(Multiply(b, c), Multiply(c, b)) holds; a difference that is a nonzero constant proves inequality, so NeQ(Add(m, 1), m) holds. A difference that still mentions a symbol proves neither, because it vanishes for some values and not others: NeQ(m, -1) is false, meaning not proved, and the guarded rewrite is skipped.

LinearMatchQ asks whether an expression is already written as a + b*x, where LinearQ asks only whether its degree is one. RUBI's normalization rules fire exactly when something is linear but not yet in that shape, so reading the two as synonyms would make those rules loop.

QuadraticMatchQ and TrinomialQ extend the same reading to a + b*x + c*x^2 and to a + b*x^n + c*x^(2n); a quadratic is the trinomial with n = 1, which is how RUBI files it.

A classifying predicate reads a head by name, so TrigQ(Sin) holds as much as TrigQ(Sin(x)) — RUBI applies these to a head a pattern bound, as in TrigQ[F] where F_ matched one of the six circular functions. InverseFunctionFreeQ asks whether a logarithm or an inverse circular or hyperbolic function of the variable occurs: Log(a) leaves an integrand alone, Log(x) does not.

BinomialQ asks the same kind of question of a + b*x^n, with a, b, and the exponent free of x; BinomialQ(u, x, n) fixes the exponent. It reads the written shape, where RUBI normalizes its argument first, so it declines some expressions RUBI would accept — leaving a rewrite unapplied rather than risking an invalid one — and agrees with BinomialMatchQ. The normalization rules guarded by BinomialQ(u, x) && Not(BinomialMatchQ(u, x)) therefore never fire.

Every predicate is conservative: it answers true only when the property is established, so an unproved guard leaves its rewrite unapplied rather than risking an invalid one.

A predicate with no implementation

A predicate that neither this library nor the loading module resolves cannot be evaluated, and so establishes nothing. Its guard is abandoned and the rule does not fire; the rule is still loaded, keeping its identity and provenance, so a report can say which rules are held back and by what.

The guard is not simply answered false, because that would make Not answer true and license a rewrite on a property nobody decided. Abandoning it instead gives the guard a three-valued reading, and && and || short-circuit, so precision is kept where it is available:

guardoutcome
["PseudoBinomialPairQ", "u", "m"]not established
["Not", ["PseudoBinomialPairQ", "u", "m"]]not established
["Or", ["IntegerQ", "m"], ["PseudoBinomialPairQ", "u", "m"]]established when m is an integer
["And", ["IntegerQ", "m"], ["PseudoBinomialPairQ", "u", "m"]]not established

A host completes the vocabulary by defining the predicate in the module that loads the rule file; the loader uses that definition as it stands. A closed arithmetic expression is evaluated exactly, which is what makes a guard such as ["PosQ", ["Power", 2, -1]] decidable:

OpenSymbolicRules.osr_number(Power(2, -1)) # 1//2

Folding only recognises the canonical Add, Multiply, Subtract, Divide, and Power heads. A rule file that renames them still loads, but its arithmetic becomes opaque and its guarded rewrites stay inactive.

A predicate the library does not define is resolved in the module that loads the rule file, so a host can supply its own:

module Host
    using OpenSymbolicRules
    EvenIntegerQ(value) = value isa Integer && iseven(value)
    const rules = @load_osr("path/to/rules.json") # may use ["EvenIntegerQ", "~m"]
end

Symbolics.jl Interoperability

When Symbolics.jl is loaded, to_osr converts its differential operator into the canonical OpenMath-aligned representation Derivative(Lambda(x, f)). to_symbolics performs the inverse conversion, preserving the differentiation variable and expression.

OpenMath Interoperability

Loading the optional OpenMath.jl package activates an extension that exports core arithmetic and propositional-logic expressions as typed OpenMath objects. It uses Content Dictionary symbols, so the representation can then be validated or written using OpenMath's XML, JSON, MathML, or binary encodings.

using OpenMath
using OpenSymbolicRules
using SymbolicUtils

@syms x
object = OpenSymbolicRules.to_openmath(Add(x, 3 // 2))
# OMA(OMS(arith1#plus), OMV(x), OMA(OMS(nums1#rational), OMI(3), OMI(2)))

expression = OpenSymbolicRules.from_openmath(object)
# Add(x, 3//2)

derivative = OpenSymbolicRules.to_openmath(Derivative(Lambda(x, Power(x, 2))))
# OMA(OMS(calculus1#diff), OMBIND(OMS(fns1#lambda), [x], ...))

piecewise = OpenSymbolicRules.to_openmath(
    Piecewise([Piece(x, GreaterThan(x, 0)), Otherwise(0)]))
# OMA(OMS(piece1#piecewise), OMA(OMS(piece1#piece), ...), OMA(OMS(piece1#otherwise), OMI(0)))

collection = OpenSymbolicRules.to_openmath([x, 1, Sin(x)])
# OMA(OMS(list1#list), OMV(x), OMI(1), OMA(OMS(transc1#sin), OMV(x)))

limit = OpenSymbolicRules.to_openmath(
    Limit(0, BothSides, Lambda(x, Divide(Sin(x), x))))
# OMA(OMS(limit1#limit), OMI(0), OMS(limit1#both_sides), OMBIND(...))

OpenSymbolicRules.to_openmath(π)
# OMS(nums1#pi)

The extension is deliberately optional and only runs at interchange boundaries; OSR rewriting does not depend on OpenMath.jl. It currently covers core arithmetic, trigonometric and hyperbolic, exponential, propositional-logic, canonical lambda-bound derivative, ordered piecewise, and structural list heads, plus canonical limits. Unsupported OpenMath symbols or OSR heads raise an explicit error, which prevents silently assigning incorrect semantics.

Loading a Profile

An OSR repository can expose an ordered default profile and named rewrite profiles in rules/meta.json:

rules = @load_osr_profile("path/to/Logic")
cnf_rules = @load_osr_profile("path/to/Logic", :to_cnf)

Multi-premise inference profiles are read as structured data, leaving proof search and clause management to the host engine:

inferences = load_inference_profile("path/to/Logic", :resolution)

Logic profiles use the exported canonical heads And, Or, Not, Implies, Equivalent, Forall, and Exists.

Quantifier heads accept a vector of bound variable names. A rule declaration using xs__ captures and preserves the complete vector, so a first-order rewrite can handle one or many bound variables without treating that vector as a scalar expression:

@syms p
rules = @load_osr("path/to/6.1-negation.json")
simplify(Not(Forall([:x, :y], p)), rules) # Exists([:x, :y], Not(p))

Rule dispatch

simplify does not try every rule on every term. Rules are indexed by the operation their pattern requires at the root of a term, so applying a rule set costs one dictionary lookup rather than one matcher call per rule. On a synthetic 6000-rule set this applies rules roughly 470 times faster than a linear scan, which is what makes a catalogue the size of RUBI usable.

Three kinds of pattern have no root requirement and are therefore always tried: a bare slot (~a), a slot in head position ((~f)(~a)), and a pattern holding an optional slot ((~a)^(~!b)), which SymbolicUtils lets match a term that lacks the operation entirely.

Dispatch is an optimisation, not a change of semantics: the rules that can match are applied in their original order, exactly as a linear scan would.

Binders and lexical scope

Lambda, Forall, and Exists introduce a lexical scope. Every other binding construct — an integral, a sum, a product, a derivative — carries its bound variable inside a Lambda, as the OpenMath fns1#lambda symbol prescribes, so the Calculus profile writes a derivative as Derivative(Lambda(x, body)):

@syms x c
rules = @load_osr_profile("path/to/Calculus")

simplify(Derivative(Lambda(x, c)), rules)             # Lambda(x, 0)
simplify(Derivative(Lambda(x, Power(x, 2))), rules)   # Lambda(x, Multiply(2, Power(x, Add(2, -1))))

A bound occurrence is not an occurrence of the free variable, and FreeQ respects that:

FreeQ(Lambda(x, Sin(x)), x) # true
free_variables(Lambda(x, Add(x, y))) # Set([:y])

osr_substitute substitutes for the free occurrences of a variable and is capture-avoiding: a binder whose variable occurs free in the replacement is alpha-renamed first, so the replacement keeps referring to the same variable it did outside the binder.

osr_substitute(Lambda(y, Add(x, y)), x => y) # Lambda(y1, Add(y, y1))

Two expressions that differ only in the names of their bound variables are compared with alpha_equivalent:

alpha_equivalent(Lambda(x, Sin(x)), Lambda(y, Sin(y))) # true
alpha_equivalent(Lambda(x, Sin(x)), Lambda(y, Sin(x))) # false

Associativity and commutativity

Associativity and commutativity are properties of the OpenMath symbol a head is bound to, never of the head's spelling. A rule file declares those bindings in its semantics block, so the file below gets commutative matching for Plus without having to be named Add:

{
  "semantics": { "Plus": "openmath:arith1#plus" },
  "rules": [
    { "id": 1, "pattern": ["Plus", "~x", 0], "constraints": [], "result": "~x" }
  ]
}

An n-ary expression headed by an associative symbol (arith1#plus, arith1#times, logic1#and, logic1#or, logic1#xor) is normalized to left-associated binary SymbolicUtils terms at load time.

A pattern headed by a commutative symbol (arith1#plus and the Boolean connectives logic1#and, logic1#or, logic1#xor, logic1#xnor, logic1#nand, logic1#nor, logic1#equivalent) compiles to a SymbolicUtils.ACRule, which matches every operand order with a single rule. A rule file therefore never needs a mirrored copy of a commutative pattern:

simplify(Plus(x, 0), rules) # x
simplify(Plus(0, x), rules) # x

arith1#times is deliberately excluded. An OSR expression carries no shape information, so a times operand may be a matrix and reordering it would be unsound.

With Symbolics.jl, symbolic arrays can be declared with @variables A[1:m, 1:n]. Matrix addition may use Add when dimensions are compatible, but matrix multiplication must retain its operand order. A future matrix profile will need explicit shape constraints and matrix-product semantics rather than scalar arith1#times assumptions.

The same rule is stricter for tensors: addition is commutative only for equal shapes, whereas tensor product, contraction, and axis permutation are ordered operations. They must be represented by dedicated heads with explicit index and shape metadata; they must never be silently encoded as Multiply.

Exact polynomial normal forms

SparsePolynomial is an opt-in exact backend for algorithms over multivariate polynomials with rational coefficients. It is intentionally separate from general symbolic expressions: callers supply the polynomial ring variables and its sparse monomial map explicitly.

p = SparsePolynomial([:x, :y], Dict((2, 0) => 1, (0, 1) => 1)) # x² + y
q = SparsePolynomial([:x, :y], Dict((1, 1) => 1, (0, 0) => -1)) # xy - 1

# Exact univariate elimination invariant
resultant(SparsePolynomial([:x], Dict((2,) => 1, (0,) => -1)),
          SparsePolynomial([:x], Dict((1,) => 1, (0,) => -2))) # 3//1

# A zero discriminant identifies a repeated algebraic root exactly.
discriminant(SparsePolynomial([:x], Dict((2,) => 1, (1,) => -2, (0,) => 1))) # 0//1

# Monic square-free factors retain their exact root multiplicities.
squarefree_decomposition(
    SparsePolynomial([:x], Dict((5,) => 1, (4,) => 4, (3,) => 1,
                                (2,) => -10, (1,) => -4, (0,) => 8)))
# [(factor = x - 1, multiplicity = 2), (factor = x + 2, multiplicity = 3)]

# Only exact rational roots are returned; irrational roots are never approximated.
rational_roots(SparsePolynomial([:x], Dict((2,) => 2, (1,) => -3, (0,) => 1)))
# [(root = 1//2, multiplicity = 1), (root = 1//1, multiplicity = 1)]

root_result = solve(UnivariatePolynomialProblem(
    SparsePolynomial([:x], Dict((2,) => 1, (1,) => -3, (0,) => 2))))
root_result.roots
root_result.complete # true only when no unresolved factor remains

The same exact fragment is available from an equation:

julia @syms x solve(x^2 - 3x + 2 ~ 0, x).roots

[(root = 1//1, multiplicity = 1), (root = 2//1, multiplicity = 1)]


## Integration utility semantics

Integration rule results may contain OSR utility heads. `Subst` is evaluated
with the semantics mandated by OSR-E-012, including capture-avoiding treatment
of lexical binders:

julia @syms x y

Subst(Add(x, Power(x, 2)), x, y)

Add(y, Power(y, 2))


`ExpandIntegrand` remains deliberately unevaluated until a terminating,
domain-aware expansion strategy is available: erasing it as an identity can
recreate the integral that produced it and make an integration rewrite loop.

spoly(p, q; ordering=:lex)              # y² + x
normal_form(p, [q]; ordering=:grevlex)  # normal form modulo q
g = groebner_basis([p, q]; ordering=:lex)
ideal_membership(p, g; ordering=:lex)   # true

The available orders are :lex, :grlex, and :grevlex. This foundation is for exact algebraic algorithms; conversion from SymbolicUtils expressions and equation solving remain separate planned layers. For implementation inspection, low-level leading-term and S-polynomial primitives stay qualified as OpenSymbolicRules.leading_monomial and OpenSymbolicRules.spoly.

Exact numeric radicals

normalize_sqrt avoids constructing floating-point literals for numeric radicals while preserving the canonical OpenMath root semantics:

normalize_sqrt(12)      # 2 * Sqrt(3)
normalize_sqrt(7 // 2)  # (1//2) * Sqrt(14)
normalize_sqrt(49)      # 7

Perfect-square extraction is bounded. Therefore normalization always remains exact and terminates, even when a large radicand is not fully factored.

An explicit boundary retains the exact coefficient domain when exchanging polynomials with SymbolicUtils. The requested variables define the ring; functions, negative powers, and undeclared parameters are rejected.

using SymbolicUtils
@syms x y

p = to_sparse_polynomial(x^2 * y + 3 // 2, [:x, :y])
to_symbolic_polynomial(p, Dict(:x => x, :y => y))

Propositional satisfiability

The Boolean kernel includes a small pure-Julia DPLL solver for finite CNF problems. It has no native-library or solver-package dependency. Clauses use the standard DIMACS literal convention: a positive integer denotes a variable, and its negative denotes the variable's negation.

# (a ∨ b) ∧ (¬a ∨ b) ∧ (a ∨ ¬b)
satisfiable([[1, 2], [-1, 2], [1, -2]]) # true

# a ∧ ¬a
satisfiable([[1], [-1]])                # false

The structured operation API extends CommonSolve.solve, keeping solver selection and result status explicit while remaining interoperable with SciML:

using CommonSolve

result = solve(SATProblem([[1, 2], [-1, 2]]))
result isa SatResult # true
result.model          # directly checkable witness

# The same problem can be initialized and solved explicitly.
state = CommonSolve.init(SATProblem([[1]]), BuiltinBackend())
CommonSolve.solve!(state)

The same interface covers the exact linear SMT theory:

atoms = Dict(1 => LinearConstraint(Dict(:x => 1), :le, 0))
result = solve(SMTProblem([[1]], atoms))
result.model.rationals[:x] # an exact rational satisfying x ≤ 0

Numeric equality atoms can be combined with linear constraints through the same operation API. Their dictionary must declare the shared numeric sort:

mixed_atoms = Dict{Int,Union{LinearConstraint,EqualityConstraint}}(
    1 => LinearConstraint(Dict(:x => 1), :le, 0),
    2 => EqualityConstraint(:x, :y, :eq),
)
result = solve(SMTProblem([[1], [2]], mixed_atoms))
result.model.rationals[:x] == result.model.rationals[:y] # true

This is the Boolean component of a planned pure-Julia DPLL(T) architecture. Theory reasoning, such as equality and rational linear arithmetic, is added only when its result can retain explicit assumptions and proof obligations.

For a satisfiable CNF problem, sat_model returns a dictionary that witnesses the decision and can be checked directly against every clause. It returns nothing for an unsatisfiable formula.

sat_model([[1, 2], [-1, 2]]) # Dict(1 => true, 2 => true)

Exact rational linear theory

linear_satisfiable decides a conjunction of linear constraints over ℚ using exact Fourier–Motzkin elimination. A constraint uses :le, :lt, or :eq for ≤, <, or = respectively.

x_at_least_one = LinearConstraint(Dict(:x => -1), :le, -1)
x_less_than_one = LinearConstraint(Dict(:x => 1), :lt, 1)

linear_satisfiable([x_at_least_one, x_less_than_one]) # false

It is the exact rational theory component used by the DPLL(T) integration below.

For a feasible system, linear_model reconstructs rational variable values from the elimination layers. Its result is an ordinary dictionary and can be checked against the original constraints without numerical tolerances.

linear_model([x_at_least_one]) # Dict(:x => 1)

Combining Boolean and linear constraints

linear_smt_satisfiable now joins the local DPLL engine to linear theory atoms. CNF clauses refer to positive atom numbers; a negative literal is the exact logical negation of a non-strict or strict inequality.

atoms = Dict(
    1 => LinearConstraint(Dict(:x => 1), :le, 0),
    2 => LinearConstraint(Dict(:x => -1), :lt, -1), # x > 1
)

linear_smt_satisfiable([[1, 2]], atoms) # x ≤ 0 ∨ x > 1; true
linear_smt_satisfiable([[1], [2]], atoms) # false

linear_smt_model returns both the Boolean choices and the rational assignment for the selected theory branch.

model = linear_smt_model([[1, 2]], atoms)
model.booleans
model.rationals

Negated equalities are expanded exactly as a < b ∨ a > b; the solver keeps those alternatives as explicit theory branches. Proof-producing explanations remain the next SMT milestone.

Equality theory

For ground, uninterpreted symbols, smt_satisfiable uses union-find to close equalities transitively before checking disequalities.

atoms = Dict(
    1 => EqualityConstraint(:a, :b, :eq),
    2 => EqualityConstraint(:a, :b, :ne),
)

smt_satisfiable([[1, 2]], atoms) # true
smt_satisfiable([[1], [2]], atoms) # false

smt_model returns the Boolean choices and a map from every ground term to its equivalence-class representative.

model = smt_model([[1, 2]], atoms)
model.classes[:a] == model.classes[:b]

This equality theory is separate from rational linear arithmetic for now. For symbols interpreted as rational variables, use the explicitly sorted rational_smt_satisfiable entry point instead: it combines equality, disequality, and linear arithmetic by translating x = y into x - y = 0. It is intentionally distinct from the uninterpreted equality solver above.

numeric_atoms = Dict{Int,Union{LinearConstraint,EqualityConstraint}}(
    1 => EqualityConstraint(:x, :y, :eq),
    2 => LinearConstraint(Dict(:x => 1), :le, 0),
    3 => LinearConstraint(Dict(:y => -1), :le, -1),
)

rational_smt_satisfiable([[1], [2], [3]], numeric_atoms) # false

Checking assumption consistency

The same exact rational engine can reject contradictory CAS hypotheses before they are used to justify a conditional rewrite. It reports nothing rather than guessing when a fact is outside its supported fragment.

@syms x
rational_assumptions_satisfiable([GreaterThan(x, 0), LessThan(x, 0)]) # false
rational_assumptions_satisfiable([IsNonzero(x), x ∈ 0..0]) # false

Exact interval memberships participate in the same check, including open and closed endpoints.

rational_assumptions_satisfiable([x ∈ 1..2, LessThan(x, 1)]) # false

simplify performs this consistency check for supplied assumptions. A context proven contradictory raises ArgumentError; an unsupported fact remains conservative and does not block rewriting.

Supported facts can also combine to discharge a conditional predicate. For example, neither x ∈ [0,2] nor x ≠ 0 alone proves positivity, while their combination does.

assuming(x ∈ 0..2, IsNonzero(x)) do
    is_positive(x) # true
end