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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 208 - (show annotations) (download)
Tue Jan 24 03:19:37 2006 UTC (18 years, 4 months ago) by johnpye
File size: 11584 byte(s)
Added menu bar at top of PyGTK interface.
'Preferences' menu currently just outputs the number of
solver parameters in use. Plan is to allow the parameters
to be viewed and edited via the GUI.
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 #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(ExtFnVector) std::vector<ExtFn>;
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<ExtFn> getExtFns();
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 Plot getPlot() const;
359
360 const bool isPlottable() const;
361 const ASCXX_Set<long> getSetValue<long>() const;
362 const ASCXX_Set<SymChar> getSetValue<SymChar>() const;
363 const bool isChildless() const;
364 void setFixed(const bool &val=true);
365 void setRealValue(const double &val);
366 void setRealValueWithUnits(const double &, const char *);
367 void setBoolValue(const bool &val);
368 void write();
369 };
370
371 %extend Instanc{
372 const char *__repr__(){
373 return self->getName().toString();
374 }
375 %pythoncode {
376 def getSetValue(self):
377 if self.isSetInt():
378 return self.getSetIntValue()
379 elif self.isSetString():
380 return self.getSetStringValue()
381 elif self.isSetEmpty():
382 return set()
383 else:
384 raise RuntimeError("getSetValue: unknown set type");
385
386 def getValue(self):
387 # print "GETTING VALUE OF %s" % self.getName()
388 if self.isCompound():
389 return ""
390 elif self.isRelation() or self.isWhen():
391 return "RELATION"
392 elif self.isSet():
393 _s = set(self.getSetValue());
394 #for _v in self.getSetValue():
395 # _s.add( _v )
396 return _s
397
398 elif ( self.isAtom() or self.isFund() ) and not self.isDefined():
399 return "undefined"
400 elif self.isReal():
401 return self.getRealValueAndUnits()
402 elif self.isBool():
403 return self.getBoolValue()
404 elif self.isInt():
405 return self.getIntValue()
406 elif self.isSymbol():
407 return self.getSymbolValue()
408 else:
409 return "UNKNOWN TYPE" #raise RuntimeError("Unknown value model type="+self.getType().getName().toString()+", instance kind=".getKindStr())
410
411 def getRealValueAndUnits(self):
412 if not self.isReal():
413 raise TypeError
414 if self.isDimensionless():
415 return self.getRealValue();
416 _u = self.getType().getPreferredUnits();
417 if _u == None:
418 return str(self.getRealValue()) + ' ' + self.getDimensions().getDefaultUnits().getName().toString()
419 return _u.getConvertedValue(self.getRealValue())
420
421 def setFixedValue(self,val):
422 if not self.isFixed():
423 self.setFixed();
424 # getReporter().reportError("Setting value of %s to %s" % (self.getName().toString(),val))
425 self.setRealValue(val);
426 }
427 }
428
429 class Solver{
430 public:
431 Solver(const std::string &name);
432 Solver(const Solver &);
433
434 const int &getIndex() const;
435 const std::string getName() const;
436 };
437
438
439 class SolverParameters{
440 public:
441 const std::string toString();
442 SolverParameters(const SolverParameters &);
443 };
444
445 class Simulation : public Instanc{
446 public:
447 Simulation(Instance *&, const SymChar &name);
448 Instanc &getModel();
449 std::vector<Variable> getFixableVariables();
450 void build();
451 const bool check();
452 void checkDoF() const;
453 void run(const Method &);
454 void solve(Solver s);
455 SolverParameters getSolverParameters() const;
456 };
457
458 class Variable{
459 public:
460 const std::string &getName();
461 ~Variable();
462
463 };
464
465 %extend Variable {
466 const std::string __repr__(){
467 return self->getName();
468 }
469 }
470
471 class ExtFn{
472 public:
473 ExtFn(const ExtFn &);
474 const char *getName() const;
475 const char *getHelp() const;
476 const unsigned long getNumInputs() const;
477 const unsigned long getNumOutputs() const;
478 };
479
480 %include "plot.i"
481
482 class Curve : public Instanc{
483
484 public:
485 std::vector<double> x;
486 std::vector<double> y;
487 const std::string getLegend() const;
488
489 };

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