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

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

Parent Directory Parent Directory | Revision Log Revision Log


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