Configurable.py 10.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#MDANSE : Molecular Dynamics Analysis for Neutron Scattering Experiments
#------------------------------------------------------------------------------------------
#Copyright (C)
#2015- Eric C. Pellegrini Institut Laue-Langevin
#BP 156
#6, rue Jules Horowitz
#38042 Grenoble Cedex 9
#France
#pellegrini[at]ill.fr
#goret[at]ill.fr
#aoun[at]ill.fr
#
#This library is free software; you can redistribute it and/or
#modify it under the terms of the GNU Lesser General Public
#License as published by the Free Software Foundation; either
#version 2.1 of the License, or (at your option) any later version.
#
#This library is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#Lesser General Public License for more details.
#
#You should have received a copy of the GNU Lesser General Public
#License along with this library; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

''' 
Created on Mar 30, 2015

@author: pellegrini
'''

import collections

from MDANSE.Core.Error import Error
from MDANSE import REGISTRY

class ConfigurationError(Error):
    '''
    Handles the exception that may occurs when configuring an object that derives from MDANSE.Core.Configurable class.
    '''
    pass

class Configurable(object):
    '''
    This class allows any object that derives from it to be configurable within the MDANSE framework.
    
    Within that framework, to be configurable, a class must:
        #. derive from this class
        #. implement the "configurators"  class attribute as a list of 3-tuple whose:
            #.. 0-value is the type of the configurator that will be used to fetch the corresponding 
                MDANSE.Framework.Configurators.IConfigurator.IConfigurator derived class from the configurators registry
            #.. 1-value is the name of the configurator that will be used as the key of the _configuration attribute.
            #.. 2-value is the dictionary of the keywords used when initializing the configurator.  
    '''
    
eric pellegrini's avatar
eric pellegrini committed
57
58
    settings = collections.OrderedDict()
    
59
60
61
62
63
64
65
    def __init__(self):
        '''
        Constructor
        '''
               
        self._configuration = {}
        
eric pellegrini's avatar
eric pellegrini committed
66
        if not isinstance(self.settings,dict):
67
            raise ConfigurationError("Invalid type for settings: must be a mapping-like object")
68
69

        self._configurators = {}
eric pellegrini's avatar
eric pellegrini committed
70
        for name,(typ,kwds) in self.settings.items():
71

72
73
74
75
76
            try:
                self._configurators[name] = REGISTRY["configurator"][typ](name, **kwds)
            # Any kind of error has to be caught
            except:
                raise ConfigurationError("Invalid type for %r configurator" % name)
77
                     
78
79
80
81
82
83
84
85
86
        self._configured=False
        
    def __getitem__(self, name):
        """
        Returns a configuration item given its name.
        
        :param name: the name of the configuration item
        :type name: str 
        
87
        If not found return an empty dictionary. 
88
        """
89
                
90
        return self._configuration.setdefault(name,{})
eric pellegrini's avatar
eric pellegrini committed
91
92
93
94
95
    
    @classmethod
    def set_settings(cls, settings):
        
        cls.settings.clear()
96
        
eric pellegrini's avatar
eric pellegrini committed
97
98
99
        if isinstance(settings,dict):
            cls.settings.update(settings)        
    
100
101
102
103
104
105
106
107
108
109
110
    @property
    def configuration(self):
        '''
        Return the configuration bound to the Configurable object.
        
        :return: the configuration bound to the Configurable object.
        :rtype: dict
        '''
        
        return self._configuration
    
111
112
113
114
115
116
117
118
119
120
121
122
    def setup(self,parameters):
        '''
        Setup the configuration according to a set of input parameters.
        
        :param parameters: the input parameters
        :type parameters: dict
        '''
                
        # Cleans the previous configuration
        self._configuration.clear()

        self._configured=False
eric pellegrini's avatar
eric pellegrini committed
123
                        
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
        # If no configurator has to be configured, just return
        if not self._configurators:
            self._configured=True
            return
        
        if isinstance(parameters,dict):
            # Loop over the configuration items          
            for k,v in self._configurators.items():
                # If no input parameter has been set for this item, use its default value.
                if not parameters.has_key(k):
                    parameters[k] = v.default
        else:
            raise ConfigurationError("Invalid type for configuration parameters")             
                        
        toBeConfigured = set(self._configurators.keys())
        configured = set()
                
        while toBeConfigured != configured:
eric pellegrini's avatar
eric pellegrini committed
142
                        
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
            progress = False

            for name,conf in self._configurators.items():
                                                                                
                if name in configured:
                    continue
                
                if conf.check_dependencies(configured):

                    conf.configure(self,parameters[name])
                    
                    self._configuration[name]=conf
                                                            
                    configured.add(name)
                    
                    progress = True
                    
            if not progress:
                raise ConfigurationError("Circular or unsatisfiable dependencies when setting up configuration.")

        self._configured=True

    def __str__(self):
        '''
        Returns the informations about the current configuration in text form.
        
        :return: the informations about the current configuration in text form
        :rtype: str
        '''
        
        if not self._configured:
            return "Not yet configured"
        
        info = []
        
        for configurator in self._configuration.values():
            
            info.append(configurator.get_information())
            
        return "\n".join(info)
    
    @classmethod
    def build_doc(cls):
        '''
        Return the documentation about a configurable class based on its configurators contents.
        
        :param cls: the configurable class for which documentation should be built
        :type cls: an instance of MDANSE.Framework.Configurable.Configurable derived class
        
        :return: the documnetation about the configurable class
        :rtype: str
        '''
              
