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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

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