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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

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