aboutsummaryrefslogtreecommitdiffstats
path: root/src/modelica_model.rs
blob: 40b83d661c8eb8c688bf8393ee4a8ef97bc850f4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302

extern crate modelica_parser;

use std::clone::Clone;
use std::collections::HashMap;
use std::collections::HashSet;
use std::iter::FromIterator;

use self::modelica_parser::*;
use errors::Result;


/// Helpers

pub trait ModelicaModelExt {
    fn get_constant_vars(&self) -> HashMap<String, Option<Expr>>;
    fn get_free_vars(&self) -> HashSet<String>;
    fn solve_for(&self,
                 indep_vars: Vec<String>,
                 dep_vars: Vec<String>)
                 -> Result<ModelicaModel>;
}

impl ModelicaModelExt for ModelicaModel {
    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)));
                }
                _ => (),
            }
        }
        binds
    }

    // This crude function finds "unbound" variables: those which are not constants, parameters, or
    // the sole element on the LHS of an equation.
    // Bugs:
    //   if a var is on LHS and RHS of same equation
    fn get_free_vars(&self) -> HashSet<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,
        });

        // Remove LHS (bound) vars
        let mut outputs = vec![];
        for eq in self.equations.iter() {
            // TODO:
            if let Expr::Ident(ref symb) = eq.lhs {
                outputs.push(symb.to_string());
            }
        }
        let vars = vars.filter(|v| !outputs.contains(&v.name));

        vars.map(|c| c.name.clone()).collect()
    }

    // V variables
    // Q constants (become kwargs)
    // P bound vars (independent, inputs/passed, become like constants)
    // M unknowns (dependent, outputs)
    // N' total equations
    // N equations with unknowns
    //
    // TODO: allow passing in Q
    fn solve_for(&self,
                 indep_vars: Vec<String>,
                 dep_vars: Vec<String>)
                 -> Result<ModelicaModel> {

        let indep_vars: HashSet<String> = HashSet::from_iter(indep_vars);
        let dep_vars: HashSet<String> = HashSet::from_iter(dep_vars);
        let constants = self.get_constant_vars();
        let mut all_vars: HashSet<String> = HashSet::new();
        for eqn in &self.equations {
            all_vars.extend(eqn.identifiers());
        }

        // check that all dep and indep are in equations
        let mut passed_vars = indep_vars.clone();
        passed_vars.extend(dep_vars.clone());
        for var in passed_vars {
            if !all_vars.contains(&var) {
                return bail!("Variable not found in equations: {}", var);
            }
        }

        // check that  V = Q + P + M
        if all_vars.len() != (constants.len() + indep_vars.len() + dep_vars.len()) {
            return bail!("Variable counts don't add up (V={} Q={} P={} M={})",
                               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 => bail!("UnderSpecifiedConstant: {}", name),
                Some(Expr::Integer(_)) |
                Some(Expr::Float(_)) => (), // Ok,
                Some(_) => {
                    bail!("NaiveImplementation: can't handle constant: {}", name);
                }
            }
        }

        // check that there is a depdendent variable in each equation
        for eqn in &self.equations {
            if dep_vars.is_disjoint(&eqn.identifiers()) {
                bail!("NaiveImplementation/OverConstrained: at least one equation is \
                        missing a dependent variable")
            }
        }

        // check N >= M
        if self.equations.len() < dep_vars.len() {
            bail!("UnderConstrained: more dependent variables than equations");
        }

        println!("Soliving for {:?} in terms of params {:?} and constants {:?}, with {} equations",
                 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()
                .position(|ref x| unsolved_vars.intersection(&x.identifiers()).count() == 1);
            let eqn = match next_i {
                None => {
                    return bail!("NaiveImplementation (or poor equation selection?)");
                }
                Some(i) => unsolved_eqns.remove(i),
            };
            let eqn_tmp = eqn.identifiers();
            let ref var = unsolved_vars.intersection(&eqn_tmp).nth(0).unwrap().clone();
            let eqn = eqn.rebalance_for(var.to_string()).expect("rebalance for success");
            // Replace all other references to var with RHS of solved equation
            unsolved_eqns = unsolved_eqns.iter().map(|ref e|
                SimpleEquation{
                    lhs: substitute_with(&e.lhs, &Expr::Ident(var.to_string()), &eqn.rhs),
                    rhs: substitute_with(&e.rhs, &Expr::Ident(var.to_string()), &eqn.rhs),
                }).collect();
            solved.push(eqn);
            unsolved_vars.remove(var);
        }

        Ok(ModelicaModel {
            name: self.name.clone(),
            description: self.description.clone(),
            components: self.components.clone(),
            connections: vec![],
            equations: solved,
        })
    }
}

