Equation

Struct Equation 

Source
pub struct Equation { /* private fields */ }
Expand description

A Chemical Equation. Containing a left and right side. Also keeps track of the mol ratio.

Eg: 4Fe + 3O2 -> 2Fe2O3

Implementations§

Source§

impl Equation

Source

pub fn new(input: &str) -> Result<Self, EquationError>

Create an Equation from a str. Fails if the string couldn’t be parsed.

§Examples
use chem_eq::{Equation, error::EquationError};

let eq = Equation::new("2H2 + O2 -> 2H2O");
assert!(eq.is_ok());

let eq = Equation::new("H2b + bad_name == joe");
assert!(matches!(eq, Err(EquationError::ParsingError(_))));
Examples found in repository?
examples/balance.rs (line 13)
8fn main() -> Result<(), Box<dyn Error>> {
9    let mut buf = String::new();
10    print!("Input equation: ");
11    io::stdout().flush()?;
12    io::stdin().read_line(&mut buf)?;
13    let solved = Equation::new(buf.as_str())?.to_balancer().balance()?;
14    println!("solved: {}", solved);
15
16    Ok(())
17}
More examples
Hide additional examples
examples/parse.rs (line 10)
5fn main() -> io::Result<()> {
6    let mut input = String::default();
7    print!("Input equation: ");
8    io::stdout().flush()?;
9    io::stdin().read_line(&mut input)?;
10    let eq = Equation::new(input.as_str()).unwrap();
11    println!("eq = {:?}", eq);
12    println!("back = {}", eq);
13
14    Ok(())
15}
Source

pub fn mol_ratio(&self) -> (usize, usize)

Get the mol ratio of the equation (left over right). Will count any compound with no specified state.

§Examples
use chem_eq::Equation;

// returns left over right
// if states aren't given, everything is counted
let eq = Equation::new("2H2 + O2 -> 2H2O").unwrap();
assert_eq!(eq.mol_ratio(), (3, 2));

// doesn't matter how bad an equation this is...
let eq = Equation::new("4FeH3(s) + 3O2(g) -> 2Fe2O3(s) + 6H2(g)").unwrap();
assert_eq!(eq.mol_ratio(), (3, 6));
Source

pub fn uniq_elements(&self) -> Vec<&str>

Get a vec of each unique element name

§Examples
use chem_eq::Equation;

let eq = Equation::new("2O2 + H2 -> 2H2O").unwrap();
assert_eq!(eq.uniq_elements().len(), 2);

let eq =
    Equation::new("3(NH4)2SO4(aq) + Fe3(PO4)2(s) <- 2(NH4)3PO4(aq) + 3FeSO4(aq)").unwrap();
assert_eq!(eq.uniq_elements().len(), 6);
Source

pub fn num_compounds(&self) -> usize

Count how many compounds are in the whole equation.

§Examples
use chem_eq::Equation;

let eq = Equation::new("O2 + 2H2 -> 2H2O").unwrap();
assert_eq!(eq.num_compounds(), 3);

let eq = Equation::new("3(NH4)2SO4(aq) + Fe3(PO4)2(s) <- 2(NH4)3PO4(aq) + 3FeSO4(aq)").unwrap();
assert_eq!(eq.num_compounds(), 4);
Source

pub fn reconstruct(&self) -> String

Reconstruct original equation without using the saved original string.

§Examples
use chem_eq::Equation;

let eq = Equation::new("O2 + H2 -> H2O").unwrap();
assert_eq!(eq.reconstruct(), "1O2 + 1H2 -> 1H2O1");
Source

pub fn iter_compounds(&self) -> impl Iterator<Item = &Compound>

Create an iterator over all compounds of an equation

§Examples
use chem_eq::{Equation, Compound};

let eq = Equation::new("O2 + H2 -> H2O").unwrap();
assert_eq!(eq.iter_compounds().collect::<Vec<&Compound>>().len(), 3);
Source

pub fn iter_compounds_mut(&mut self) -> impl Iterator<Item = &mut Compound>

Create a mutable iterator over all compounds of an equation.

§Examples
use chem_eq::{Equation, Compound};

let mut eq = Equation::new("O2 + H2 -> H2O").unwrap();
assert_eq!(eq.iter_compounds_mut().collect::<Vec<&mut Compound>>().len(), 3);
Source

pub fn is_balanced(&self) -> bool

Available on crate feature balance only.

Check if the equation is balanced

§Examples
use chem_eq::Equation;

let eq = Equation::new("C + 2H2O -> CO2 + 2H2").unwrap();
assert!(eq.is_balanced());

let eq = Equation::new("Mg(OH)2 + Fe -> Fe(OH)3 + Mg").unwrap();
assert!(!eq.is_balanced());
Source

pub fn to_balancer(&self) -> EquationBalancer<'_>

Available on crate feature balance only.

Create an EquationBalancer, mostly as a convenience method.

§Examples
use chem_eq::Equation;

