IJob.py 18.2 KB
Newer Older
1
2
3
4
5
#MDANSE : Molecular Dynamics Analysis for Neutron Scattering Experiments
#------------------------------------------------------------------------------------------
#Copyright (C)
#2015- Eric C. Pellegrini Institut Laue-Langevin
#BP 156
6
7
#71 avenue des Martyrs
#38000 Grenoble Cedex 9
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#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

30
:author: Eric C. Pellegrini
31
32
'''

eric pellegrini's avatar
test    
eric pellegrini committed
33
34
35
36
37
38
39
40
import abc
import glob
import os
import random
import stat
import string
import subprocess
import sys
41
import traceback
eric pellegrini's avatar
test    
eric pellegrini committed
42

43
from MDANSE import PLATFORM, REGISTRY
eric pellegrini's avatar
test    
eric pellegrini committed
44
from MDANSE.Core.Error import Error
45
from MDANSE.Framework.Configurable import Configurable
46
47
from MDANSE.Framework.Jobs.JobStatus import JobStatus
from MDANSE.Framework.OutputVariables.IOutputVariable import OutputData
eric pellegrini's avatar
test    
eric pellegrini committed
48
49

class JobError(Error):
eric pellegrini's avatar
eric pellegrini committed
50
51
52
53
54
55
56
57
58
59
60
61
    '''
    This class handles any exception related to IJob-derived objects
    '''
    
    def __init__(self,job,message=None):
        '''
        Initializes the the object.
        
        :param job: the configurator in which the exception was raised
        :type job: IJob derived object
        '''

62
63
64
        trace = []                        

        tback = traceback.extract_stack()
65
        
66
67
68
        for tb in tback:
            trace.append(' -- '.join([str(t) for t in tb]))

eric pellegrini's avatar
eric pellegrini committed
69
70
        if message is None:
            message = sys.exc_info()[1]
71

eric pellegrini's avatar
eric pellegrini committed
72
        self._message = str(message)
73
74
75
76

        trace.append("\n%s" % self._message)

        trace = '\n'.join(trace)
77
                
eric pellegrini's avatar
eric pellegrini committed
78
        if job._status is not None:
79
            job._status._state["state"] = "aborted"
80
81
            job._status._state['traceback'] = trace
            job._status._state['info'] += trace
eric pellegrini's avatar
eric pellegrini committed
82
83
84
85
86
            job._status.update(force=True)
            
    def __str__(self):
        
        return self._message
eric pellegrini's avatar
test    
eric pellegrini committed
87

88
def key_generator(keySize, chars=None, prefix=""):
eric pellegrini's avatar
test    
eric pellegrini committed
89
90
91
92
    
    if chars is None:
        chars = string.ascii_lowercase + string.digits
    
93
    key = ''.join(random.choice(chars) for _ in range(keySize))
eric pellegrini's avatar
test    
eric pellegrini committed
94
95
96
97
98
    if prefix:
        key = "%s_%s" % (prefix,key)
    
    return key
        
99
class IJob(Configurable):
eric pellegrini's avatar
test    
eric pellegrini committed
100
    """
101
    This class handles a MDANSE job. In MDANSE any task modeled by a loop can be considered as a MDANSE job. 
eric pellegrini's avatar
test    
eric pellegrini committed
102
103
104
105
106
107
108
    """
            
    __metaclass__ = REGISTRY
    
    type = "job"
    
    section = "job"
eric pellegrini's avatar
eric pellegrini committed
109
    
110
    ancestor = []
eric pellegrini's avatar
test    
eric pellegrini committed
111
112
        
    @staticmethod
113
    def define_unique_name():
eric pellegrini's avatar
test    
eric pellegrini committed
114
115
116
117
118
119
120
121
122
123
124
125
        """
        Sets a name for the job that is not already in use by another running job.
        """
        
        prefix = '%d' % PLATFORM.pid()
    
        # The list of the registered jobs.
        registeredJobs = [os.path.basename(f) for f in glob.glob(os.path.join(PLATFORM.temporary_files_directory(),'*'))]
        
        while True:     
    
            # Followed by 4 random letters.
126
            name = key_generator(6, prefix=prefix)
eric pellegrini's avatar
test    
eric pellegrini committed
127
128
129
130
131
132
            
            if not name in registeredJobs:
                break
                        
        return name
        
133
    def __init__(self):
eric pellegrini's avatar
test    
eric pellegrini committed
134
135
136
137
138
        """
        The base class constructor.        
        """

        Configurable.__init__(self)
139
140

        self._outputData = OutputData()
eric pellegrini's avatar
test    
eric pellegrini committed
141
        
142
143
        self._status = None

eric pellegrini's avatar
test    
eric pellegrini committed
144
        self._info = ""
145
                                            
eric pellegrini's avatar
test    
eric pellegrini committed
146
147
148
149
150
151
152
153
    @classmethod
    def build_parallelization_test(cls, testFile, parameters=None):
        """
        Produce a file like object for a given job.\n
        :Parameters:
            #. parameters (dict): optional. If not None, the parameters with which the job file will be built.
        """
         
eric pellegrini's avatar
eric pellegrini committed
154
        f = open(testFile, 'w')
eric pellegrini's avatar
test    
eric pellegrini committed
155
156
157
158
159
160
161
162
163
164
           
        # The first line contains the call to the python executable. This is necessary for the file to
        # be autostartable.
        f.write('#!%s\n\n' % sys.executable)

        f.write('import os\n')
        f.write('import unittest\n')
        f.write('import numpy\n')
        f.write('from Scientific.IO.NetCDF import NetCDFFile\n')
        f.write('from Tests.UnitTest import UnitTest\n')
165
        f.write('from MDANSE import REGISTRY\n\n')
eric pellegrini's avatar
test    
eric pellegrini committed
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
                
        f.write('class Test%sParallel(UnitTest):\n\n' % cls.type.upper())
                    
        f.write('    def test(self):\n')      

        # Writes the line that will initialize the |parameters| dictionary.
        f.write('        parameters = {}\n')
        
        for k, v in sorted(parameters.items()):
            f.write('        parameters[%r] = %r\n' % (k, v))
                
        f.write('\n        job = REGISTRY[%r](%r)\n\n' % ('job',cls.type))

        f.write('        parameters["running_mode"] = ("monoprocessor",1)\n')
        f.write('        self.assertNotRaises(job.run,parameters,False)\n\n')

        f.write('        f = NetCDFFile(job.configuration["output_files"]["files"][0],"r")\n')
        f.write('        resMono = {}\n')
        f.write('        for k,v in f.variables.items():\n')
        f.write('            resMono[k] = v.getValue()\n')
        f.write('        f.close()\n\n')

        f.write('        parameters["running_mode"] = ("multiprocessor",2)\n')
        f.write('        self.assertNotRaises(job.run,parameters,False)\n\n')

        f.write('        f = NetCDFFile(job.configuration["output_files"]["files"][0],"r")\n')
        f.write('        resMulti = {}\n')
        f.write('        for k,v in f.variables.items():\n')
        f.write('            resMulti[k] = v.getValue()\n')
        f.write('        f.close()\n\n')

        f.write('        for k in resMono.keys():\n')
        f.write('            self.assertTrue(numpy.allclose(resMono[k],resMulti[k]))\n\n')
            
        f.write('def suite():\n')
        f.write('    loader = unittest.TestLoader()\n')
        f.write('    s = unittest.TestSuite()\n')
        f.write('    s.addTest(loader.loadTestsFromTestCase(Test%sParallel))\n' % cls.type.upper())
        f.write('    return s\n\n')
        f.write('if __name__ == "__main__":\n')
        f.write('    unittest.main(verbosity=2)\n')
        
        f.close()
        
        os.chmod(testFile,stat.S_IRWXU)

    @staticmethod
    def set_pyro_server():
    
        import Pyro.errors
        import Pyro.naming
    
        # Gets a Pyro proxy for the name server.
        locator = Pyro.naming.NameServerLocator()
    
        # Try to get an existing name server.        
        try:
            ns = locator.getNS()
            
        # Otherwise, start a new one.        
        except Pyro.errors.NamingError:
            
            subprocess.Popen([sys.executable, '-O', '-c', "import Pyro.naming; Pyro.naming.main([])"], stdout = subprocess.PIPE)
            ns = None
            while ns is None:
                try:
                    ns = locator.getNS()
                except Pyro.errors.NamingError:
                    pass
                            
    @property
    def name(self):
        return self._name

    @property
    def configuration(self):
        return self._configuration

    @abc.abstractmethod
    def finalize(self):        
        pass
        
    @abc.abstractmethod
    def initialize(self):        
        pass

    @abc.abstractmethod
    def run_step(self):
        pass
            
    @classmethod
    def save(cls, jobFile, parameters=None):
        """
        Save a job file for a given job.\n
        :Parameters:
            #. jobFile (str): The name of the output job file.\n
            #. parameters (dict): optional. If not None, the parameters with which the job file will be built.
        """
264
        
eric pellegrini's avatar
eric pellegrini committed
265
266
        f = open(jobFile, 'w')
                   
eric pellegrini's avatar
test    
eric pellegrini committed
267
268
269
270
271
272
273
        # The first line contains the call to the python executable. This is necessary for the file to
        # be autostartable.
        f.write('#!%s\n\n' % sys.executable)
        
        # Writes the input file header.
        f.write('########################################################\n')
        f.write('# This is an automatically generated MDANSE run script #\n')
274
        f.write('########################################################\n\n')
eric pellegrini's avatar
test    
eric pellegrini committed
275
276
277
278
279
280
281
282
283
284
285
286
                                    
        # Write the import.
        f.write("from MDANSE import REGISTRY\n\n")
                        
        f.write('################################################################\n')
        f.write('# Job parameters                                               #\n')
        f.write('################################################################\n\n')

        # Writes the line that will initialize the |parameters| dictionary.
        f.write('parameters = {}\n')
        
        if parameters is None:
287
            parameters = cls.get_default_parameters()
eric pellegrini's avatar
test    
eric pellegrini committed
288
289
290
291
292
293
294
295
296
297
        
        for k, v in sorted(parameters.items()):
            f.write('parameters[%r] = %r\n' % (k, v))

        f.write('\n')
        f.write('################################################################\n')
        f.write('# Setup and run the analysis                                   #\n')
        f.write('################################################################\n')
        f.write('\n')
    
298
        f.write('job = REGISTRY[%r][%r]()\n' % ('job',cls.type))
eric pellegrini's avatar
eric pellegrini committed
299
        f.write('job.run(parameters,status=True)')
eric pellegrini's avatar
test    
eric pellegrini committed
300
301
302
303
304
305
306
307
308
309
310
311
312
         
        f.close()
        
        os.chmod(jobFile,stat.S_IRWXU)
                
    @classmethod
    def build_test(cls, testFile, parameters=None):
        """
        Produce a file like object for a given job.\n
        :Parameters:
            #. parameters (dict): optional. If not None, the parameters with which the job file will be built.
        """
                
eric pellegrini's avatar
eric pellegrini committed
313
        f = open(testFile, 'w')
eric pellegrini's avatar
test    
eric pellegrini committed
314
315
316
317
318
319
           
        # The first line contains the call to the python executable. This is necessary for the file to
        # be autostartable.
        f.write('#!%s\n\n' % sys.executable)

        f.write('import unittest\n')
320
        f.write('from Tests.UnitTests.UnitTest import UnitTest\n')
321
        f.write('from MDANSE import REGISTRY\n\n')
eric pellegrini's avatar
test    
eric pellegrini committed
322
323
324
325
326
327
328
329
                
        f.write('class Test%s(UnitTest):\n\n' % cls.type.upper())
        
        f.write('    def test(self):\n')      

        # Writes the line that will initialize the |parameters| dictionary.
        f.write('        parameters = {}\n')
        
330
        if parameters is None:
331
            parameters = cls.get_default_parameters()
332
        
eric pellegrini's avatar
test    
eric pellegrini committed
333
334
335
336
        for k, v in sorted(parameters.items()):
            f.write('        parameters[%r] = %r\n' % (k, v))
    
        # Sets |analysis| variable to an instance analysis to save. 
337
338
        f.write('        job = REGISTRY[%r][%r]()\n' % ('job',cls.type))
        f.write('        self.assertNotRaises(job.run, parameters, status=False)\n\n')
eric pellegrini's avatar
test    
eric pellegrini committed
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
        
        f.write('def suite():\n')
        f.write('    loader = unittest.TestLoader()\n')
        f.write('    s = unittest.TestSuite()\n')
        f.write('    s.addTest(loader.loadTestsFromTestCase(Test%s))\n' % cls.type.upper())
        f.write('    return s\n\n')
        f.write("if __name__ == '__main__':\n")
        f.write('    unittest.main(verbosity=2)\n')
        
        f.close()
        
        os.chmod(testFile,stat.S_IRWXU)
        
    def _run_monoprocessor(self):

        for index in range(self.numberOfSteps):
            idx, x = self.run_step(index)                            
            self.combine(idx, x)
            
            if self._status is not None:
                if self._status.is_stopped():
                    self._status.cleanup()
                    return
                else:
                    self._status.update()
        
    def _run_multiprocessor(self):

        import MDANSE.DistributedComputing.MasterSlave as MasterSlave

        script = os.path.abspath(os.path.join(PLATFORM.package_directory(),'DistributedComputing','Slave.py'))
                
        master = MasterSlave.initializeMasterProcess(self._name, slave_script=script, use_name_server=False)

        master.setGlobalState(job=self)
        master.launchSlaveJobs(n=self.configuration['running_mode']['slots'],port=master.pyro_daemon.port)

        for index in range(self.numberOfSteps):
            master.requestTask('run_step',MasterSlave.GlobalStateValue(1,'job'),index)
        
        for index in range(self.numberOfSteps):
            _, _, (idx, x) = master.retrieveResult('run_step')
            self.combine(idx, x)

            if self._status is not None:
                if self._status.is_stopped():
                    self._status.cleanup()
                    return
                else:
                    self._status.update()
            
        master.shutdown()
        
    def _run_remote(self):

394
        IJob.set_pyro_server()
eric pellegrini's avatar
test    
eric pellegrini committed
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420

        import MDANSE.DistributedComputing.MasterSlave as MasterSlave

        tasks = MasterSlave.initializeMasterProcess(self._name, slave_module='MDANSE.DistributedComputing.Slave')
             
        tasks.setGlobalState(job=self)

        if self._status is not None:
            self._status.start(self.numberOfSteps,rate=0.1)
                
        for  index in range(self.numberOfSteps):
            tasks.requestTask('run_step',MasterSlave.GlobalStateValue(1,'job'),index)

        for index in range(self.numberOfSteps):
            _, _, (idx, x) = tasks.retrieveResult("run_step")
            self.combine(idx, x)

        if self._status is not None:
            if self._status.is_stopped():
                self._status.cleanup()
                return
            else:
                self._status.update()
            
    _runner = {"monoprocessor" : _run_monoprocessor, "multiprocessor" : _run_multiprocessor, "remote" : _run_remote}

421
    def run(self,parameters,status=False):
eric pellegrini's avatar
test    
eric pellegrini committed
422
423
424
425
426
        """
        Run the job.
        """
        
        try:
427
            
428
            self._name = IJob.define_unique_name()
429
430
431
432
                                                        
            if status:
                self._status = JobStatus(self)
            
eric pellegrini's avatar
eric pellegrini committed
433
            self.setup(parameters)
434
                                    
eric pellegrini's avatar
eric pellegrini committed
435
            self.initialize()
436

eric pellegrini's avatar
eric pellegrini committed
437
438
            self._info = 'Information about %s job.\n' % self._name
            self._info += str(self)
439
            
440
441
442
443
            if self._status is not None:
                self._status.start(self.numberOfSteps,rate=0.1)
                self._status.state['info'] = self._info
                                        
eric pellegrini's avatar
eric pellegrini committed
444
445
446
            if getattr(self,'numberOfSteps', 0) <= 0:
                raise JobError(self,"Invalid number of steps for job %s" % self._name)
    
447
448
449
450
            if self.configuration.has_key('running_mode'):
                mode = self.configuration['running_mode']['mode']
            else:
                mode = 'monoprocessor'
eric pellegrini's avatar
eric pellegrini committed
451
    
452
            IJob._runner[mode](self)
eric pellegrini's avatar
eric pellegrini committed
453
454
455
456
457
458
    
            self.finalize()
    
            if self._status is not None:
                self._status.finish()
        except:
459
460
            tb = traceback.format_exc()
            raise JobError(self,tb)
eric pellegrini's avatar
test    
eric pellegrini committed
461
462
463
464

    @property
    def info(self):
            
465
        return self._info
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500

    @classmethod
    def save_template(cls, shortname,longname=None):
        
        if longname is None:
            longname = shortname
            
        if REGISTRY['job'].has_key(shortname):
            raise IOError("A job with %r name is already stored in the registry" % shortname)
                        
        from MDANSE import PREFERENCES
        macrosDir =  PREFERENCES.get_preferences_item("macros_directory").get_value()
        
        templateFile = os.path.join(macrosDir,"%s.py" % longname)
                
        f = open(templateFile,'w')
        
        f.write(
'''import collections

