aboutsummaryrefslogtreecommitdiffstats
path: root/src/modelica_model.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/modelica_model.rs')
-rw-r--r--src/modelica_model.rs178
1 files changed, 115 insertions, 63 deletions
diff --git a/src/modelica_model.rs b/src/modelica_model.rs
index 36c5a2e..81680d6 100644
--- a/src/modelica_model.rs
+++ b/src/modelica_model.rs
@@ -8,23 +8,29 @@ use std::collections::HashSet;
use self::modelica_parser::ast::*;
-//// Helpers
+/// / Helpers
pub trait ModelicaModelExt {
- fn get_constant_vars(&self) -> HashMap<String,Option<Expr>>;
+ fn get_constant_vars(&self) -> HashMap<String, Option<Expr>>;
fn get_free_vars(&self) -> Vec<String>;
- fn solve_for(&self, indep_vars: Vec<String>, dep_vars: Vec<String>) -> Result<ModelicaModel,String>;
+ fn solve_for(&self,
+ indep_vars: Vec<String>,
+ dep_vars: Vec<String>)
+ -> Result<ModelicaModel, String>;
}
impl ModelicaModelExt for ModelicaModel {
-
- fn get_constant_vars(&self) -> HashMap<String,Option<Expr>> {
+ fn get_constant_vars(&self) -> HashMap<String, Option<Expr>> {
let mut binds = HashMap::new();
// XXX: actually implement this...
for c in &self.components {
match c.prefix {
- Some(ComponentPrefix::Constant) => { binds.insert(c.name.clone(), Some(Expr::Integer(123))); },
- Some(ComponentPrefix::Parameter) => { binds.insert(c.name.clone(), Some(Expr::Float(4.56))); },
+ Some(ComponentPrefix::Constant) => {
+ binds.insert(c.name.clone(), Some(Expr::Integer(123)));
+ }
+ Some(ComponentPrefix::Parameter) => {
+ binds.insert(c.name.clone(), Some(Expr::Float(4.56)));
+ }
_ => (),
}
}
@@ -38,9 +44,10 @@ impl ModelicaModelExt for ModelicaModel {
fn get_free_vars(&self) -> Vec<String> {
// Start with components, and remove constants and parameters
let vars = self.components.iter().filter(|v| match v.prefix {
- Some(ComponentPrefix::Constant) | Some(ComponentPrefix::Parameter) => false,
- _ => true,
- });
+ Some(ComponentPrefix::Constant) |
+ Some(ComponentPrefix::Parameter) => false,
+ _ => true,
+ });
// Remove LHS (bound) vars
let mut outputs = vec![];
@@ -63,7 +70,10 @@ impl ModelicaModelExt for ModelicaModel {
// N equations with unknowns
//
// TODO: allow passing in Q
- fn solve_for(&self, indep_vars: Vec<String>, dep_vars: Vec<String>) -> Result<ModelicaModel,String> {
+ fn solve_for(&self,
+ indep_vars: Vec<String>,
+ dep_vars: Vec<String>)
+ -> Result<ModelicaModel, String> {
let constants = self.get_constant_vars();
let mut all_vars: HashSet<String> = HashSet::new();
for eqn in &self.equations {
@@ -82,25 +92,30 @@ impl ModelicaModelExt for ModelicaModel {
// check that V = Q + P + M
if all_vars.len() != (constants.len() + indep_vars.len() + dep_vars.len()) {
return Err(format!("Variable counts don't add up (V={} Q={} P={} M={})",
- all_vars.len(),
- constants.len(),
- indep_vars.len(),
- dep_vars.len()));
+ all_vars.len(),
+ constants.len(),
+ indep_vars.len(),
+ dep_vars.len()));
}
// check that all constants are bound and simple
for (name, value) in &constants {
match *value {
None => return Err(format!("UnderSpecifiedConstant: {}", name)),
- Some(Expr::Integer(_)) | Some(Expr::Float(_)) => (), // Ok,
- Some(_) => return Err(format!("NaiveImplementation: can't handle constant: {}", name)),
+ Some(Expr::Integer(_)) |
+ Some(Expr::Float(_)) => (), // Ok,
+ Some(_) => {
+ return Err(format!("NaiveImplementation: can't handle constant: {}", name))
+ }
}
}
// check that there is a depdendent variable in each equation
for eqn in &self.equations {
if intersect_strings(&dep_vars, &eqn.identifiers()).len() == 0 {
- return Err("NaiveImplementation/OverConstrained: at least one equation is missing a dependent variable".to_string());
+ return Err("NaiveImplementation/OverConstrained: at least one equation is \
+ missing a dependent variable"
+ .to_string());
}
}
@@ -110,17 +125,21 @@ impl ModelicaModelExt for ModelicaModel {
}
println!("Soliving for {:?} in terms of params {:?} and constants {:?}, with {} equations",
- dep_vars, indep_vars, constants, self.equations.len());
+ dep_vars,
+ indep_vars,
+ constants,
+ self.equations.len());
let mut unsolved_eqns = self.equations.clone();
let mut solved: Vec<SimpleEquation> = vec![];
let mut unsolved_vars = dep_vars.clone();
while unsolved_eqns.len() > 0 {
- let next_i = unsolved_eqns
- .iter()
+ let next_i = unsolved_eqns.iter()
.position(|ref x| intersect_strings(&unsolved_vars, &x.identifiers()).len() == 1);
let eqn = match next_i {
- None => { return Err("NaiveImplementation (or poor equation selection?)".to_string()); },
+ None => {
+ return Err("NaiveImplementation (or poor equation selection?)".to_string());
+ }
Some(i) => unsolved_eqns.remove(i),
};
let ref var = intersect_strings(&unsolved_vars, &eqn.identifiers())[0];
@@ -128,10 +147,10 @@ impl ModelicaModelExt for ModelicaModel {
solved.push(eqn);
let var_i = unsolved_vars.iter().position(|ref x| x == &var).unwrap();
unsolved_vars.remove(var_i);
- };
+ }
// TODO: sort output equations by LHS
- Ok(ModelicaModel{
+ Ok(ModelicaModel {
name: self.name.clone(),
description: self.description.clone(),
components: self.components.clone(),
@@ -152,13 +171,12 @@ fn intersect_strings(a: &Vec<String>, b: &Vec<String>) -> Vec<String> {
}
pub trait SimpleEquationExt {
- fn rebalance_for(&self, ident: String) -> Result<SimpleEquation,String>;
- fn simplify_lhs(&self, ident: &str) -> Result<SimpleEquation,String>;
+ fn rebalance_for(&self, ident: String) -> Result<SimpleEquation, String>;
+ fn simplify_lhs(&self, ident: &str) -> Result<SimpleEquation, String>;
}
impl SimpleEquationExt for SimpleEquation {
-
- fn rebalance_for(&self, ident: String) -> Result<SimpleEquation,String> {
+ fn rebalance_for(&self, ident: String) -> Result<SimpleEquation, String> {
let lvars = self.lhs.identifiers();
let rvars = self.rhs.identifiers();
@@ -166,9 +184,13 @@ impl SimpleEquationExt for SimpleEquation {
(true, true) => Err("SymbolicError: NaiveImplementation".to_string()),
(false, false) => Err("SymbolicError: VariableNotFound".to_string()),
(true, false) => self.simplify_lhs(&ident),
- (false, true) =>
- SimpleEquation{lhs: self.rhs.clone(),
- rhs: self.lhs.clone()}.simplify_lhs(&ident),
+ (false, true) => {
+ SimpleEquation {
+ lhs: self.rhs.clone(),
+ rhs: self.lhs.clone(),
+ }
+ .simplify_lhs(&ident)
+ }
};
match ret {
Ok(eqn) => {
@@ -176,56 +198,86 @@ impl SimpleEquationExt for SimpleEquation {
Err("SymbolicError: NaiveImplementation".to_string())
} else {
Ok(eqn)
- }},
+ }
+ }
Err(_) => ret,
}
}
- fn simplify_lhs(&self, ident: &str) -> Result<SimpleEquation,String> {
+ fn simplify_lhs(&self, ident: &str) -> Result<SimpleEquation, String> {
use modelica_parser::ast::Expr::*;
use modelica_parser::ast::BinOperator::*;
match self.lhs {
Ident(ref s) if s == ident => Ok((*self).clone()),
- Ident(_) | Integer(_) | Float(_) | Boolean(_) | StringLiteral(_) =>
- Err("SymbolicError: InternalError: expected var on LHS".to_string()),
- Der(_) | MathUnaryExpr(_,_) | Sign(_) | Array(_) =>
- Err("SymbolicError: NaiveImplementation: can't simplify".to_string()),
+ Ident(_) | Integer(_) | Float(_) | Boolean(_) | StringLiteral(_) => {
+ Err("SymbolicError: InternalError: expected var on LHS".to_string())
+ }
+ Der(_) |
+ MathUnaryExpr(_, _) |
+ Sign(_) |
+ Array(_) => Err("SymbolicError: NaiveImplementation: can't simplify".to_string()),
// TODO: create a macro for the below...
BinExpr(Multiply, ref a, ref b) if a.contains(ident) => {
- SimpleEquation{
- lhs: *a.clone(),
- rhs: BinExpr(Divide, Box::new(self.rhs.clone()), b.clone())}.simplify_lhs(&ident) },
+ SimpleEquation {
+ lhs: *a.clone(),
+ rhs: BinExpr(Divide, Box::new(self.rhs.clone()), b.clone()),
+ }
+ .simplify_lhs(&ident)
+ }
BinExpr(Multiply, ref a, ref b) if b.contains(ident) => {
- SimpleEquation{
- lhs: *b.clone(),
- rhs: BinExpr(Divide, Box::new(self.rhs.clone()), a.clone())}.simplify_lhs(&ident) },
+ SimpleEquation {
+ lhs: *b.clone(),
+ rhs: BinExpr(Divide, Box::new(self.rhs.clone()), a.clone()),
+ }
+ .simplify_lhs(&ident)
+ }
BinExpr(Divide, ref a, ref b) if a.contains(ident) => {
- SimpleEquation{
- lhs: *a.clone(),
- rhs: BinExpr(Multiply, Box::new(self.rhs.clone()), b.clone())}.simplify_lhs(&ident) },
+ SimpleEquation {
+ lhs: *a.clone(),
+ rhs: BinExpr(Multiply, Box::new(self.rhs.clone()), b.clone()),
+ }
+ .simplify_lhs(&ident)
+ }
BinExpr(Divide, ref a, ref b) if b.contains(ident) => {
- SimpleEquation{
- lhs: *b.clone(),
- rhs: BinExpr(Divide, a.clone(), Box::new(self.rhs.clone()))}.simplify_lhs(&ident) },
+ SimpleEquation {
+ lhs: *b.clone(),
+ rhs: BinExpr(Divide, a.clone(), Box::new(self.rhs.clone())),
+ }
+ .simplify_lhs(&ident)
+ }
BinExpr(Add, ref a, ref b) if a.contains(ident) => {
- SimpleEquation{
- lhs: *a.clone(),
- rhs: BinExpr(Subtract, Box::new(self.rhs.clone()), b.clone())}.simplify_lhs(&ident) },
+ SimpleEquation {
+ lhs: *a.clone(),
+ rhs: BinExpr(Subtract, Box::new(self.rhs.clone()), b.clone()),
+ }
+ .simplify_lhs(&ident)
+ }
BinExpr(Add, ref a, ref b) if b.contains(ident) => {
- SimpleEquation{
- lhs: *b.clone(),
- rhs: BinExpr(Subtract, Box::new(self.rhs.clone()), a.clone())}.simplify_lhs(&ident) },
+ SimpleEquation {
+ lhs: *b.clone(),
+ rhs: BinExpr(Subtract, Box::new(self.rhs.clone()), a.clone()),
+ }
+ .simplify_lhs(&ident)
+ }
BinExpr(Subtract, ref a, ref b) if a.contains(ident) => {
- SimpleEquation{
- lhs: *a.clone(),
- rhs: BinExpr(Add, Box::new(self.rhs.clone()), b.clone())}.simplify_lhs(&ident) },
+ SimpleEquation {
+ lhs: *a.clone(),
+ rhs: BinExpr(Add, Box::new(self.rhs.clone()), b.clone()),
+ }
+ .simplify_lhs(&ident)
+ }
BinExpr(Subtract, ref a, ref b) if b.contains(ident) => {
- SimpleEquation{
- lhs: *b.clone(),
- rhs: BinExpr(Subtract, a.clone(), Box::new(self.rhs.clone()))}.simplify_lhs(&ident) },
- BinExpr(_, _, _) => Err("SymbolicError: NotImplemented BinOperator (or else couldn't find var...)".to_string()),
+ SimpleEquation {
+ lhs: *b.clone(),
+ rhs: BinExpr(Subtract, a.clone(), Box::new(self.rhs.clone())),
+ }
+ .simplify_lhs(&ident)
+ }
+ BinExpr(_, _, _) => {
+ Err("SymbolicError: NotImplemented BinOperator (or else couldn't find var...)"
+ .to_string())
+ }
// in case we add opers: _ => Err("NotImplemented".to_string()),
}
}
}
-