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

Contents of /trunk/pygtk/interface/simulation.cpp

Parent Directory Parent Directory | Revision Log Revision Log


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

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