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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

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