from MDANSE.Framework.Jobs.IJob import IJob

class %s(IJob):
    """
    You should enter the description of your job here ...
    """
    
    type = %r
    
    # You should enter the label under which your job will be referenced from the gui.
    label = %r

    # You should enter the category under which your job will be references.
    category = ('My jobs',)
    
501
    ancestor = ["mmtk_trajectory"]
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551

    # You should enter the configuration of your job here
    # Here a basic example of a job that will use a MMTK trajectory, a frame selection and an output file in NetCDF and ASCII file formats
    settings = collections.OrderedDict()
    settings['trajectory']=('mmtk_trajectory',{})
    settings['frames']=('frames', {"dependencies":{'trajectory':'trajectory'}})
    settings['output_files']=('output_files', {"formats":["netcdf","ascii"]})
            
    def initialize(self):
        """
        Initialize the input parameters and analysis self variables
        """

        # Compulsory. You must enter the number of steps of your job.
        # Here for example the number of selected frames
        self.numberOfSteps = self.configuration['frames']['number']
                        
        # Create an output data for the selected frames.
        self._outputData.add("times", "line", self.configuration['frames']['time'], units='ps')


    def run_step(self, index):
        """
        Runs a single step of the job.
        """
                                
        return index, None
    
    
    def combine(self, index, x):
        """
        Synchronize the output of each individual run_step output.
        """     
                    
    def finalize(self):
        """
        Finalizes the job (e.g. averaging the total term, output files creations ...).
        """ 

        # The output data are written
        self._outputData.write(self.configuration['output_files']['root'], self.configuration['output_files']['formats'], self._info)
        
        # The trajectory is closed
        self.configuration['trajectory']['instance'].close()        
''' % (longname,shortname,longname))
        
        
        f.close()
        
        return templateFile