/[ascend]/trunk/pygtk/simulation.cpp
ViewVC logotype

Contents of /trunk/pygtk/simulation.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 502 - (show annotations) (download) (as text)
Tue Apr 18 12:57:30 2006 UTC (14 years, 5 months ago) by johnpye
Original Path: trunk/pygtk/interface/simulation.cpp
File MIME type: text/x-c++src
File size: 18470 byte(s)
Added check to see that YACC runs OK.
Fixing build with MSVC++ 2005.
All builds now except for some problems in the SWIG-generated code.
1 #include <iostream>
2 #include <iomanip>
3 #include <stdexcept>
4 #include <sstream>
5 using namespace std;
6
7 extern "C"{
8 #include <utilities/ascConfig.h>
9 #include <utilities/ascSignal.h>
10 #include <utilities/ascMalloc.h>
11 #include <general/dstring.h>
12 #include <general/tm_time.h>
13 #include <compiler/instance_enum.h>
14 #include <compiler/fractions.h>
15 #include <compiler/compiler.h>
16 #include <compiler/dimen.h>
17 #include <compiler/symtab.h>
18 #include <compiler/instance_io.h>
19 #include <compiler/instantiate.h>
20 #include <compiler/bintoken.h>
21 #include <compiler/instance_enum.h>
22 #include <compiler/instquery.h>
23 #include <compiler/check.h>
24 #include <compiler/name.h>
25 #include <compiler/pending.h>
26
27 #include <utilities/readln.h>
28 #include <solver/mtx.h>
29 #include <solver/slv_types.h>
30 #include <solver/var.h>
31 #include <solver/rel.h>
32 #include <solver/discrete.h>
33 #include <solver/conditional.h>
34 #include <solver/logrel.h>
35 #include <solver/bnd.h>
36 #include <solver/calc.h>
37 #include <solver/relman.h>
38 #include <solver/slv_common.h>
39 #include <solver/linsol.h>
40 #include <solver/linsolqr.h>
41 #include <solver/slv_client.h>
42 #include <solver/system.h>
43 #include <solver/slv_interface.h>
44 #include <solver/slvDOF.h>
45 #include <solver/slv3.h>
46 #include <solver/slv_stdcalls.h>
47 #include <solver/slv_server.h>
48 }
49
50 #include "simulation.h"
51 #include "solver.h"
52 #include "solverparameters.h"
53 #include "name.h"
54 #include "incidencematrix.h"
55 #include "variable.h"
56 #include "solverstatus.h"
57 #include "solverreporter.h"
58
59 /**
60 Create an instance of a type (call compiler etc)
61
62 @TODO fix mutex on compile command filenames
63 */
64 Simulation::Simulation(Instance *i, const SymChar &name) : Instanc(i, name), simroot(GetSimulationRoot(i),SymChar("simroot")){
65 is_built = false;
66 // Create an Instance object for the 'simulation root' (we'll call
67 // it the 'simulation model') and it can be fetched using 'getModel()'
68 // any time later.
69 //simroot = Instanc(GetSimulationRoot(i),name);
70 }
71
72 Simulation::Simulation(const Simulation &old) : Instanc(old), simroot(old.simroot){
73 is_built = old.is_built;
74 sys = old.sys;
75 bin_srcname = old.bin_srcname;
76 bin_objname = old.bin_objname;
77 bin_libname = old.bin_libname;
78 bin_cmd = old.bin_cmd;
79 bin_rm = old.bin_rm;
80 }
81
82 Simulation::~Simulation(){
83 //CONSOLE_DEBUG("Deleting simulation %s", getName().toString());
84 }
85
86 Instanc &
87 Simulation::getModel(){
88 if(!simroot.getInternalType()){
89 throw runtime_error("Simulation::getModel: simroot.getInternalType()is NULL");
90 }
91 return simroot;
92 }
93
94 void
95 Simulation::checkDoF() const{
96 cerr << "CHECKING DOF..." << endl;
97 int dof, status;
98 if(!sys){
99 throw runtime_error("System not yet built");
100 }
101 slvDOF_status(sys, &status, &dof);
102 switch(status){
103 case 1: ERROR_REPORTER_NOLINE(ASC_USER_ERROR,"Underspecified; %d degrees of freedom",dof); break;
104 case 2: ERROR_REPORTER_NOLINE(ASC_USER_NOTE,"Square"); break;
105 case 3: ERROR_REPORTER_NOLINE(ASC_USER_ERROR,"Structurally singular"); break;
106 case 4: ERROR_REPORTER_NOLINE(ASC_USER_ERROR,"Overspecified"); break;
107 case 5:
108 throw runtime_error("Unable to resolve degrees of freedom"); break;
109 default:
110 throw runtime_error("Invalid return status from slvDOF_status");
111 }
112 }
113
114 void
115 Simulation::checkConsistency() const{
116 cerr << "CHECKING CONSISTENCY..." << endl;
117 int *fixedarrayptr;
118
119 int res = consistency_analysis(sys, &fixedarrayptr);
120 struct var_variable **vp = slv_get_master_var_list(sys);
121
122 if(res==1){
123 cerr << "STRUCTURALLY CONSISTENT" << endl;
124 return;
125 }else{
126 ERROR_REPORTER_NOLINE(ASC_USER_ERROR,"Structurally inconsistent. Free the variables listed on the console\nin order to make system consistent.");
127 cerr << "INCONSISTENT: Free these vars:" << endl;
128 for(int i=0; fixedarrayptr[i]!=-1; ++i){
129 Instanc i1((struct Instance *)var_instance(vp[fixedarrayptr[i]]));
130 cerr << " " << getInstanceName(i1) << endl;
131 }
132 }
133 }
134
135 void
136 Simulation::checkStructuralSingularity() const{
137 cerr << "CHECKING STRUCTURAL SINGULARITY..." << endl;
138
139 int *vil;
140 int *ril;
141 int *fil;
142
143 int res = slvDOF_structsing(sys, mtx_FIRST, &vil, &ril, &fil);
144 struct var_variable **varlist = slv_get_solvers_var_list(sys);
145 struct rel_relation **rellist = slv_get_solvers_rel_list(sys);
146
147 if(res==0){
148 cerr << "UNABLE TO DETERMINE SINGULARITY LISTS" << endl;
149 return;
150 }else if(res==1){
151 ERROR_REPORTER_NOLINE(ASC_USER_ERROR,"Structurally singular. Check the listing on the console.");
152 cerr << "STRUCTURALLY SINGULAR: The found singularity involves these relations:" << endl;
153 for(int i=0; ril[i]!=-1; ++i){
154 Instanc i1((struct Instance *)rel_instance(rellist[ril[i]]));
155 cerr << " " << getInstanceName(i1) << endl;
156 }
157
158 cerr << "STRUCTURALLY SINGULAR: ... and these variables:" << endl;
159 for(int i=0; vil[i]!=-1; ++i){
160 Instanc i1((struct Instance *)var_instance(varlist[vil[i]]));
161 cerr << " " << getInstanceName(i1) << endl;
162 }
163
164 cerr << "STRUCTURALLY SINGULAR: ... and may be mitigated by freeing these variables:" << endl;
165 for(int i=0; fil[i]!=-1; ++i){
166 Instanc i1((struct Instance *)var_instance(varlist[fil[i]]));
167 cerr << " " << getInstanceName(i1) << endl;
168 }
169 }else{
170 throw runtime_error("Invalid return from slvDOF_structsing.");
171 }
172 ascfree(vil);
173 ascfree(ril);
174 ascfree(fil);
175 }
176
177 void
178 Simulation::run(const Method &method){
179 cerr << "RUNNING PROCEDURE " << method.getName() << endl;
180 Nam name = Nam(method.getSym());
181 //cerr << "CREATED NAME '" << name.getName() << "'" << endl;
182 Proc_enum pe;
183 pe = Initialize(
184 &*(getModel().getInternalType()) ,name.getInternalType(), "__not_named__"
185 ,ASCERR
186 ,0, NULL, NULL
187 );
188
189 if(pe == Proc_all_ok){
190 ERROR_REPORTER_NOLINE(ASC_PROG_NOTE,"Method '%s' was run (check above for errors)\n",method.getName());
191 //cerr << "METHOD " << method.getName() << " COMPLETED OK" << endl;
192 }else{
193 stringstream ss;
194 ss << "Simulation::run: Method '" << method.getName() << "' returned error: ";
195 switch(pe){
196 case Proc_CallOK: ss << "Call OK"; break;
197 case Proc_CallError: ss << "Error occurred in call"; break;
198 case Proc_CallReturn: ss << "Request that caller return (OK)"; break;
199 case Proc_CallBreak: ss << "Break out of enclosing loop"; break;
200 case Proc_CallContinue: ss << "Skip to next iteration"; break;
201
202 case Proc_break: ss << "Break"; break;
203 case Proc_continue: ss << "Continue"; break;
204 case Proc_fallthru: ss << "Fall-through"; break;
205 case Proc_return: ss << "Return"; break;
206 case Proc_stop: ss << "Stop"; break;
207 case Proc_stack_exceeded: ss << "Stack exceeded"; break;
208 case Proc_stack_exceeded_this_frame: ss << "Stack exceeded this frame"; break;
209 case Proc_case_matched: ss << "Case matched"; break;
210 case Proc_case_unmatched: ss << "Case unmatched"; break;
211
212 case Proc_case_undefined_value: ss << "Undefined value in case"; break;
213 case Proc_case_boolean_mismatch: ss << "Boolean mismatch in case"; break;
214 case Proc_case_integer_mismatch: ss << "Integer mismatch in case"; break;
215 case Proc_case_symbol_mismatch: ss << "Symbol mismatch in case"; break;
216 case Proc_case_wrong_index: ss << "Wrong index in case"; break;
217 case Proc_case_wrong_value: ss << "Wrong value in case"; break;
218 case Proc_case_extra_values: ss << "Extra values in case"; break;
219 case Proc_bad_statement: ss << "Bad statement"; break;
220 case Proc_bad_name: ss << "Bad name"; break;
221 case Proc_for_duplicate_index: ss << "Duplicate index"; break;
222 case Proc_for_set_err: ss << "For set error"; break;
223 case Proc_for_not_set: ss << "For not set"; break;
224 case Proc_illegal_name_use: ss << "Illegal name use"; break;
225 case Proc_name_not_found: ss << "Name not found"; break;
226 case Proc_instance_not_found: ss << "Instance not found"; break;
227 case Proc_type_not_found: ss << "Type not found"; break;
228 case Proc_illegal_type_use: ss << "Illegal use"; break;
229 case Proc_proc_not_found: ss << "Method not found"; break;
230 case Proc_if_expr_error_typeconflict: ss << "Type conflict in 'if' expression"; break;
231 case Proc_if_expr_error_nameunfound: ss << "Name not found in 'if' expression"; break;
232 case Proc_if_expr_error_incorrectname: ss << "Incorrect name in 'if' expression"; break;
233 case Proc_if_expr_error_undefinedvalue: ss << "Undefined value in 'if' expression"; break;
234 case Proc_if_expr_error_dimensionconflict: ss << "Dimension conflict in 'if' expression"; break;
235 case Proc_if_expr_error_emptychoice: ss << "Empty choice in 'if' expression"; break;
236 case Proc_if_expr_error_emptyintersection: ss << "Empty intersection in 'if' expression"; break;
237 case Proc_if_expr_error_confused: ss << "Confused in 'if' expression"; break;
238 case Proc_if_real_expr: ss << "Real-valued result in 'if' expression"; break;
239 case Proc_if_integer_expr: ss << "Integeter-valued result in 'if' expression"; break;
240 case Proc_if_symbol_expr: ss << "Symbol-valued result in 'if' expression"; break;
241 case Proc_if_set_expr: ss << "Set-valued result in 'if' expression"; break;
242 case Proc_if_not_logical: ss << "If expression is not logical"; break;
243 case Proc_user_interrupt: ss << "User interrupt"; break;
244 case Proc_infinite_loop: ss << "Infinite loop"; break;
245 case Proc_declarative_constant_assignment: ss << "Declarative constant assignment"; break;
246 case Proc_nonsense_assignment: ss << "Nonsense assginment (bogus)"; break;
247 case Proc_nonconsistent_assignment: ss << "Inconsistent assignment"; break;
248 case Proc_nonatom_assignment: ss << "Non-atom assignment"; break;
249 case Proc_nonboolean_assignment: ss << "Non-boolean assignment"; break;
250 case Proc_noninteger_assignment: ss << "Non-integer assignment"; break;
251 case Proc_nonreal_assignment: ss << "Non-real assignment"; break;
252 case Proc_nonsymbol_assignment: ss << "Non-symbol assignment"; break;
253 case Proc_lhs_error: ss << "Left-hand-side error"; break;
254 case Proc_rhs_error: ss << "Right-hand-side error"; break;
255 case Proc_unknown_error: ss << "Unknown error"; break;
256 default:
257 ss << "Invalid error code";
258 }
259
260
261 ss << " (" << int(pe) << ")";
262 throw runtime_error(ss.str());
263 }
264 }
265
266 const bool
267 Simulation::check(){
268 cerr << "CHECKING SIMULATION" << endl;
269 Instance *i1 = getModel().getInternalType();
270 CheckInstance(stderr, &*i1);
271 cerr << "...DONE CHECKING" << endl;
272 this->checkConsistency();
273 this->checkStructuralSingularity();
274 return true;
275 }
276
277 void
278 Simulation::build(){
279 cerr << "BUILDING SIMULATION..." << endl;
280 Instance *i1 = getModel().getInternalType();
281 sys = system_build(&*i1);
282 if(!sys){
283 throw runtime_error("Unable to build system");
284 }
285 is_built = true;
286 cerr << "...DONE BUILDING" << endl;
287 }
288
289 vector<Variable>
290 Simulation::getFixableVariables(){
291 cerr << "GETTING FIXABLE VARIABLES..." << endl;
292 vector<Variable> vars;
293
294 if(!sys){
295 throw runtime_error("Simulation system not yet built");
296 }
297
298 int32 *vip; /** TODO ensure 32 bit integers are used */
299
300 // Get IDs of elegible variables in array at vip...
301 if(!slvDOF_eligible(sys,&vip)){
302 ERROR_REPORTER_NOLINE(ASC_USER_NOTE,"No fixable variables found.");
303 }else{
304 //cerr << "FIXABLE VARS FOUND" << endl;
305 struct var_variable **vp = slv_get_solvers_var_list(sys);
306
307 /*struct var_variable *first_var = vp[0];
308 char *first_var_name = var_make_name(sys,first_var);
309 cerr << "FIRST SYS VAR IS NAMED " << var_make_name(s,first_var) << endl;
310 ascfree(first_var_name);*/
311
312 if(vp==NULL){
313 throw runtime_error("Simulation variable list is null");
314 }
315
316 // iterate through this list until we find a -1:
317 int i=0;
318 int var_index = vip[i];
319 while(var_index >= 0){
320 //cerr << "FOUND VARIABLE var_index = " << var_index << endl;
321 struct var_variable *var = vp[var_index];
322 //cerr << "VARIABLE " << var_index << " IS ELIGIBLE" << endl;
323
324 //char *var_name = var_make_name(sys,var);
325 //cerr << "ELIGIBLE VAR: " << var_name << endl;
326 //ascfree(var_name);
327
328 vars.push_back( Variable(this, var) );
329 ++i;
330 var_index = vip[i];
331 }
332 ERROR_REPORTER_NOLINE(ASC_USER_NOTE,"Found %d fixable variables.",i);
333 //cerr << "END ELEGIBLE VARS LIST" << endl;
334 ascfree(vip);
335 //cerr << "FREED VIP LIST" << endl;
336 }
337
338 //cerr << "FINISHED WITH FINDING ELEGIBLE VARIABLES" << endl;
339 return vars;
340 }
341
342 vector<Variable>
343 Simulation::getVariablesNearBounds(const double &epsilon){
344 cerr << "GETTING VARIABLES NEAR BOUNDS..." << endl;
345 vector<Variable> vars;
346
347 if(!sys){
348 throw runtime_error("Simulation system not yet built");
349 }
350
351 int *vip;
352 if(slv_near_bounds(sys,epsilon,&vip)){
353 struct var_variable **vp = slv_get_solvers_var_list(sys);
354 struct var_variable *var;
355 cerr << "VARS FOUND NEAR BOUNDS" << endl;
356 int nlow = vip[0];
357 int nhigh = vip[1];
358 int lim1 = 2 + nlow;
359 for(int i=2; i<lim1; ++i){
360 var = vp[vip[i]];
361 char *var_name = var_make_name(sys,var);
362 cerr << "AT LOWER BOUND: " << var_name << endl;
363 ascfree(var_name);
364 vars.push_back(Variable(this,var));
365 };
366 int lim2 = lim1 + nhigh;
367 for(int i=lim1; i<lim2; ++i){
368 var = vp[vip[i]];
369 char *var_name = var_make_name(sys,var);
370 cerr << "AT UPPER BOUND: " << var_name << endl;
371 ascfree(var_name);
372 vars.push_back(Variable(this,var));
373 }
374 }
375 ascfree(vip);
376 return vars;
377 }
378
379 void
380 Simulation::solve(Solver solver, SolverReporter &reporter){
381 if(!is_built){
382 throw runtime_error("Simulation::solver: simulation is not yet built, can't start solving.");
383 }
384
385 cerr << "SIMULATION::SOLVE STARTING..." << endl;
386 enum inst_t k = getModel().getKind();
387 if(k!=MODEL_INST)throw runtime_error("Can't solve: not an instance of type MODEL_INST");
388
389 Instance *i1 = getInternalType();
390 int npend = NumberPendingInstances(&*i1);
391 if(npend)throw runtime_error("Can't solve: There are still %d pending instances");
392
393 if(!sys)throw runtime_error("Can't solve: Simulation system has not been built yet.");
394
395 cerr << "SIMULATION::SOLVE: SET SOLVER..." << endl;
396 setSolver(solver);
397
398
399 cerr << "PRESOLVING SYSTEM...";
400 slv_presolve(sys);
401 cerr << "DONE" << endl;
402
403 cerr << "SOLVING SYSTEM..." << endl;
404 // Add some stuff here for cleverer iteration....
405 unsigned niter = 1000;
406 double updateinterval = 0.02;
407
408 double starttime = tm_cpu_time();
409 double lastupdate = starttime;
410 SolverStatus status;
411 int solved_vars=0;
412 bool stop=false;
413
414 status.getSimulationStatus(*this);
415 reporter.report(&status);
416
417 for(int iter = 1; iter <= niter && !stop; ++iter){
418
419 if(status.isReadyToSolve()){
420 slv_iterate(sys);
421 }
422
423 status.getSimulationStatus(*this);
424
425 if(reporter.report(&status)){
426 stop = true;
427 }
428 }
429
430 double elapsed = tm_cpu_time() - starttime;
431
432
433 activeblock = status.getCurrentBlockNum();
434
435 reporter.finalise(&status);
436
437 // Just a little bit of console output:
438
439 if(status.isOK()){
440 cerr << "... SOLVED, STATUS OK" << endl;
441 }else{
442 cerr << "... SOLVER FAILED" << endl;
443 }
444
445 cerr << "SOLVER PERFORMED " << status.getIterationNum() << " ITERATIONS IN " << elapsed << "s" << endl;
446 }
447
448 void
449 Simulation::write(){
450 simroot.write();
451 }
452
453 //------------------------------------------
454 // ASSIGNING SOLVER TO SIMULATION
455
456 void
457 Simulation::setSolver(Solver &solver){
458 cerr << "SETTING SOLVER ON SIMULATION TO " << solver.getName() << endl;
459
460 if(!sys)throw runtime_error("Can't solve: Simulation system has not been built yet.");
461 // Update the solver object because sometimes an alternative solver can be returned, apparently.
462
463 int selected = slv_select_solver(sys, solver.getIndex());
464 //cerr << "Simulation::setSolver: slv_select_solver returned " << selected << endl;
465
466 if(selected<0){
467 ERROR_REPORTER_NOLINE(ASC_PROG_ERROR,"Failed to select solver");
468 throw runtime_error("Failed to select solver");
469 }
470
471 if(selected!=solver.getIndex()){
472 solver = Solver(slv_solver_name(selected));
473 ERROR_REPORTER_NOLINE(ASC_PROG_NOTE,"Substitute solver '%s' (index %d) selected.\n", solver.getName().c_str(), selected);
474 }
475
476 if( slv_eligible_solver(sys) <= 0){
477 ERROR_REPORTER_NOLINE(ASC_PROG_ERROR,"Inelegible solver '%s'", solver.getName().c_str() );
478 throw runtime_error("Inelegible solver");
479 }
480 }
481
482 const Solver
483 Simulation::getSolver() const{
484 int index = slv_get_selected_solver(sys);
485 //cerr << "Simulation::getSolver: index = " << index << endl;
486 if(index<0)throw runtime_error("No solver selected");
487
488 return Solver(slv_solver_name(index));
489 }
490
491
492 /**
493 Get solver parameters struct wrapped up as a SolverParameters class.
494 */
495 SolverParameters
496 Simulation::getSolverParameters() const{
497 if(!sys)throw runtime_error("Can't getSolverParameters: Simulation system has not been built yet.");
498
499 slv_parameters_t p;
500 slv_get_parameters(sys,&p);
501 return SolverParameters(p);
502 }
503
504 /**
505 Update the solver parameters by passing a new set back
506 */
507 void
508 Simulation::setSolverParameters(SolverParameters &P){
509 if(!sys)throw runtime_error("Can't set solver parameters: simulation has not been built yet.");
510 slv_set_parameters(sys, &(P.getInternalType()));
511 }
512
513 slv_system_structure *
514 Simulation::getSystem(){
515 if(!sys)throw runtime_error("Can't getSystem: simulation not yet built");
516 return sys;
517 }
518
519 IncidenceMatrix
520 Simulation::getIncidenceMatrix(){
521 return IncidenceMatrix(*this);
522 }
523
524 const string
525 Simulation::getInstanceName(const Instanc &i) const{
526 char *n;
527 n = WriteInstanceNameString(i.getInternalType(),simroot.getInternalType());
528 string s(n);
529 ascfree(n);
530 return s;
531 }
532
533 const int
534 Simulation::getNumVars(){
535 return slv_get_num_solvers_vars(getSystem());
536 }
537
538 void
539 Simulation::processVarStatus(){
540
541 // this is a cheap function call:
542 const mtx_block_t *bb = slv_get_solvers_blocks(getSystem());
543
544 var_variable **vlist = slv_get_solvers_var_list(getSystem());
545 int nvars = slv_get_num_solvers_vars(getSystem());
546
547 slv_status_t status;
548 slv_get_status(getSystem(), &status);
549
550 if(status.block.number_of == 0){
551 cerr << "Variable statuses can't be set: block structure not yet determined." << endl;
552 return;
553 }
554
555 int activeblock = status.block.current_block;
556 int low = bb->block[activeblock].col.low;
557 int high = bb->block[activeblock].col.high;
558 bool allsolved = status.converged;
559 for(int c=0; c < nvars; ++c){
560 var_variable *v = vlist[c];
561 Instanc i((Instance *)var_instance(v));
562 VarStatus s = ASCXX_VAR_STATUS_UNKNOWN;
563 if(i.isFixed()){
564 s = ASCXX_VAR_FIXED;
565 }else if(var_incident(v) && var_active(v)){
566 if(allsolved || c < low){
567 s = ASCXX_VAR_SOLVED;
568 }else if(c <= high){
569 s = ASCXX_VAR_ACTIVE;
570 }else{
571 s = ASCXX_VAR_UNSOLVED;
572 }
573 }
574 i.setVarStatus(s);
575 }
576 }
577
578 const int
579 Simulation::getActiveBlock() const{
580 return activeblock;
581 }

john.pye@anu.edu.au
ViewVC Help
Powered by ViewVC 1.1.22