let eq = Equation::new("H2 + O2 -> H2O").unwrap().to_balancer().balance().unwrap();
assert_eq!(eq.equation(), "2H2 + O2 -> 2H2O".to_string());
Examples found in repository?
examples/balance.rs (line 13)
8fn main() -> Result<(), Box<dyn Error>> {
9    let mut buf = String::new();
10    print!("Input equation: ");
11    io::stdout().flush()?;
12    io::stdin().read_line(&mut buf)?;
13    let solved = Equation::new(buf.as_str())?.to_balancer().balance()?;
14    println!("solved: {}", solved);
15
16    Ok(())
17}
Source

pub fn is_exothermic(&self) -> bool

Check whether an equation is exothermic

§Examples
use chem_eq::Equation;

let mut eq = Equation::new("2Mg(s) + O2(g) -> 2MgO(s)").unwrap();
eq.set_delta_h(-601.1);
assert!(eq.is_exothermic());
Source

pub fn is_endothermic(&self) -> bool

Check whether an equation is endothermic

§Examples
use chem_eq::Equation;

let mut eq = Equation::new("6CO2 + 6H2O -> C6H12O6 + 6O2").unwrap();
eq.set_delta_h(2802.7);
assert!(eq.is_endothermic());
Source

pub fn compound_names(&self) -> impl Iterator<Item = &str>

Get an iterator over each compounds name.

§Examples
use chem_eq::Equation;

let eq = Equation::new("H2 + O2 -> H2O").unwrap();
assert_eq!(vec!["H2", "O2", "H2O"], eq.compound_names().collect::<Vec<&str>>());

let eq = Equation::new("Fe2O3 <- Fe + O2").unwrap();
assert_eq!(vec!["Fe2O3", "Fe", "O2"], eq.compound_names().collect::<Vec<&str>>());
Source

pub fn concentrations(&self) -> impl Iterator<Item = &f32>

Get an iterator for each concentration in an equation

Source

pub fn concentrations_mut(&mut self) -> impl Iterator<Item = &mut f32>

Get a mutable iterator for each concentration in an equation

Source

pub fn name_and_concentration(&self) -> impl Iterator<Item = (&str, &f32)>

Get an iterator yielding compound names and concentrations

Source

pub fn name_and_concentration_mut( &mut self, ) -> impl Iterator<Item = (String, &mut f32)>

Get a mutable iterator yielding compound names and mutable concentrations

Source

pub fn get_concentrations(&self) -> Vec<f32>

Get a vec of all concentrations

§Examples
use chem_eq::Equation;

let mut eq = Equation::new("H2 + O2 -> H2O").unwrap();
assert_eq!(eq.get_concentrations(), vec![0.0, 0.0, 0.0]);

eq.set_concentrations(&[1.0, 2.0, 3.0]);
assert_eq!(eq.get_concentrations(), vec![1.0, 2.0, 3.0]);
Source

pub fn set_concentrations( &mut self, concentrations: &[f32], ) -> Result<(), ConcentrationError>

Set concentrations with a slice. A convenience method to quickly set all compounds to have a concentration.

§Examples
use chem_eq::{Equation, error::ConcentrationError};

let mut eq = Equation::new("H2 + O2 -> H2O").unwrap();
eq.set_concentrations(&[1.0, 2.0, 3.0]).unwrap();
assert_eq!(eq.get_concentrations(), vec![1.0, 2.0, 3.0]);

assert_eq!(eq.set_concentrations(&[1.0, 34.0]), Err(ConcentrationError::WrongSliceSize));
Source

pub fn get_concentration_by_name( &self, name: &str, ) -> Result<f32, ConcentrationNameError>

Get a singular compounds concentration by its name.

§Examples
use chem_eq::{Equation, error::ConcentrationNameError};

let mut eq = Equation::new("H2 + O2 -> H2O").unwrap();
eq.set_concentration_by_name("O2", 0.25).unwrap();
assert_eq!(eq.get_concentration_by_name("O2"), Ok(0.25));

assert_eq!(eq.get_concentration_by_name("joe"), Err(ConcentrationNameError::NotFound));
Source

pub fn get_compound_by_name(&self, name: &str) -> Option<&Compound>

Get a compound by name

§Examples
use chem_eq::{Equation, Compound};

let mut eq = Equation::new("H2 + O2 -> H2O").unwrap();
let cmp = eq.get_compound_by_name("O2");
assert_eq!(cmp.unwrap(), &Compound::parse("O2").unwrap());

assert!(eq.get_compound_by_name("joe").is_none());
Source

pub fn get_compound_by_name_mut(&mut self, name: &str) -> Option<&mut Compound>

Get a mutable reference to a compound by name

§Examples
use chem_eq::{Equation, Compound};

let mut eq = Equation::new("H2 + O2 -> H2O").unwrap();
let cmp = eq.get_compound_by_name_mut("O2");
assert_eq!(cmp.unwrap(), &mut Compound::parse("O2").unwrap());

assert!(eq.get_compound_by_name("joe").is_none());
Source

pub fn set_concentration_by_name( &mut self, name: &str, concentration: f32, ) -> Result<(), ConcentrationNameError>

