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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

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