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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

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