Skip to content

Commit

Permalink
Create BorrowedAtom base type
Browse files Browse the repository at this point in the history
- BorrowedAtom is a Deref target for Atom
- Implement all borrowed functions on BorrowedAtom
- Deprecate AtomCore
  • Loading branch information
benruijl committed Dec 14, 2024
1 parent 5e9279b commit e9c504b
Show file tree
Hide file tree
Showing 54 changed files with 449 additions and 327 deletions.
5 changes: 1 addition & 4 deletions examples/coefficient_ring.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
use std::sync::Arc;

use symbolica::{
atom::{Atom, AtomCore},
state::State,
};
use symbolica::{atom::Atom, state::State};

fn main() {
let expr = Atom::parse("x*z+x*(y+2)^-1*(y+z+1)").unwrap();
Expand Down
2 changes: 1 addition & 1 deletion examples/collect.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use symbolica::{
atom::{Atom, AtomCore},
atom::Atom,
fun,
state::State,
};
Expand Down
5 changes: 1 addition & 4 deletions examples/derivative.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
use symbolica::{
atom::{Atom, AtomCore},
state::State,
};
use symbolica::{atom::Atom, state::State};

fn main() {
let x = State::get_symbol("x");
Expand Down
1 change: 0 additions & 1 deletion examples/evaluate.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use ahash::HashMap;
use symbolica::atom::AtomCore;
use symbolica::evaluate::EvaluationFn;
use symbolica::{atom::Atom, state::State};

Expand Down
2 changes: 1 addition & 1 deletion examples/expansion.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use symbolica::atom::{Atom, AtomCore};
use symbolica::atom::Atom;

fn main() {
let input = Atom::parse("(1+x)^3").unwrap();
Expand Down
2 changes: 1 addition & 1 deletion examples/factorization.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::sync::Arc;

use symbolica::{
atom::{Atom, AtomCore},
atom::Atom,
domains::{finite_field::Zp, integer::Z},
poly::{factor::Factorize, polynomial::MultivariatePolynomial, Variable},
state::State,
Expand Down
4 changes: 2 additions & 2 deletions examples/fibonacci.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use symbolica::{
atom::{Atom, AtomCore, AtomView},
atom::{Atom, AtomView},
id::{Match, Pattern, WildcardRestriction},
state::{RecycledAtom, State},
};
Expand Down Expand Up @@ -35,7 +35,7 @@ fn main() {
target.replace_all_into(&pattern, &rhs, Some(&restrictions), None, &mut out);

let mut out2 = RecycledAtom::new();
out.expand_into(None, &mut out2);
out.expand_into::<Atom>(None, &mut out2);

out2.replace_all_into(&lhs_zero_pat, &rhs_one, None, None, &mut out);

Expand Down
2 changes: 1 addition & 1 deletion examples/groebner_basis.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use symbolica::{
atom::{Atom, AtomCore},
atom::Atom,
domains::finite_field::Zp,
poly::{groebner::GroebnerBasis, polynomial::MultivariatePolynomial, GrevLexOrder},
state::State,
Expand Down
4 changes: 2 additions & 2 deletions examples/nested_evaluation.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use symbolica::{
atom::{Atom, AtomCore},
atom::{representation::BorrowedAtom, Atom},
domains::rational::Rational,
evaluate::{CompileOptions, FunctionMap, InlineASM, OptimizationSettings},
state::State,
Expand Down Expand Up @@ -64,7 +64,7 @@ fn main() {

let params = vec![Atom::parse("x").unwrap()];

let evaluator = Atom::evaluator_multiple(
let evaluator = BorrowedAtom::evaluator_multiple(
&[e1.as_view(), e2.as_view()],
&fn_map,
&params,
Expand Down
2 changes: 1 addition & 1 deletion examples/optimize.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use symbolica::{
atom::{Atom, AtomCore},
atom::Atom,
domains::rational::Q,
poly::evaluate::{BorrowedHornerScheme, InstructionSetPrinter},
};
Expand Down
2 changes: 1 addition & 1 deletion examples/optimize_multiple.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use symbolica::{
atom::{Atom, AtomCore},
atom::Atom,
domains::rational::Q,
poly::evaluate::{HornerScheme, InstructionSetPrinter},
};
Expand Down
2 changes: 1 addition & 1 deletion examples/partition.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use symbolica::{
atom::{Atom, AtomCore},
atom::Atom,
id::Pattern,
state::State,
transformer::Transformer,
Expand Down
2 changes: 1 addition & 1 deletion examples/pattern_match.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use symbolica::{
atom::{Atom, AtomCore},
atom::Atom,
id::Match,
state::State,
};
Expand Down
2 changes: 1 addition & 1 deletion examples/pattern_restrictions.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use symbolica::{
atom::{Atom, AtomCore, AtomView},
atom::{Atom, AtomView},
coefficient::CoefficientView,
domains::finite_field,
id::{Condition, Match, MatchSettings, WildcardRestriction},
Expand Down
2 changes: 1 addition & 1 deletion examples/polynomial_gcd.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use symbolica::{
atom::{Atom, AtomCore},
atom::Atom,
domains::{integer::Z, rational::Q},
};
use tracing_subscriber::{fmt, prelude::*, util::SubscriberInitExt, EnvFilter};
Expand Down
2 changes: 1 addition & 1 deletion examples/rational_polynomial.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use symbolica::{
atom::{Atom, AtomCore},
atom::Atom,
domains::{integer::Z, rational_polynomial::RationalPolynomial},
};

Expand Down
2 changes: 1 addition & 1 deletion examples/replace_all.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use symbolica::{
atom::{Atom, AtomCore},
atom::Atom,
id::Pattern,
};

Expand Down
2 changes: 1 addition & 1 deletion examples/replace_once.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use symbolica::atom::{Atom, AtomCore};
use symbolica::atom::Atom;

fn main() {
let expr = Atom::parse("f(z)*f(f(x))*f(y)").unwrap();
Expand Down
5 changes: 1 addition & 4 deletions examples/series.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
use symbolica::{
atom::{Atom, AtomCore},
state::State,
};
use symbolica::{atom::Atom, state::State};

fn main() {
let x = State::get_symbol("x");
Expand Down
7 changes: 5 additions & 2 deletions examples/solve_linear_system.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
use std::sync::Arc;

use symbolica::{
atom::{representation::InlineVar, Atom, AtomCore, AtomView},
atom::{
representation::{BorrowedAtom, InlineVar},
Atom,
},
domains::{
integer::Z,
rational::Q,
Expand All @@ -20,7 +23,7 @@ fn solve() {

let system: Vec<_> = eqs.iter().map(|e| Atom::parse(e).unwrap()).collect();

let sol = AtomView::solve_linear_system::<u8, _, InlineVar>(&system, &[x, y, z]).unwrap();
let sol = BorrowedAtom::solve_linear_system::<u8, _, InlineVar>(&system, &[x, y, z]).unwrap();

for (v, s) in ["x", "y", "z"].iter().zip(&sol) {
println!("{} = {}", v, s);
Expand Down
2 changes: 1 addition & 1 deletion examples/streaming.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use brotli::CompressorWriter;
use symbolica::{
atom::{Atom, AtomCore},
atom::Atom,
id::Pattern,
streaming::{TermStreamer, TermStreamerConfig},
};
Expand Down
2 changes: 1 addition & 1 deletion examples/tree_replace.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use symbolica::{
atom::{Atom, AtomCore},
atom::Atom,
id::Match,
state::State,
symb,
Expand Down
19 changes: 10 additions & 9 deletions src/api/python.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ use smartstring::{LazyCompact, SmartString};
use pyo3::pymodule;

use crate::{
atom::{Atom, AtomCore, AtomType, AtomView, ListIterator, Symbol},
atom::{Atom, AtomType, AtomView, BorrowedAtom, ListIterator, Symbol},
coefficient::CoefficientView,
domains::{
algebraic_number::AlgebraicExtension,
Expand Down Expand Up @@ -2978,7 +2978,7 @@ impl PythonExpression {
/// Add this expression to `other`, returning the result.
pub fn __add__(&self, rhs: ConvertibleToExpression) -> PyResult<PythonExpression> {
let rhs = rhs.to_expression();
Ok((self.expr.as_ref() + rhs.expr.as_ref()).into())
Ok((self.expr.as_ref() + rhs.expr).into())
}

/// Add this expression to `other`, returning the result.
Expand All @@ -3000,7 +3000,7 @@ impl PythonExpression {
/// Add this expression to `other`, returning the result.
pub fn __mul__(&self, rhs: ConvertibleToExpression) -> PyResult<PythonExpression> {
let rhs = rhs.to_expression();
Ok((self.expr.as_ref() * rhs.expr.as_ref()).into())
Ok((&self.expr * rhs.expr).into())
}

/// Add this expression to `other`, returning the result.
Expand All @@ -3011,7 +3011,7 @@ impl PythonExpression {
/// Divide this expression by `other`, returning the result.
pub fn __truediv__(&self, rhs: ConvertibleToExpression) -> PyResult<PythonExpression> {
let rhs = rhs.to_expression();
Ok((self.expr.as_ref() / rhs.expr.as_ref()).into())
Ok((&self.expr / rhs.expr).into())
}

/// Divide `other` by this expression, returning the result.
Expand Down Expand Up @@ -3062,7 +3062,7 @@ impl PythonExpression {

/// Negate the current expression, returning the result.
pub fn __neg__(&self) -> PyResult<PythonExpression> {
Ok((-self.expr.as_ref()).into())
Ok((-self.expr.clone()).into())
}

/// Return the length of the atom.
Expand Down Expand Up @@ -4511,7 +4511,7 @@ impl PythonExpression {
ReplaceIterator::new(
lhs,
target.as_view(),
crate::id::BorrowPatternOrMap::borrow(rhs),
crate::id::BorrowPatternOrMap::borrow_pat_map(rhs),
Some(res),
Some(settings),
)
Expand Down Expand Up @@ -5203,9 +5203,10 @@ impl PythonExpression {

let exprs = exprs.iter().map(|x| x.expr.as_view()).collect::<Vec<_>>();

let eval = Atom::evaluator_multiple(&exprs, &fn_map, &params, settings).map_err(|e| {
exceptions::PyValueError::new_err(format!("Could not create evaluator: {}", e))
})?;
let eval =
BorrowedAtom::evaluator_multiple(&exprs, &fn_map, &params, settings).map_err(|e| {
exceptions::PyValueError::new_err(format!("Could not create evaluator: {}", e))
})?;

let eval_f64 = eval.map_coeff(&|x| x.to_f64());

Expand Down
42 changes: 18 additions & 24 deletions src/atom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ mod coefficient;
mod core;
pub mod representation;

use representation::InlineVar;

use crate::{
coefficient::Coefficient,
parser::Token,
Expand All @@ -13,12 +11,11 @@ use crate::{
};
use std::{cmp::Ordering, hash::Hash, ops::DerefMut, str::FromStr};

pub use self::core::AtomCore;
use self::representation::RawAtom;
pub use self::representation::{
Add, AddView, Fun, KeyLookup, ListIterator, ListSlice, Mul, MulView, Num, NumView, Pow,
PowView, Var, VarView,
Add, AddView, BorrowedAtom, Fun, FunView, InlineNum, InlineVar, KeyLookup, ListIterator,
ListSlice, Mul, MulView, Num, NumView, Pow, PowView, Var, VarView,
};
use self::representation::{FunView, RawAtom};

/// A symbol, for example the name of a variable or the name of a function,
/// together with its properties.
Expand Down Expand Up @@ -816,7 +813,7 @@ impl Atom {
/// For example:
/// ```
/// # use symbolica::{
/// # atom::{Atom, AtomCore, FunctionBuilder},
/// # atom::{Atom,, FunctionBuilder},
/// # state::{FunctionAttribute, State},
/// # };
/// # fn main() {
Expand Down Expand Up @@ -844,19 +841,19 @@ impl FunctionBuilder {
}

/// Add an argument to the function.
pub fn add_arg<T: AtomCore>(mut self, arg: T) -> FunctionBuilder {
pub fn add_arg<T: AsRef<BorrowedAtom>>(mut self, arg: T) -> FunctionBuilder {
if let Atom::Fun(f) = self.handle.deref_mut() {
f.add_arg(arg.as_atom_view());
f.add_arg(arg.as_ref().to_view());
}

self
}

/// Add multiple arguments to the function.
pub fn add_args<T: AtomCore>(mut self, args: &[T]) -> FunctionBuilder {
pub fn add_args<T: AsRef<BorrowedAtom>>(mut self, args: &[T]) -> FunctionBuilder {
if let Atom::Fun(f) = self.handle.deref_mut() {
for a in args {
f.add_arg(a.as_atom_view());
f.add_arg(a.as_ref().to_view());
}
}

Expand Down Expand Up @@ -982,22 +979,23 @@ impl Atom {
}

/// Take the `self` to the power `exp`. Use [`Atom::npow()`] for a numerical power and [`Atom::rpow()`] for the reverse operation.
pub fn pow<T: AtomCore>(&self, exp: T) -> Atom {
pub fn pow<T: AsRef<BorrowedAtom>>(&self, exp: T) -> Atom {
Workspace::get_local().with(|ws| {
let mut t = ws.new_atom();
self.as_view()
.pow_no_norm(ws, exp.as_atom_view())
.pow_no_norm(ws, exp.as_ref().to_view())
.as_view()
.normalize(ws, &mut t);
t.into_inner()
})
}

/// Take `base` to the power `self`.
pub fn rpow<T: AtomCore>(&self, base: T) -> Atom {
pub fn rpow<T: AsRef<BorrowedAtom>>(&self, base: T) -> Atom {
Workspace::get_local().with(|ws| {
let mut t = ws.new_atom();
base.as_atom_view()
base.as_ref()
.to_view()
.pow_no_norm(ws, self.as_view())
.as_view()
.normalize(ws, &mut t);
Expand All @@ -1006,13 +1004,13 @@ impl Atom {
}

/// Add the atoms in `args`.
pub fn add_many<'a, T: AtomCore + Copy>(args: &[T]) -> Atom {
pub fn add_many<'a, T: AsRef<BorrowedAtom> + Copy>(args: &[T]) -> Atom {
let mut out = Atom::new();
Workspace::get_local().with(|ws| {
let mut t = ws.new_atom();
let add = t.to_add();
for a in args {
add.extend(a.as_atom_view());
add.extend(a.as_ref().to_view());
}

t.as_view().normalize(ws, &mut out);
Expand All @@ -1021,13 +1019,13 @@ impl Atom {
}

/// Multiply the atoms in `args`.
pub fn mul_many<'a, T: AtomCore + Copy>(args: &[T]) -> Atom {
pub fn mul_many<'a, T: AsRef<BorrowedAtom> + Copy>(args: &[T]) -> Atom {
let mut out = Atom::new();
Workspace::get_local().with(|ws| {
let mut t = ws.new_atom();
let add = t.to_mul();
for a in args {
add.extend(a.as_atom_view());
add.extend(a.as_ref().to_view());
}

t.as_view().normalize(ws, &mut out);
Expand Down Expand Up @@ -1538,11 +1536,7 @@ impl AsRef<Atom> for Atom {

#[cfg(test)]
mod test {
use crate::{
atom::{Atom, AtomCore},
fun,
state::State,
};
use crate::{atom::Atom, fun, state::State};

#[test]
fn debug() {
Expand Down
Loading

0 comments on commit e9c504b

Please sign in to comment.