// Recurses through 'original', replacing all instances of 'a' with 'b'
pub fn substitute_with(original: &Expr, a: &Expr, b: &Expr) -> Expr {
    use modelica_parser::Expr::*;
    println!("original: {:?}  replacing: {:?}   with: {:?}", original, a, b);
    if *original == *a {
        return b.clone();
    }
    match *original {
        Integer(_) | Float(_) | Boolean(_) | StringLiteral(_) | Ident(_) => original.clone(),
        Der(ref e) => Der(Box::new(substitute_with(e, a, b))),
        Sign(ref e) => Sign(Box::new(substitute_with(e, a, b))),
        MathUnaryExpr(muf, ref e) =>
            MathUnaryExpr(muf, Box::new(substitute_with(e, a, b))),
        BinExpr(bo, ref e1, ref e2) =>
            BinExpr(bo,
                    Box::new(substitute_with(e1, a, b)),
                    Box::new(substitute_with(e2, a, b))),
        Array(ref l) => Array(l.iter().map(|ref e| substitute_with(e, a, b)).collect()),
    }
}

pub trait SimpleEquationExt {
    fn rebalance_for(&self, ident: String) -> Result<SimpleEquation>;
    fn simplify_lhs(&self, ident: &str) -> Result<SimpleEquation>;
}

impl SimpleEquationExt for SimpleEquation {
    fn rebalance_for(&self, ident: String) -> Result<SimpleEquation> {
        let lvars = self.lhs.identifiers();
        let rvars = self.rhs.identifiers();

        let ret = match (lvars.contains(&ident), rvars.contains(&ident)) {
            (true, true) => bail!("SymbolicError: NaiveImplementation"),
            (false, false) => bail!("SymbolicError: VariableNotFound"),
            (true, false) => self.simplify_lhs(&ident),
            (false, true) => {
                SimpleEquation {
                        lhs: self.rhs.clone(),
                        rhs: self.lhs.clone(),
                    }
                    .simplify_lhs(&ident)
            }
        };
        match ret {
            Ok(eqn) => {
                if eqn.rhs.contains(&ident) {
                    bail!("SymbolicError: NaiveImplementation")
                } else {
                    Ok(eqn)
                }
            }
            Err(_) => ret,
        }
    }

    fn simplify_lhs(&self, ident: &str) -> Result<SimpleEquation> {
        use modelica_parser::Expr::*;
        use modelica_parser::BinOperator::*;
        match self.lhs {
            Ident(ref s) if s == ident => Ok((*self).clone()),
            Ident(_) | Integer(_) | Float(_) | Boolean(_) | StringLiteral(_) => {
                bail!("SymbolicError: InternalError: expected var on LHS")
            }
            Der(_) |
            MathUnaryExpr(_, _) |
            Sign(_) |
            Array(_) => bail!("SymbolicError: NaiveImplementation: can't simplify"),
            // 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)
            }
            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)
            }
            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)
            }
            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)
            }
            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)
            }
            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)
            }
            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)
            }
            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(_, _, _) => {
                bail!("SymbolicError: NotImplemented BinOperator (or else couldn't find var...)")
            }
            // in case we add opers: _ => Err("NotImplemented".to_string()),
        }
    }
}