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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

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