Set a singular compounds concentration by its name.

§Examples
use chem_eq::{Equation, error::ConcentrationNameError};

let mut eq = Equation::new("H2 + O2 -> H2O").unwrap();
eq.set_concentration_by_name("O2", 0.25).unwrap();
assert_eq!(eq.get_concentrations(), vec![0.0, 0.25, 0.0]);

assert_eq!(eq.set_concentration_by_name("joe", 24.0), Err(ConcentrationNameError::NotFound));
assert_eq!(eq.set_concentration_by_name("H2O", f32::NAN), Err(ConcentrationNameError::NAN));
Source

pub fn equilibrium_constant(&self) -> Option<f32>

Get the k expression or Kc of an equation. Returns None if one side has a compound with a concentration of 0

§Examples
use chem_eq::Equation;

let eq = Equation::new("H2 + O2 -> H2O").unwrap();
// is nan because all compounds have an initial concentration of 0M
assert!(eq.equilibrium_constant().is_none());

let mut eq = Equation::new("N2 + 2O2 -> 2NO2").unwrap();
eq.set_concentrations(&[0.25, 0.50, 0.75]).unwrap();
assert_eq!(eq.equilibrium_constant().unwrap(), (0.75 * 0.75) / (0.25 * 0.5 * 0.5));
Source

pub fn reaction_quotient(&self) -> ReactionQuotient

Get Qc of the equation, called the reaction coefficient. It’s calculated the same way as the k-expression, however it can apply to non equilibrium concentrations.

§Returns

Assuming the hypothetical reaction where a, b, c, and d are the coefficents of A, B, C and D respectively:

aA + bB <-> cC + dD

Since Qc = ([C]^c * [D]^d) / ([A]^a * [B]^b), This function will return:

Source

pub fn nth_compound(&self, idx: usize) -> Option<&Compound>

Get the nth compound of the equation.

§Examples
use chem_eq::{Equation, Compound};

let eq = Equation::new("H2 + O2 -> H2O").unwrap();
assert_eq!(eq.nth_compound(0).unwrap(), &Compound::parse("H2").unwrap());
assert_eq!(eq.nth_compound(1).unwrap(), &Compound::parse("O2").unwrap());
assert_eq!(eq.nth_compound(2).unwrap(), &Compound::parse("H2O").unwrap());
assert!(eq.nth_compound(3).is_none());
Source

pub fn nth_compound_mut(&mut self, idx: usize) -> Option<&mut Compound>

Get the nth compound of the equation mutably.

§Examples
use chem_eq::{Equation, Compound};

let mut eq = Equation::new("H2 + O2 -> H2O").unwrap();
assert_eq!(eq.nth_compound_mut(0).unwrap(), &mut Compound::parse("H2").unwrap());
assert_eq!(eq.nth_compound_mut(1).unwrap(), &mut Compound::parse("O2").unwrap());
assert_eq!(eq.nth_compound_mut(2).unwrap(), &mut Compound::parse("H2O").unwrap());
assert!(eq.nth_compound_mut(3).is_none());
Source

pub fn left(&self) -> &[Compound]

Getter for the left side of the equation.

Source

pub fn left_mut(&mut self) -> &mut Vec<Compound>

Mut getter for the right side of the equation

Source

pub fn right(&self) -> &[Compound]

Getter for the right side of the equation

Source

pub fn right_mut(&mut self) -> &mut Vec<Compound>

Mut getter for the right side of the equation

Source

pub const fn direction(&self) -> &Direction

Getter for the direction of the equation

Source

pub fn equation(&self) -> &str

Getter for the equation as text

Source

pub const fn delta_h(&self) -> f32

Getter for delta_h in kJ

Source

pub fn set_delta_h(&mut self, delta_h: f32)

Setter for delta_h in kJ

Source

pub const fn temperature(&self) -> Option<f32>

Getter for temperature in degrees Celsius

Source

pub fn set_temperature(&mut self, temperature: f32)

Setter for temperature in degrees Celsius

Source

pub const fn volume(&self) -> Option<f32>

Getter for the volume equation in litres

Source

pub fn set_volume(&mut self, volume: f32)

Setter for volume in Litres

Trait Implementations§

Source§

impl Clone for Equation

Source§

fn clone(&self) -> Equation

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Equation

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Equation

Source§

fn default() -> Equation

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Equation

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for Equation

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'a> From<&'a Equation> for EquationBalancer<'a>

Available on crate feature balance only.
Source§

fn from(eq: &'a Equation) -> Self

Create matrix for solving out of equation

Source§

impl FromStr for Equation

Source§

type Err = EquationError

The associated error which can be returned from parsing.
Source§

fn from_str(s: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
Source§

impl PartialEq for Equation

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialOrd for Equation

Source§

fn partial_cmp(&self, other: &Equation) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Serialize for Equation

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl TryFrom<&str> for Equation

Source§

type Error = EquationError

The type returned in the event of a conversion error.
Source§

fn try_from(s: &str) -> Result<Self, EquationError>

Performs the conversion.
Source§

impl Eq for Equation

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,