csworkflow.py 12.8 KB
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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 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 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 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 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 394 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
#! /usr/bin/env python
# ==========================================================================
# This script executes a workflow defined in an XML file.
#
# Copyright (C) 2016 Juergen Knoedlseder
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# ==========================================================================
import gammalib
import ctools
import cscripts
import sys


# ================ #
# csworkflow class #
# ================ #
class csworkflow(ctools.cscript):
    """
    """
    def __init__(self, *argv):
        """
        Constructor.
        """
        # Set name and version
        self.name    = "csworkflow"
        self.version = "1.0.0"

        # Set members
        self.workflow = gammalib.GXml()
        self.actors   = []

        # Make sure that parfile exists
        self.parfile()

        # Initialise application
        if len(argv) == 0:
            ctools.cscript.__init__(self, self.name, self.version)
        elif len(argv) ==1:
            ctools.cscript.__init__(self, self.name, self.version, *argv)
        else:
            raise TypeError("Invalid number of arguments given.")

        # Set logger properties
        self.log_header()
        self.log.date(True)

        # Return
        return

    def __del__(self):
        """
        Destructor.
        """
        # Return
        return

    def parfile(self):
        """
        Check if parfile exists. If parfile does not exist then create a
        default parfile. This kluge avoids shipping the cscript with a parfile.
        """
        # Set parfile name
        parfile = self.name+".par"

        # Load parfile or create one
        try:
            pars = gammalib.GApplicationPars(parfile)
        except:
            # Signal if parfile was not found
            print("Parfile "+parfile+" not found. Create default parfile.")

            # Create default parfile
            pars = gammalib.GApplicationPars()
            pars.append(gammalib.GApplicationPar("inflow","f","h","test/data/workflow.xml","","","Input workflow XML file"))
            pars.append_standard()
            pars.append(gammalib.GApplicationPar("logfile","f","h","csworkflow.log","","","Log filename"))
            pars.save(parfile)

        # Return
        return

    def get_parameters(self):
        """
        Get parameters from parfile.
        """
        # Load workflow XML file
        xmlfile       = self["inflow"].filename()
        self.workflow = gammalib.GXml(xmlfile.url())

        # Return
        return

    def execute(self):
        """
        Execute the script.
        """
        # Run the script
        self.run()

        # Return
        return

    def run(self):
        """
        Run the script.
        """
        # Switch screen logging on in debug mode
        if self.logDebug():
            self.log.cout(True)

        # Get parameters
        self.get_parameters()

        #  Write input parameters into logger
        if self.logTerse():
            self.log_parameters()
            self.log("\n")

        # Parse XML file
        if self.logTerse():
            self.log("\n")
            self.log.header1("Parse workflow XML file")
        self.parse_workflow()

        # Execute workflow
        if self.logTerse():
            self.log("\n")
            self.log.header1("Execute workflow")
        self.execute_workflow()

        # Return
        return

    def parse_workflow(self):
        """
        """
        # Get workflow
        workflow = self.workflow.element("workflow")
        
        # Get number of actors
        num_actors = workflow.elements("actor")

        # Initialise actors
        self.actors = []

        # Loop over all actors
        for i in range(num_actors):
        
            # Get actor
            actor = workflow.element("actor", i)

            # Initialise parameters and input actors
            input_parameters  = []
            output_parameters = []
            input_actors      = []
            output_actors     = []

            # Get actor attributes
            name = actor.attribute("name")
            tool = actor.attribute("tool")

            # Get actor input parameters
            if actor.elements("input") > 0:
                actor_inputs = actor.element("input")
                num_inputs   = actor_inputs.elements("parameter")
                for k in range(num_inputs):
                    input       = actor_inputs.element("parameter", k)
                    input_name  = input.attribute("name")
                    input_value = input.attribute("value")
                    input_actor = input.attribute("actor")
                    parameter   = {'name': input_name, \
                                   'value': input_value, \
                                   'actor': input_actor}
                    input_parameters.append(parameter)
                    if input_actor != "":
                        if input_actor not in input_actors:
                            input_actors.append(input_actor)

            # Get actor output parameters
            if actor.elements("output") > 0:
                actor_output = actor.element("output")
                num_outputs  = actor_output.elements("parameter")
                for k in range(num_outputs):
                    output       = actor_output.element("parameter", k)
                    output_name  = output.attribute("name")
                    output_value = output.attribute("value")
                    output_actor = output.attribute("actor")
                    parameter    = {'name': output_name, \
                                    'value': output_value, \
                                    'actor': output_actor}
                    output_parameters.append(parameter)
                    if output_actor != "":
                        if output_actor not in output_actors:
                            output_actors.append(output_actor)

            # Determine number of dependencies
            num_inputs = len(input_actors)

            # Set actor status
            if num_inputs > 0:
                status = 'waiting for input'
            else:
                status = 'ready'

            # Create actor entry
            entry = {'name': name,
                     'tool': tool,
                     'input_parameters': input_parameters,
                     'input_actors': input_actors,
                     'output_parameters': output_parameters,
                     'output_actors': output_actors,
                     'status': status}

            # Append entry
            self.actors.append(entry)

            # Log information about actors
            if self.logNormal():
                self.log.parformat("Actor \""+name+"\"")
                self.log(tool)
                self.log("\n")
                if num_inputs == 0:
                    self.log.parformat("  Predecessor")
                    self.log("none\n")
                else:
                    if num_inputs == 1:
                        self.log.parformat("  Predecessor")
                    else:
                        self.log.parformat("  Predecessors")
                    for k in range(num_inputs):
                        if k > 0:
                            self.log(", ")
                        self.log("\""+input_actors[k]+"\"")
                    self.log("\n")

        # Return
        return

    def execute_workflow(self):
        """
        """
        # Continue while there are actors
        while len(self.actors) > 0:

            # Find actors which are ready
            num_executed = 0
            for actor in self.actors:

                # If actor is ready then execute it
                if actor['status'] == 'ready':

                    # Log execution start
                    if self.logNormal():
                        self.log.parformat("Execute actor")
                        self.log("\""+actor['name']+"\"\n")

                    # Execute actor
                    self.execute_actor(actor)

                    # Log execution finish
                    if self.logNormal():
                        self.log.parformat("Finished actor execution")
                        self.log("\""+actor['name']+"\"\n")

                    # Set actor status to finished
                    actor['status'] = 'finished'

                    # Increment number of executed actors
                    num_executed += 1

            # Break if no actors have been executed
            if num_executed < 1:
                break
            
            # Update actor status
            for actor in self.actors:
                if actor['status'] != 'finished':
                    input_actors = actor['input_actors']
                    ready        = True
                    for input_actor in input_actors:
                        a = self.get_actor(input_actor)
                        if a['status'] != 'finished':
                            ready = False
                            break
                    if ready:
                        actor['status'] = 'ready'

        # Return
        return

    def execute_actor(self, actor):
        """
        Excute an actor.
        """
        # Log input parameters
        if self.logNormal():
            pars = actor['input_parameters']
            for par in pars:
                self.log.parformat("  Input parameter")
                self.log(par['name'])
                self.log("=")
                self.log(self.get_parameter_value(par))
                self.log("\n")

        # Log output parameters
        if self.logNormal():
            pars = actor['output_parameters']
            for par in pars:
                self.log.parformat("  Output parameter")
                self.log(par['name'])
                self.log("=")
                self.log(self.get_parameter_value(par))
                self.log("\n")

        # Set actor tool
        if 'tool' in actor:
            tool = actor['tool']
            if tool[:2] == 'ct':
                tool_eval = 'ctools.'+tool+'()'
            elif tool[:2] == 'cs':
                tool_eval = 'cscripts.'+tool+'()'
            else:
                tool_eval = ""
        if tool_eval == "":
            return

        # Create actor tool object
        object = eval(tool_eval)

        # Set actor input parameters
        pars = actor['input_parameters']
        for par in pars:
            app_par = object[par['name']]
            app_par.value(self.get_parameter_value(par))
            object[par['name']] = app_par

        # Set actor output parameters
        pars = actor['output_parameters']
        for par in pars:
            app_par = object[par['name']]
            app_par.value(self.get_parameter_value(par))
            object[par['name']] = app_par

        # Execute actor
        object.logFileOpen()
        object.execute()
        
        # Return
        return

    def get_parameter_value(self, par):
        """
        Get the parameter value from the respective actor.
        """
        # If the actor is empty then simply return the value
        if (par['actor'] == ""):
            value = par['value']

        # ... otherwise get the value from the actor
        else:
            found = False
            actor = self.get_actor(par['actor'])
            for output in actor['output_parameters']:
                if output['name'] == par['value']:
                    value = output['value']
                    found = True
                    break
            if not found:
                msg = "Parameter \""+par['value']+"\" is not an output "\
                      "parameter of actor \""+par['actor']+"\"."
                raise RuntimeError(msg)
        
        # Return value
        return value

    def get_actor(self, name):
        """
        Get the actor with the specified name.
        """
        # Return actor with specified name
        for actor in self.actors:
            if actor['name'] == name:
                return actor

        # Throw an exception
        msg = "Actor \""+name+"\" not found."
        raise RuntimeError(msg)
 
        # Return
        return


# ======================== #
# Main routine entry point #
# ======================== #
if __name__ == '__main__':
    """
    Executes workflow.
    """
    # Create instance of application
    app = csworkflow(sys.argv)

    # Open logfile
    app.logFileOpen()

    # Execute application
    app.execute()