1 | #!/usr/bin/env python |
---|
2 | """ Model factory |
---|
3 | Class that creates models by looking up the name of a model |
---|
4 | in the models directory |
---|
5 | |
---|
6 | @author: Mathieu Doucet / UTK |
---|
7 | @contact: mathieu.doucet@nist.gov |
---|
8 | """ |
---|
9 | |
---|
10 | import os |
---|
11 | import imp |
---|
12 | |
---|
13 | # info |
---|
14 | __author__ = "Mathieu Doucet" |
---|
15 | |
---|
16 | class ModelFactory: #pylint: disable-msg=W0232 |
---|
17 | """ Class to create available models """ |
---|
18 | |
---|
19 | def getModel(self, name="BaseComponent"): #pylint: disable-msg=R0201 |
---|
20 | """ Returns the model if found |
---|
21 | @param name: name of the model to look for |
---|
22 | @return: the model object |
---|
23 | """ |
---|
24 | |
---|
25 | # Look up the files in the model directory |
---|
26 | |
---|
27 | # Find correct directory first... |
---|
28 | path = os.path.dirname(__file__) |
---|
29 | if(os.path.isfile("%s/%s.py" % (path, name))): |
---|
30 | fObj, path, descr = imp.find_module(name, [path]) |
---|
31 | modObj = imp.load_module(name, fObj, path, descr) |
---|
32 | if hasattr(modObj, name): |
---|
33 | return getattr(modObj, name)() |
---|
34 | else: |
---|
35 | raise ValueError, "Could not find module file" |
---|
36 | |
---|
37 | raise ValueError, "Could not find module %s" % name |
---|
38 | |
---|
39 | def getAllModels(self): #pylint: disable-msg=R0201 |
---|
40 | """ Returns a list of all available models |
---|
41 | @return: python list object |
---|
42 | """ |
---|
43 | |
---|
44 | # from AbstractModel import AbstractModel |
---|
45 | # Find correct directory first... |
---|
46 | path = os.path.dirname(__file__) |
---|
47 | filelist = os.listdir(path) |
---|
48 | internal_components = ["BaseComponent", "AddComponent", |
---|
49 | "SubComponent", "DivComponent", "MulComponent", |
---|
50 | "DisperseModel", "ModelFactory", "ModelIO"] |
---|
51 | |
---|
52 | funclist = [] |
---|
53 | for filename in filelist: |
---|
54 | toks = filename.split('.') |
---|
55 | # Look for exceptions... |
---|
56 | # TODO: These should be in another directory |
---|
57 | if len(toks)==2 and toks[0].count('__')==0 and toks[1]=='py' \ |
---|
58 | and not toks[0] in internal_components: |
---|
59 | funclist.append(toks[0]) |
---|
60 | |
---|
61 | return funclist |
---|
62 | |
---|
63 | # main |
---|
64 | if __name__ == '__main__': |
---|
65 | print ModelFactory().getAllModels() |
---|
66 | app = ModelFactory().getModel('CylinderModel') |
---|
67 | print "%s: f(45) = %g" % (app.name, app.run(1)) |
---|
68 | |
---|
69 | # End of file |
---|