196
        settings = getattr(cls,"settings",{})
197
        
eric pellegrini's avatar
eric pellegrini committed
198
        if not isinstance(settings,dict):
199
            raise ConfigurationError("Invalid type for settings: must be a mapping-like object")
200
201
202
                                    
        doclist = []
        
203
        for name,(typ,kwds) in settings.items():
204
            cfg=REGISTRY["configurator"][typ](name, **kwds)
205
206
207
            descr = kwds.get("description","")
            descr += "\n"+str(cfg.__doc__)
            doclist.append({'Configurator' : name,'Default value' : repr(cfg.default),'Description' : descr})
208
                                    
209
210
211
212
213
214
215
216
217
218
219
220
        docstring = "\n:Example:\n\n"
        docstring += ">>> from MDANSE import REGISTRY\n"
        docstring += ">>> \n"
        docstring += ">>> parameters = {}\n"
        for k,v in cls.get_default_parameters().items():
            docstring += ">>> parameters[%r]=%r\n" % (k,v)
        docstring += ">>> \n"
        docstring += ">>> job = REGISTRY['job'][%r]()\n" % cls.type            
        docstring += ">>> job.setup(parameters)\n"
        docstring += ">>> job.run()\n"
                                   
        docstring += '\n**Job input configurators:** \n\n'
221
222
223
224

        columns = ['Configurator','Default value','Description']
        
        sizes = [len(v) for v in columns]
225
226
        
        for v in doclist:
227
228
229
230
231
232
233
234
235
236
237
            sizes[0] = max(sizes[0],len(v['Configurator']))
            sizes[1] = max(sizes[1],len(v['Default value']))
            # Case of Description field: has to be splitted and parsed for inserting sphinx "|" keyword for multiline            
            v['Description'] = v['Description'].strip()
            v['Description'] = v["Description"].split("\n")
            v['Description'] = ["| " + vv.strip() for vv in v['Description']]
            sizes[2] = max(sizes[2],max([len(d) for d in v["Description"]]))

        docstring += '+%s+%s+%s+\n'% ("-"*(sizes[0]+1),"-"*(sizes[1]+1),"-"*(sizes[2]+1))
        docstring += '| %-*s| %-*s| %-*s|\n'% (sizes[0],columns[0],sizes[1],columns[1],sizes[2],columns[2])
        docstring += '+%s+%s+%s+\n'% ("="*(sizes[0]+1),"="*(sizes[1]+1),"="*(sizes[2]+1))
238
        
239
240
241
242
243
244
245
246
247
        for v in doclist:
            docstring += '| %-*s| %-*s| %-*s|\n'% (sizes[0],v["Configurator"],sizes[1],v["Default value"],sizes[2],v["Description"][0])
            if len(v["Description"]) > 1:
                for descr in v["Description"][1:]:
                    docstring += '| %-*s| %-*s| %-*s|\n'% (sizes[0],"",sizes[1],"",sizes[2],descr)
            docstring += '+%s+%s+%s+\n'% ("-"*(sizes[0]+1),"-"*(sizes[1]+1),"-"*(sizes[2]+1))
            
        docstring += "\n"
        
248
249
250
251
252
253
254
255
256
257
258
259
260
261
        return docstring
    
    @classmethod
    def get_default_parameters(cls):
        '''
        Return the default parameters of a configurable based on its configurators contents.
        
        :param cls: the configurable class for which documentation should be built
        :type cls: an instance of MDANSE.Framework.Configurable.Configurable derived class
        
        :return: a dictionary of the default parameters of the configurable class
        :rtype: dict
        '''
        
262
        settings = getattr(cls,"settings",{})
263
        
eric pellegrini's avatar
eric pellegrini committed
264
        if not isinstance(settings,dict):
265
            raise ConfigurationError("Invalid type for settings: must be a mapping-like object")
266
267
                                    
        params = collections.OrderedDict()
268
        for name,(typ,kwds) in settings.items():
269
270
271
            cfg=REGISTRY["configurator"][typ](name, **kwds)        
            params[name] = cfg.default
            
272
273
274
275
276
277
278
279
280
281
282
283
        return params
    
    @property
    def configurators(self):
        '''
        Return the configurator objects of this Configurable object
        
        :return: a mapping between the name of the configurator object and its corresponding IConfigurator instance
        :rtype: dict 
        '''
        
        return self._configurators