/[ascend]/trunk/pygtk/interface/ascend.i
ViewVC logotype

Contents of /trunk/pygtk/interface/ascend.i

Parent Directory Parent Directory | Revision Log Revision Log


Revision 319 - (show annotations) (download)
Thu Feb 23 12:30:40 2006 UTC (14 years, 9 months ago) by johnpye
File size: 11957 byte(s)
Fixed a bug with the diagnose window after a successful solve
Added preference: SolverReporter:close_on_converged
1 /* : set syntax=cpp : */
2 /*
3 SWIG interface routines to read a file into the library
4 */
5
6 %module(directors=1) ascend
7
8 %include <python/std_string.i>
9 %include <python/std_vector.i>
10 %include <python/std_except.i>
11 %include <python/std_set.i>
12
13 %{
14 #include "library.h"
15 #include "type.h"
16 #include "instance.h"
17 #include "variable.h"
18 #include "relation.h"
19 #include "name.h"
20 #include "reporter.h"
21 #include "simulation.h"
22 #include "solver.h"
23 #include "symchar.h"
24 #include "set.h"
25 #include "dimensions.h"
26 #include "units.h"
27 #include "extmethod.h"
28 #include "plot.h"
29 #include "curve.h"
30 #include "solverparameters.h"
31 #include "solverstatus.h"
32 #include "solverreporter.h"
33 #include "incidencematrix.h"
34 %}
35
36 // All STL runtime_errors caught to Python
37
38 %exception {
39 try {
40 $action
41 }
42 catch (std::range_error &e) {
43 SWIG_exception(SWIG_IndexError,e.what());
44 }
45 catch (std::runtime_error &e) {
46 SWIG_exception(SWIG_RuntimeError,e.what());
47 }
48 }
49
50 // Import the preferences module
51 %pythoncode {
52 import preferences;
53 }
54
55 // Set-valued instance variable
56 %pythoncode {
57 class SetIter:
58 def __init__(self,set):
59 self.set=set
60 self.index=0
61 def next(self):
62 if self.index==self.set.length():
63 raise StopIteration
64 self.index = self.index + 1
65 return self.set[self.index]
66 }
67
68 template<class T>
69 class ASCXX_Set{
70 private:
71 ASCXX_Set();
72 public:
73 const T at(const unsigned long&) const;
74 const unsigned long length() const;
75 };
76 %extend ASCXX_Set<long>{
77 %pythoncode {
78 def __getitem__(self, index):
79 return self.at(index)
80 def __iter__(self):
81 return SetIter(self)
82 }
83 }
84 %extend ASCXX_Set<SymChar>{
85 %pythoncode {
86 def __getitem__(self, index):
87 return self.at(index)
88 def __iter__(self):
89 return SetIter(self)
90 }
91 }
92
93
94 %template(ModuleVector) std::vector<Module>;
95 %template(TypeVector) std::vector<Type>;
96 %template(VariableVector) std::vector<Variable>;
97 %template(RelationVector) std::vector<Relation>;
98 %template(MethodVector) std::vector<Method>;
99 %template(InstancVector) std::vector<Instanc>;
100 %template(ExtMethodVector) std::vector<ExtMethod>;
101 %template(SetInt) ASCXX_Set<long>;
102 %template(SetString) ASCXX_Set<SymChar>;
103 %template(DoubleVector) std::vector<double>;
104 %template(IntVector) std::vector<int>;
105 %template(CurveVector) std::vector<Curve>;
106 %template(StringVector) std::vector<std::string>;
107 %template(InstancSet) std::set<Instanc,InstancCompare>;
108
109 %rename(Instance) Instanc;
110 %rename(Name) Nam;#include "incidencematrix.h"
111 %rename(getSetIntValue) Instanc::getSetValue<long>;
112 %rename(getSetStringValue) Instanc::getSetValue<SymChar>;
113 %rename(Units) UnitsM;
114
115
116 // Grab a Python function object as a Python object.
117 %typemap(python,in) PyObject *pyfunc {
118 if (!PyCallable_Check($input)) {
119 PyErr_SetString(PyExc_TypeError, "Need a callable object!");
120 return NULL;
121 }
122 $1 = $input;
123 }
124
125 //----------------------------
126 // REPORTER: callbacks to python
127 class Reporter{
128 private:
129 ~Reporter();
130 Reporter();
131 public:
132 // use 'getReporter' instead of 'Reporter::Instance()' in python
133 void setErrorCallback(error_reporter_callback_t callback, void *client_data);
134 void setPythonErrorCallback(PyObject *pyfunc);
135 void clearPythonErrorCallback();
136 };
137
138 %extend Reporter {
139 void reportError(const char *msg){
140 error_reporter(ASC_USER_ERROR,NULL,0,"%s", msg);
141 }
142 void reportNote(const char *msg){
143 error_reporter(ASC_USER_NOTE,NULL,0,"%s",msg);
144 }
145 void reportWarning(const char *msg){
146 error_reporter(ASC_USER_WARNING,NULL,0,"%s",msg);
147 }
148 void reportSuccess(const char *msg){
149 error_reporter(ASC_USER_SUCCESS,NULL,0,"%s",msg);
150 }
151 }
152
153 // There are problems with Instance(), so use this instead:
154 Reporter *getReporter();
155
156 //----------------------------------------
157 // UNITS AND DIMENSIONS
158
159
160 class UnitsM;
161
162 class Dimensions{
163 public:
164 static const unsigned MAX_DIMS;
165 static const std::string getBaseUnit(const unsigned &);
166
167 const bool operator==(const Dimensions &) const;
168 const bool operator!=(const Dimensions &) const;
169 const bool operator<(const Dimensions &) const;
170 Dimensions(const Dimensions &);
171 const bool isWild() const;
172 const bool isDimensionless() const;
173 const short getFractionNumerator(const unsigned &) const;
174 const short getFractionDenominator(const unsigned &) const;
175 };
176
177 class UnitsM{
178 public:
179 UnitsM(const char *);
180 const SymChar getName() const; // the units description string eg 'bar' or 'kJ/kg/K'
181 const Dimensions getDimensions() const;
182 const double getConversion() const; // multiplication factor to convert eg feet to SI (metres)
183 };
184
185 %extend UnitsM{
186 %pythoncode{
187 def getConvertedValue(self,si_value):
188 _u_value = si_value / self.getConversion()
189 return str(_u_value) + " " + self.getName().toString();
190 }
191 }
192
193 /*
194 This function creates default (SI) units for any dimension given. Most
195 of the time you will want to use custom units in place of these, eg
196 'N' instead of 'kg*m/s^2'.
197 */
198 %extend Dimensions{
199 %pythoncode {
200
201 def getDefaultUnits(self):
202 if self.isDimensionless():
203 return Units("");
204
205 if self.isWild():
206 return Units("?");
207
208 # create a string representation of the current dimensions
209 numparts=[]
210 denparts=[]
211 for i in range(0, self.MAX_DIMS):
212 baseunit = self.getBaseUnit(i);
213 num = self.getFractionNumerator(i)
214 den = self.getFractionDenominator(i)
215 if num > 0:
216 if den == 1:
217 if num == 1:
218 numparts.append(baseunit)
219 else:
220 numparts.append("%s^%d" % (baseunit, num) )
221 else:
222 numparts.append("%s^(%d/%d)" % (baseunit, num, den) )
223 elif num < 0:
224 if den == 1:
225 if num == -1:
226 denparts.append(baseunit)
227 else:
228 denparts.append("%s^%d" % (baseunit, -num) )
229 else:
230 denparts.append("%s^(%d/%d)" % (baseunit, -num, den) )
231
232 if len(numparts):
233 str = "*".join(numparts)
234 else:
235 str = "1"
236
237 if len(denparts):
238 str = str + "/" + "/".join(denparts)
239
240 return Units(str)
241
242 }
243 }
244
245 /*
246 some python code for nice unicode unit strings, need to extend the units.c code as well though.
247
248 elif num == 2:
249 numparts.append(baseunit + ur'\u00b2')
250 elif num == 3:
251 numparts.append(baseunit + ur'\u00b3')
252
253 str = ur'\u00b7'.join(numparts)
254 */
255 //----------------------------
256
257 class Library{
258 public:
259 Library();
260 ~Library();
261
262 void load(char *filename);
263 void listModules(const int &module_type=0);
264 Type &findType(const char *name);
265 std::vector<Module> getModules();
266 std::vector<Type> getModuleTypes(const Module &);
267 std::vector<ExtMethod> getExtMethods();
268 void clear();
269 };
270
271 class SymChar{
272 public:
273 SymChar(const std::string &);
274 const char *toString() const;
275 };
276 %extend SymChar{
277 const char *__repr__(){
278 return self->toString();
279 }
280 }
281
282 class Module{
283 public:
284 const char *getName() const;
285 const char *getFilename() const;
286 const struct tm *getMtime() const;
287 };
288
289 class Method{
290 public:
291 const char *getName() const;
292 };
293
294 // Renamed in python as 'Name'
295 class Nam{
296 public:
297 Nam(const SymChar &);
298 const std::string getName() const;
299 };
300
301 class Type{
302 public:
303 const SymChar getName();
304 const int getParameterCount();
305 Simulation getSimulation(const char *name);
306 std::vector<Method> getMethods();
307 const bool isRefinedSolverVar() const;
308 const bool isRefinedReal() const;
309 const Dimensions getDimensions() const;
310 };
311 %extend Type{
312 const char *__repr__(){
313 return self->getName().toString();
314 }
315
316 %pythoncode{
317 def getPreferredUnits(self):
318 if not self.isRefinedReal():
319 return None
320
321 _pref = preferences.Preferences()
322 #print "Checking for preferred units for %s" % self.getName()
323 _u = _pref.getPreferredUnits(self.getName().toString())
324 if _u == None:
325 # no preferred units set
326 return None
327 _units = Units(_u);
328
329 if _units.getDimensions() != self.getDimensions():
330 getReporter().reportWarning("Preferred units '%s' for type '%s' are not dimensionally correct: ignoring." % (_u, self.getName()) );
331 return None
332
333 return _units;
334 }
335 }
336
337 typedef enum{
338 ASCXX_VAR_STATUS_UNKNOWN=0, ASCXX_VAR_FIXED, ASCXX_VAR_UNSOLVED, ASCXX_VAR_ACTIVE, ASCXX_VAR_SOLVED
339 } VarStatus;
340
341 class Instanc{
342 private:
343 Instanc();
344 public:
345 Instanc(Instance *);
346 Instanc(Instance *, SymChar &name);
347 std::vector<Instanc> getChildren();
348 const std::string getKindStr() const;
349 const SymChar &getName();
350 const Type getType() const;
351 const bool isAtom() const;
352 const bool isFixed() const;
353 const bool isFund() const;
354 const bool isConst() const;
355 const bool isAssigned() const;
356 const bool isCompound() const;
357 const bool isRelation() const;
358 const bool isWhen() const;
359 const bool isSet() const; // a set (group) of things
360 const bool isSetInt() const;
361 const bool isSetString() const;
362 const bool isSetEmpty() const;
363 const bool isDefined() const;
364 const bool isBool() const;
365 const bool isInt() const;
366 const bool isSymbol() const;
367 const bool isReal() const;
368 const double getRealValue() const;
369 const bool isDimensionless() const;
370 const Dimensions getDimensions() const;
371 const bool getBoolValue() const;
372 const long getIntValue() const;
373 const SymChar getSymbolValue() const;
374 const std::string getValueAsString() const; ///< Use carefully: rounding will occur for doubles!
375
376 const std::string getRelationAsString(const Instanc &relative_to) const;
377 const double getResidual() const;
378
379 Plot getPlot() const;
380
381 const bool isPlottable() const;
382 const ASCXX_Set<long> getSetValue<long>() const;
383 const ASCXX_Set<SymChar> getSetValue<SymChar>() const;
384 const bool isChildless() const;
385 void setFixed(const bool &val=true);
386 void setRealValue(const double &val);
387 void setRealValueWithUnits(const double &, const char *);
388 void setBoolValue(const bool &val);
389 void write();
390
391 const VarStatus getVarStatus() const;
392
393 void setLowerBound(const double &);
394 void setUpperBound(const double &);
395 void setNominal(const double &);
396 const double getLowerBound() const;
397 const double getUpperBound() const;
398 const double getNominal() const;
399
400 const std::set<Instanc,InstancCompare> getClique() const;
401 };
402
403 %extend Instanc{
404 const char *__repr__(){
405 return self->getName().toString();
406 }
407 %pythoncode {
408 def getSetValue(self):
409 if self.isSetInt():
410 return self.getSetIntValue()
411 elif self.isSetString():
412 return self.getSetStringValue()
413 elif self.isSetEmpty():
414 return set()
415 else:
416 raise RuntimeError("getSetValue: unknown set type");
417
418 def getValue(self):
419 # print "GETTING VALUE OF %s" % self.getName()
420 if self.isCompound():
421 return ""
422 elif self.isRelation():
423 return self.getResidual()
424 elif self.isWhen():
425 return "WHEN"
426 elif self.isSet():
427 _s = set(self.getSetValue());
428 #for _v in self.getSetValue():
429 # _s.add( _v )
430 return _s
431
432 elif ( self.isAtom() or self.isFund() ) and not self.isDefined():
433 return "undefined"
434 elif self.isReal():
435 return self.getRealValueAndUnits()
436 elif self.isBool():
437 return self.getBoolValue()
438 elif self.isInt():
439 return self.getIntValue()
440 elif self.isSymbol():
441 return self.getSymbolValue()
442 else:
443 return "UNKNOWN TYPE" #raise RuntimeError("Unknown value model type="+self.getType().getName().toString()+", instance kind=".getKindStr())
444
445 def getRealValueAndUnits(self):
446 if not self.isReal():
447 raise TypeError
448 if self.isDimensionless():
449 return self.getRealValue();
450 _u = self.getType().getPreferredUnits();
451 if _u == None:
452 return str(self.getRealValue()) + ' ' + self.getDimensions().getDefaultUnits().getName().toString()
453 return _u.getConvertedValue(self.getRealValue())
454
455 def setFixedValue(self,val):
456 if not self.isFixed():
457 self.setFixed();
458 # getReporter().reportError("Setting value of %s to %s" % (self.getName().toString(),val))
459 self.setRealValue(val);
460 }
461 }
462
463 %include "solver.i"
464
465 class ExtMethod{
466 public:
467 ExtMethod(const ExtMethod &);
468 const char *getName() const;
469 const char *getHelp() const;
470 const unsigned long getNumInputs() const;
471 const unsigned long getNumOutputs() const;
472 };
473
474 %include "plot.i"
475
476 class Curve : public Instanc{
477
478 public:
479 std::vector<double> x;
480 std::vector<double> y;
481 const std::string getLegend() const;
482
483 };

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