lilypond-0.0.40
[lilypond.git] / lily / qlp.cc
blobe6696acf39966b4a25c72a77f70d89f67d898370
1 #include "debug.hh"
2 #include "const.hh"
3 #include "qlp.hh"
4 #include "choleski.hh"
6 void
7 Mixed_qp::add_equality_cons(Vector , double )
9 assert(false);
12 void
13 Mixed_qp::add_fixed_var(int i, Real r)
15 eq_cons.push(i);
16 eq_consrhs.push(r);
19 void
20 Ineq_constrained_qp::add_inequality_cons(Vector c, double r)
22 cons.push(c);
23 consrhs.push(r);
26 Ineq_constrained_qp::Ineq_constrained_qp(int novars):
27 quad(novars),
28 lin(novars),
29 const_term (0.0)
33 void
34 Ineq_constrained_qp::OK() const
36 #ifndef NDEBUG
37 assert(cons.size() == consrhs.size());
38 Matrix Qdif= quad - quad.transposed();
39 assert(Qdif.norm()/quad.norm() < EPS);
40 #endif
44 Real
45 Ineq_constrained_qp::eval (Vector v)
47 return v * quad * v + lin * v + const_term;
50 /**
51 eliminate appropriate variables, until we have a Ineq_constrained_qp
52 then solve that.
54 PRE
55 cons should be ascending
57 Vector
58 Mixed_qp::solve(Vector start) const
60 print();
61 Ineq_constrained_qp pure(*this);
63 for (int i= eq_cons.size()-1; i>=0; i--) {
64 pure.eliminate_var(eq_cons[i], eq_consrhs[i]);
65 start.del(eq_cons[i]);
67 Vector sol = pure.solve(start);
68 for (int i= 0; i < eq_cons.size(); i++) {
69 sol.insert( eq_consrhs[i],eq_cons[i]);
71 return sol;
75 assume x(idx) == value, and adjust constraints, lin and quad accordingly
77 TODO: add const_term
79 void
80 Ineq_constrained_qp::eliminate_var(int idx, Real value)
82 Vector row(quad.row(idx));
83 row*= value;
85 quad.delete_row(idx);
87 quad.delete_column(idx);
89 lin.del(idx);
90 row.del(idx);
91 lin +=row ;
93 for (int i=0; i < cons.size(); i++) {
94 consrhs[i] -= cons[i](idx) *value;
95 cons[i].del(idx);
101 void
102 Ineq_constrained_qp::assert_solution(Vector sol) const
104 Array<int> binding;
105 for (int i=0; i < cons.size(); i++) {
106 Real R=cons[i] * sol- consrhs[i];
107 assert(R> -EPS);
108 if (R < EPS)
109 binding.push(i);
111 // KKT check...
112 // todo
115 void
116 Ineq_constrained_qp::print() const
118 #ifndef NPRINT
119 mtor << "Quad " << quad;
120 mtor << "lin " << lin <<"\n"
121 << "const " << const_term<<"\n";
122 for (int i=0; i < cons.size(); i++) {
123 mtor << "constraint["<<i<<"]: " << cons[i] << " >= " << consrhs[i];
124 mtor << "\n";
126 #endif
129 /* *************** */
131 Mixed_qp::Mixed_qp(int n)
132 : Ineq_constrained_qp(n)
136 void
137 Mixed_qp::OK() const
139 #ifndef NDEBUG
140 Ineq_constrained_qp::OK();
141 assert(eq_consrhs.size() == eq_cons.size());
142 #endif
145 void
146 Mixed_qp::print() const
148 #ifndef NPRINT
149 Ineq_constrained_qp::print();
150 for (int i=0; i < eq_cons.size(); i++) {
151 mtor << "eq cons "<<i<<": x["<<eq_cons[i]<<"] == " << eq_consrhs[i]<<"\n";
153 #endif