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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 355 - (show annotations) (download)
Mon Mar 6 03:11:28 2006 UTC (14 years, 4 months ago) by johnpye
File size: 12013 byte(s)
In PyGTK 'modules' list, you can now see non-parameterised types in bold.
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_except.i>
10 %include <python/std_vector.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(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(std::string defaultpath=NULL);
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 const bool hasParameters() const;
311 };
312 %extend Type{
313 const char *__repr__(){
314 return self->getName().toString();
315 }
316
317 %pythoncode{
318 def getPreferredUnits(self):
319 if not self.isRefinedReal():
320 return None
321
322 _pref = preferences.Preferences()
323 #print "Checking for preferred units for %s" % self.getName()
324 _u = _pref.getPreferredUnits(self.getName().toString())
325 if _u == None:
326 # no preferred units set
327 return None
328 _units = Units(_u);
329
330 if _units.getDimensions() != self.getDimensions():
331 getReporter().reportWarning("Preferred units '%s' for type '%s' are not dimensionally correct: ignoring." % (_u, self.getName()) );
332 return None
333
334 return _units;
335 }
336 }
337
338 typedef enum{
339 ASCXX_VAR_STATUS_UNKNOWN=0, ASCXX_VAR_FIXED, ASCXX_VAR_UNSOLVED, ASCXX_VAR_ACTIVE, ASCXX_VAR_SOLVED
340 } VarStatus;
341
342 class Instanc{
343 private:
344 Instanc();
345 public:
346 Instanc(Instance *);
347 Instanc(Instance *, SymChar &name);
348 std::vector<Instanc> getChildren();
349 const std::string getKindStr() const;
350 const SymChar &getName();
351 const Type getType() const;
352 const bool isAtom() const;
353 const bool isFixed() const;
354 const bool isFund() const;
355 const bool isConst() const;
356 const bool isAssigned() const;
357 const bool isCompound() const;
358 const bool isRelation() const;
359 const bool isWhen() const;
360 const bool isSet() const; // a set (group) of things
361 const bool isSetInt() const;
362 const bool isSetString() const;
363 const bool isSetEmpty() const;
364 const bool isDefined() const;
365 const bool isBool() const;
366 const bool isInt() const;
367 const bool isSymbol() const;
368 const bool isReal() const;
369 const double getRealValue() const;
370 const bool isDimensionless() const;
371 const Dimensions getDimensions() const;
372 const bool getBoolValue() const;
373 const long getIntValue() const;
374 const SymChar getSymbolValue() const;
375 const std::string getValueAsString() const; ///< Use carefully: rounding will occur for doubles!
376
377 const std::string getRelationAsString(const Instanc &relative_to) const;
378 const double getResidual() const;
379
380 Plot getPlot() const;
381
382 const bool isPlottable() const;
383 const ASCXX_Set<long> getSetValue<long>() const;
384 const ASCXX_Set<SymChar> getSetValue<SymChar>() const;
385 const bool isChildless() const;
386 void setFixed(const bool &val=true);
387 void setRealValue(const double &val);
388 void setRealValueWithUnits(const double &, const char *);
389 void setBoolValue(const bool &val);
390 void write();
391
392 const VarStatus getVarStatus() const;
393
394 void setLowerBound(const double &);
395 void setUpperBound(const double &);
396 void setNominal(const double &);
397 const double getLowerBound() const;
398 const double getUpperBound() const;
399 const double getNominal() const;
400
401 const std::set<Instanc,InstancCompare> getClique() const;
402 };
403
404 %extend Instanc{
405 const char *__repr__(){
406 return self->getName().toString();
407 }
408 %pythoncode {
409 def getSetValue(self):
410 if self.isSetInt():
411 return self.getSetIntValue()
412 elif self.isSetString():
413 return self.getSetStringValue()
414 elif self.isSetEmpty():
415 return set()
416 else:
417 raise RuntimeError("getSetValue: unknown set type");
418
419 def getValue(self):
420 # print "GETTING VALUE OF %s" % self.getName()
421 if self.isCompound():
422 return ""
423 elif self.isRelation():
424 return self.getResidual()
425 elif self.isWhen():
426 return "WHEN"
427 elif self.isSet():
428 _s = set(self.getSetValue());
429 #for _v in self.getSetValue():
430 # _s.add( _v )
431 return _s
432
433 elif ( self.isAtom() or self.isFund() ) and not self.isDefined():
434 return "undefined"
435 elif self.isReal():
436 return self.getRealValueAndUnits()
437 elif self.isBool():
438 return self.getBoolValue()
439 elif self.isInt():
440 return self.getIntValue()
441 elif self.isSymbol():
442 return self.getSymbolValue()
443 else:
444 return "UNKNOWN TYPE" #raise RuntimeError("Unknown value model type="+self.getType().getName().toString()+", instance kind=".getKindStr())
445
446 def getRealValueAndUnits(self):
447 if not self.isReal():
448 raise TypeError
449 if self.isDimensionless():
450 return self.getRealValue();
451 _u = self.getType().getPreferredUnits();
452 if _u == None:
453 return str(self.getRealValue()) + ' ' + self.getDimensions().getDefaultUnits().getName().toString()
454 return _u.getConvertedValue(self.getRealValue())
455
456 def setFixedValue(self,val):
457 if not self.isFixed():
458 self.setFixed();
459 # getReporter().reportError("Setting value of %s to %s" % (self.getName().toString(),val))
460 self.setRealValue(val);
461 }
462 }
463
464 %include "solver.i"
465
466 class ExtMethod{
467 public:
468 ExtMethod(const ExtMethod &);
469 const char *getName() const;
470 const char *getHelp() const;
471 const unsigned long getNumInputs() const;
472 const unsigned long getNumOutputs() const;
473 };
474
475 %include "plot.i"
476
477 class Curve : public Instanc{
478
479 public:
480 std::vector<double> x;
481 std::vector<double> y;
482 const std::string getLegend() const;
483
484 };

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