Skip to content

Core


The core data structures for starting up studies.

This module contains all of the core data structures that are needed for constructing and representing studies and the moving parts that they require. These moving parts include but are not limited to:

  • Classes for representing the abstract flow of a study. These objects at their core are the Study and StudyStep classes that are used to construct a DAG for the flow.
  • Classes that represent the items in a study's environment such as variables, scripts, and dependencies (paths, git repos, etc.)
  • Classes for managing the environment and that know how to apply the environment to an abstract flow.
  • A set of classes for managing parameters and generating combinations of parameters in a clean Pythonic way.

Combination

Bases: object

Class representing a combination of parameters.

This class represents a combination of parameters generated by a class of type ParameterGenerator. The only time a user should ever get an instance of a Combination from the ParameterGenerator is when a combination of parameters is VALID.

Source code in maestrowf/datastructures/core/parameters.py
class Combination(object):
    """
    Class representing a combination of parameters.

    This class represents a combination of parameters generated by a class of
    type ParameterGenerator. The only time a user should ever get an instance
    of a Combination from the ParameterGenerator is when a combination of
    parameters is VALID.
    """

    def __init__(self, token="$"):
        """
        Initialize an empty Combination class.

        A Combination comes packed with the following:
            - Corresponding values for each parameter in the instance.
            - A name for each parameter in instance.
            - Labels for each parameter-value combination in the instance.

        The 'token' method parameter defines the character(s) that are expected
        in front of user parameterized values in strings when an instance of
        a Combination is applied. For example, assume that we have an instance
        'c' of the Combination class that has had the parameter 'PARAM1' added.
        'PARAM1' is named 'COMPONENT1' and 'token' is left at its default value
        of '$'. 'PARAM1' has some arbitrary value that was set. In order to
        substitute the different variations of 'PARAM1' in a string when the
        apply method is called, the user would include the following mark up:

        * The value of 'PARAM1': '$(PARAM1)'
        * The label of 'PARAM1': '$(PARAM1.label)'
        * The name of 'PARAM1':  '$(PARAM1.name)'

        :param token: Token expected to be found in front of a parameter.
        """
        self._params = {}
        self._labels = OrderedDict()
        self._names = {}
        self._token = token

    def add(self, key, name, value, label):
        """
        Add a parameter to the Combination object.

        :param key: Parameter key that identifies a replacement.
        :param name: Custom name that identifies a parameter.
        :param value: Value of the parameter in this combination.
        :param label: Value of the parameter label for this combination.
        """
        # For the combination being added, assign the expected parameterized
        # strings that the user would substitute in for.
        # Parameterized value:  <self.token>(<key>)
        logger.debug("Adding parameter value to Combination with args: %s",
                     [key, name, value, label])
        var = "{}({})".format(self._token, key)
        logger.debug('Parameter value: %s = %s', var, value)
        self._params[var] = value
        # Parameterized label: <self.token>(<key>.label)
        var = "{}({}.label)".format(self._token, key)
        logger.debug('Label value: %s = %s', var, label)
        self._labels[var] = label
        # Parameterized name: <self.token>(<key>.name)
        var = "{}({}.name)".format(self._token, key)
        logger.debug('Name value: %s = %s', var, name)
        self._names[var] = name

    def __str__(self):
        """
        Generate the string representation of a Combination object.

        :returns: A string representing the combination.
        """
        return ".".join(self._labels.values())

    def get_param_string(self, params):
        """
        Get the combination string for the specified parameters.

        :param params: A set of parameters to be used in the string.
        :returns: A string containing the labels for the parameters in params.
        """
        combo_str = []
        for item in sorted(params):
            var = "{}({}.label)".format(self._token, item)
            combo_str.append(self._labels[var])

        return ".".join(combo_str)

    def apply(self, item):
        """
        Apply the combination to an item.

        :param item: String that may contain parameters to be substituted.
        :returns: String equal to item, except with parameters replaced.
        """
        # Apply the Combination's labels to the item.
        # These are substrings within item that are represented by the format
        # <self.token>(<key>.label)
        for key, value in self._labels.items():
            item = item.replace(key, str(value))

        # apply the Combination's values to the item.
        # These are substrings within item that are represented by the format
        # <self.token>(<key>)
        for key, value in self._params.items():
            item = item.replace(key, str(value))

        # Apply the Combination's names to the item.
        # These are substrings within item that are represented by the format
        # <self.token>(<key>.name)
        for key, name in self._names.items():
            item = item.replace(key, str(name))

        # Return the item after the Combination has applied itself to it. The
        # parameter item is simply reused since all we're doing is replacing
        # substrings.
        return item

    def get_param_values(self, params):
        """
        Get the values for the specified parameters.

        :param params: A set of parameters to be used in the string.
        :yields: Tuples of param names and values.
        """
        for key in params:
            var = "{}({})".format(self._token, key)
            yield key, self._params[var]

__init__(token='$')

Initialize an empty Combination class.

A Combination comes packed with the following: - Corresponding values for each parameter in the instance. - A name for each parameter in instance. - Labels for each parameter-value combination in the instance.

The 'token' method parameter defines the character(s) that are expected in front of user parameterized values in strings when an instance of a Combination is applied. For example, assume that we have an instance 'c' of the Combination class that has had the parameter 'PARAM1' added. 'PARAM1' is named 'COMPONENT1' and 'token' is left at its default value of '$'. 'PARAM1' has some arbitrary value that was set. In order to substitute the different variations of 'PARAM1' in a string when the apply method is called, the user would include the following mark up:

  • The value of 'PARAM1': '$(PARAM1)'
  • The label of 'PARAM1': '$(PARAM1.label)'
  • The name of 'PARAM1': '$(PARAM1.name)'

Parameters:

Name Type Description Default
token

Token expected to be found in front of a parameter.

'$'
Source code in maestrowf/datastructures/core/parameters.py
def __init__(self, token="$"):
    """
    Initialize an empty Combination class.

    A Combination comes packed with the following:
        - Corresponding values for each parameter in the instance.
        - A name for each parameter in instance.
        - Labels for each parameter-value combination in the instance.

    The 'token' method parameter defines the character(s) that are expected
    in front of user parameterized values in strings when an instance of
    a Combination is applied. For example, assume that we have an instance
    'c' of the Combination class that has had the parameter 'PARAM1' added.
    'PARAM1' is named 'COMPONENT1' and 'token' is left at its default value
    of '$'. 'PARAM1' has some arbitrary value that was set. In order to
    substitute the different variations of 'PARAM1' in a string when the
    apply method is called, the user would include the following mark up:

    * The value of 'PARAM1': '$(PARAM1)'
    * The label of 'PARAM1': '$(PARAM1.label)'
    * The name of 'PARAM1':  '$(PARAM1.name)'

    :param token: Token expected to be found in front of a parameter.
    """
    self._params = {}
    self._labels = OrderedDict()
    self._names = {}
    self._token = token

__str__()

Generate the string representation of a Combination object.

Returns:

Type Description

A string representing the combination.

Source code in maestrowf/datastructures/core/parameters.py
def __str__(self):
    """
    Generate the string representation of a Combination object.

    :returns: A string representing the combination.
    """
    return ".".join(self._labels.values())

add(key, name, value, label)

Add a parameter to the Combination object.

Parameters:

Name Type Description Default
key

Parameter key that identifies a replacement.

required
name

Custom name that identifies a parameter.

required
value

Value of the parameter in this combination.

required
label

Value of the parameter label for this combination.

required
Source code in maestrowf/datastructures/core/parameters.py
def add(self, key, name, value, label):
    """
    Add a parameter to the Combination object.

    :param key: Parameter key that identifies a replacement.
    :param name: Custom name that identifies a parameter.
    :param value: Value of the parameter in this combination.
    :param label: Value of the parameter label for this combination.
    """
    # For the combination being added, assign the expected parameterized
    # strings that the user would substitute in for.
    # Parameterized value:  <self.token>(<key>)
    logger.debug("Adding parameter value to Combination with args: %s",
                 [key, name, value, label])
    var = "{}({})".format(self._token, key)
    logger.debug('Parameter value: %s = %s', var, value)
    self._params[var] = value
    # Parameterized label: <self.token>(<key>.label)
    var = "{}({}.label)".format(self._token, key)
    logger.debug('Label value: %s = %s', var, label)
    self._labels[var] = label
    # Parameterized name: <self.token>(<key>.name)
    var = "{}({}.name)".format(self._token, key)
    logger.debug('Name value: %s = %s', var, name)
    self._names[var] = name

apply(item)

Apply the combination to an item.

Parameters:

Name Type Description Default
item

String that may contain parameters to be substituted.

required

Returns:

Type Description

String equal to item, except with parameters replaced.

Source code in maestrowf/datastructures/core/parameters.py
def apply(self, item):
    """
    Apply the combination to an item.

    :param item: String that may contain parameters to be substituted.
    :returns: String equal to item, except with parameters replaced.
    """
    # Apply the Combination's labels to the item.
    # These are substrings within item that are represented by the format
    # <self.token>(<key>.label)
    for key, value in self._labels.items():
        item = item.replace(key, str(value))

    # apply the Combination's values to the item.
    # These are substrings within item that are represented by the format
    # <self.token>(<key>)
    for key, value in self._params.items():
        item = item.replace(key, str(value))

    # Apply the Combination's names to the item.
    # These are substrings within item that are represented by the format
    # <self.token>(<key>.name)
    for key, name in self._names.items():
        item = item.replace(key, str(name))

    # Return the item after the Combination has applied itself to it. The
    # parameter item is simply reused since all we're doing is replacing
    # substrings.
    return item

get_param_string(params)

Get the combination string for the specified parameters.

Parameters:

Name Type Description Default
params

A set of parameters to be used in the string.

required

Returns:

Type Description

A string containing the labels for the parameters in params.

Source code in maestrowf/datastructures/core/parameters.py
def get_param_string(self, params):
    """
    Get the combination string for the specified parameters.

    :param params: A set of parameters to be used in the string.
    :returns: A string containing the labels for the parameters in params.
    """
    combo_str = []
    for item in sorted(params):
        var = "{}({}.label)".format(self._token, item)
        combo_str.append(self._labels[var])

    return ".".join(combo_str)

get_param_values(params)

Get the values for the specified parameters.

:yields: Tuples of param names and values.

Parameters:

Name Type Description Default
params

A set of parameters to be used in the string.

required
Source code in maestrowf/datastructures/core/parameters.py
def get_param_values(self, params):
    """
    Get the values for the specified parameters.

    :param params: A set of parameters to be used in the string.
    :yields: Tuples of param names and values.
    """
    for key in params:
        var = "{}({})".format(self._token, key)
        yield key, self._params[var]

ExecutionGraph

Bases: DAG, PickleInterface

Datastructure that tracks, executes, and reports on study execution.

The ExecutionGraph is used to manage, monitor, and interact with tasks and the scheduler. This class searches its graph for tasks that are ready to run, marks tasks as complete, and schedules ready tasks.

The Execution class is where functionality for checking task status, logic for managing and automatically directing and manipulating the workflow should go. Essentially, if logic is needed to automatically manipulate the workflow in some fashion or additional monitoring is needed, this class is where that would go.

Source code in maestrowf/datastructures/core/executiongraph.py
 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
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 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
 501
 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
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
class ExecutionGraph(DAG, PickleInterface):
    """
    Datastructure that tracks, executes, and reports on study execution.

    The ExecutionGraph is used to manage, monitor, and interact with tasks and
    the scheduler. This class searches its graph for tasks that are ready to
    run, marks tasks as complete, and schedules ready tasks.

    The Execution class is where functionality for checking task status, logic
    for managing and automatically directing and manipulating the workflow
    should go. Essentially, if logic is needed to automatically manipulate the
    workflow in some fashion or additional monitoring is needed, this class is
    where that would go.
    """

    def __init__(self, submission_attempts=1, submission_throttle=0,
                 use_tmp=False, dry_run=False):
        """
        Initialize a new instance of an ExecutionGraph.

        :param submission_attempts: Number of attempted submissions before
            marking a step as failed.
        :param submission_throttle: Maximum number of scheduled in progress
        submissions.
        :param use_tmp: A Boolean value that when set to 'True' designates
        that ExecutionGraph should use temporary files for output.
        """
        super(ExecutionGraph, self).__init__()
        # Member variables for execution.
        self._adapter = None
        self._description = OrderedDict()

        # Generate tempdir (if specfied)
        if use_tmp:
            self._tmp_dir = tempfile.mkdtemp()
        else:
            self._tmp_dir = ""

        # Sets to track progress.
        self.completed_steps = set([SOURCE])
        self.in_progress = set()
        self.failed_steps = set()
        self.cancelled_steps = set()
        self.ready_steps = deque()
        self.is_canceled = False

        self._status_order = 'bfs'  # Set status order type
        self._status_subtree = None  # Cache bfs_subtree for status writing

        # Values for management of the DAG. Things like submission attempts,
        # throttling, etc. should be listed here.
        self._submission_attempts = submission_attempts
        self._submission_throttle = submission_throttle
        self.dry_run = dry_run

        # A map that tracks the dependencies of a step.
        # NOTE: I don't know how performant the Python dict structure is, but
        # we'll use it for now. I think this may want to be changed to an AVL
        # tree or something of that nature to guarantee worst case performance.
        self._dependencies = {}

        LOGGER.info(
            "\n------------------------------------------\n"
            "Submission attempts =       %d\n"
            "Submission throttle limit = %d\n"
            "Use temporary directory =   %s\n"
            "Tmp Dir = %s\n"
            "------------------------------------------",
            submission_attempts, submission_throttle, use_tmp, self._tmp_dir
        )

        # Error check that the submission values are valid.
        if self._submission_attempts < 1:
            _msg = "Submission attempts should always be greater than 0. " \
                   "Received a value of {}.".format(self._submission_attempts)
            LOGGER.error(_msg)
            raise ValueError(_msg)

        if self._submission_throttle < 0:
            _msg = "Throttling should be 0 for unthrottled or a positive " \
                   "integer for the number of allowed inflight jobs. " \
                   "Received a value of {}.".format(self._submission_throttle)
            LOGGER.error(_msg)
            raise ValueError(_msg)

    def _check_tmp_dir(self):
        """Check and recreate the tempdir should it have been erased."""
        # If we've specified a tmp dir and the previous tmp dir doesn't exist
        # recreate it.
        if self._tmp_dir and not os.path.exists(self._tmp_dir):
            self._tmp_dir = tempfile.mkdtemp()

    def add_step(self, name, step, workspace, restart_limit, params=None):
        """
        Add a StepRecord to the ExecutionGraph.

        :param name: Name of the step to be added.
        :param step: StudyStep instance to be recorded.
        :param workspace: Directory path for the step's working directory.
        :param restart_limit: Upper limit on the number of restart attempts.
        :param params: Iterable of tuples of step parameter names, values
        """
        data = {
                    "step":          step,
                    "state":         State.INITIALIZED,
                    "workspace":     workspace,
                    "restart_limit": restart_limit,
                }
        record = _StepRecord(**data)
        if params:
            record.add_params(params)

        self._dependencies[name] = set()
        super(ExecutionGraph, self).add_node(name, record)

    def add_connection(self, parent, step):
        """
        Add a connection between two steps in the ExecutionGraph.

        :param parent: The parent step that is required to execute 'step'
        :param step: The dependent step that relies on parent.
        """
        self.add_edge(parent, step)
        self._dependencies[step].add(parent)

    def set_adapter(self, adapter):
        """
        Set the adapter used to interface for scheduling tasks.

        :param adapter: Adapter name to be used when launching the graph.
        """
        if not adapter:
            # If we have no adapter specified, assume sequential execution.
            self._adapter = None
            return

        if not isinstance(adapter, dict):
            msg = "Adapter settings must be contained in a dictionary."
            LOGGER.error(msg)
            raise TypeError(msg)

        # Check to see that the adapter type is something the
        if adapter["type"] not in ScriptAdapterFactory.get_valid_adapters():
            msg = "'{}' adapter must be specfied in ScriptAdapterFactory." \
                  .format(adapter)
            LOGGER.error(msg)
            raise TypeError(msg)

        self._adapter = adapter

    def add_description(self, name, description, **kwargs):
        """
        Add a study description to the ExecutionGraph instance.

        :param name: Name of the study.
        :param description: Description of the study.
        """
        self._description["name"] = name
        self._description["description"] = description
        self._description.update(kwargs)

    @property
    def name(self):
        """
        Return the name for the study in the ExecutionGraph instance.

        :returns: A string of the name of the study.
        """
        return self._description["name"]

    @name.setter
    def name(self, value):
        """
        Set the name for the study in the ExecutionGraph instance.

        :param name: A string of the name for the study.
        """
        self._description["name"] = value

    @property
    def description(self):
        """
        Return the description for the study in the ExecutionGraph instance.

        :returns: A string of the description for the study.
        """
        return self._description["description"]

    @description.setter
    def description(self, value):
        """
        Set the description for the study in the ExecutionGraph instance.

        :param value: A string of the description for the study.
        """
        self._description["description"] = value

    def log_description(self):
        """Log the description of the ExecutionGraph."""
        desc = ["{}: {}".format(key, value)
                for key, value in self._description.items()]
        desc = "\n".join(desc)
        LOGGER.info(
            "\n==================================================\n"
            "%s\n"
            "==================================================\n",
            desc
        )

    def generate_scripts(self):
        """
        Generate the scripts for all steps in the ExecutionGraph.

        The generate_scripts method scans the ExecutionGraph instance and uses
        the stored adapter to write executable scripts for either local or
        scheduled execution. If a restart command is specified, a restart
        script will be generated for that record.
        """
        # An adapter must be specified
        if not self._adapter:
            msg = "Adapter not found. Specify a ScriptAdapter using " \
                  "set_adapter."
            LOGGER.error(msg)
            raise ValueError(msg)

        # Set up the adapter.
        LOGGER.info("Generating scripts...")
        adapter = ScriptAdapterFactory.get_adapter(self._adapter["type"])
        adapter = adapter(**self._adapter)

        self._check_tmp_dir()
        for key, record in self.values.items():
            if key == SOURCE:
                continue

            # Record generates its own script.
            record.setup_workspace()
            record.generate_script(adapter, self._tmp_dir)

    def _execute_record(self, record, adapter, restart=False):
        """
        Execute a StepRecord.

        :param record: The StepRecord to be executed.
        :param adapter: An instance of the adapter to be used for cluster
        submission.
        :param restart: True if the record needs restarting, False otherwise.
        """
        # Logging for debugging.
        LOGGER.info("Calling execute for StepRecord '%s'", record.name)

        num_restarts = 0    # Times this step has temporally restarted.
        retcode = None      # Execution return code.

        # While our submission needs to be submitted, keep trying:
        # 1. If the JobStatus is not OK.
        # 2. num_restarts is less than self._submission_attempts
        self._check_tmp_dir()

        # Only set up the workspace the initial iteration.
        if not restart:
            LOGGER.debug("Setting up workspace for '%s' at %s",
                         record.name, str(datetime.now()))
            # Generate the script for execution on the fly.
            record.setup_workspace()    # Generate the workspace.
            record.generate_script(adapter, self._tmp_dir)

        if self.dry_run:
            record.mark_end(State.DRYRUN)
            self.completed_steps.add(record.name)
            return

        while retcode != SubmissionCode.OK and \
                num_restarts < self._submission_attempts:
            LOGGER.info("Attempting submission of '%s' (attempt %d of %d)...",
                        record.name, num_restarts + 1,
                        self._submission_attempts)

            # We're not restarting -- submit as usual.
            if not restart:
                LOGGER.debug("Calling 'execute' on '%s' at %s",
                             record.name, str(datetime.now()))
                retcode = record.execute(adapter)
            # Otherwise, it's a restart.
            else:
                # If the restart is specified, use the record restart script.
                LOGGER.debug("Calling 'restart' on '%s' at %s",
                             record.name, str(datetime.now()))
                # Generate the script for execution on the fly.
                record.generate_script(adapter, self._tmp_dir)
                retcode = record.restart(adapter)

            # Increment the number of restarts we've attempted.
            LOGGER.debug("Completed submission attempt %d", num_restarts)
            num_restarts += 1
            sleep((random.random() + 1) * num_restarts)

        if retcode == SubmissionCode.OK:
            self.in_progress.add(record.name)

            if record.is_local_step:
                LOGGER.info("Local step %s executed with status OK. Complete.",
                            record.name)
                record.mark_end(State.FINISHED)
                self.completed_steps.add(record.name)
                self.in_progress.remove(record.name)
        else:
            # Find the subtree, because anything dependent on this step now
            # failed.
            LOGGER.warning("'%s' failed to submit properly. "
                           "Step failed.", record.name)
            path, parent = self.bfs_subtree(record.name)
            for node in path:
                self.failed_steps.add(node)
                self.values[node].mark_end(State.FAILED)

        # After execution state debug logging.
        LOGGER.debug("After execution of '%s' -- New state is %s.",
                     record.name, record.status)

    @property
    def status_subtree(self):
        """Cache the status ordering to improve scaling"""
        if not self._status_subtree:
            if self._status_order == 'bfs':
                subtree, _ = self.bfs_subtree("_source")

            elif self._status_order == 'dfs':
                subtree, _ = self.dfs_subtree("_source", par="_source")

            self._status_subtree = [key for key in subtree
                                    if key != '_source']

        return self._status_subtree

    def write_status(self, path):
        """Write the status of the DAG to a CSV file."""
        header = "Step Name,Job ID,Workspace,State,Run Time,Elapsed Time," \
                 "Start Time,Submit Time,End Time,Number Restarts,Params"
        status = [header]

        for key in self.status_subtree:
            value = self.values[key]

            jobid_str = "--"
            if value.jobid:
                jobid_str = str(value.jobid[-1])

            # Include step root in workspace when parameterized
            if list(value.params.items()):
                ws = os.path.join(
                    * os.path.normpath(
                        value.workspace.value).split(os.sep)[-2:]
                )
            else:
                ws = os.path.split(value.workspace.value)[1]

            _ = [
                    value.name, jobid_str,
                    ws,
                    str(value.status.name), value.run_time, value.elapsed_time,
                    value.time_start, value.time_submitted, value.time_end,
                    str(value.restarts),
                    ";".join(["{}:{}".format(param, value)
                              for param, value in value.params.items()])
                ]
            _ = ",".join(_)
            status.append(_)

        stat_path = os.path.join(path, "status.csv")
        lock_path = os.path.join(path, ".status.lock")
        lock = FileLock(lock_path)
        try:
            with lock.acquire(timeout=10):
                with open(stat_path, "w+") as stat_file:
                    stat_file.write("\n".join(status))
        except Timeout:
            pass

    def _check_study_completion(self):
        # We cancelled, return True marking study as complete.
        if self.is_canceled and not self.in_progress:
            LOGGER.info("Cancelled -- completing study.")
            return StudyStatus.CANCELLED

        # check for completion of all steps
        resolved_set = \
            self.completed_steps | self.failed_steps | self.cancelled_steps
        if not set(self.values.keys()) - resolved_set:
            # some steps were cancelled and is_canceled wasn't set
            if len(self.cancelled_steps) > 0:
                logging.info("'%s' was cancelled. Returning.", self.name)
                return StudyStatus.CANCELLED

            # some steps were failures indicating failure
            if len(self.failed_steps) > 0:
                logging.info("'%s' is complete with failures. Returning.",
                             self.name)
                return StudyStatus.FAILURE

            # everything completed were are done
            logging.info("'%s' is complete. Returning.", self.name)
            return StudyStatus.FINISHED

        return StudyStatus.RUNNING

    def execute_ready_steps(self):
        """
        Execute any steps whose dependencies are satisfied.

        The 'execute_ready_steps' method is the core of how the ExecutionGraph
        manages execution. This method does the following:

        * Checks the status of existing jobs that are executing and updates
          the state if changed.
        * Finds steps that are initialized and determines what can be run
          based on satisfied dependencies and executes steps whose
          dependencies are met.

        :returns: True if the study has completed, False otherwise.
        """
        # TODO: We may want to move this to a singleton somewhere
        # so we can guarantee that all steps use the same adapter.
        adapter = ScriptAdapterFactory.get_adapter(self._adapter["type"])
        adapter = adapter(**self._adapter)

        if not self.dry_run:
            LOGGER.debug("Checking status check...")
            retcode, job_status = self.check_study_status()
        else:
            LOGGER.debug("DRYRUN: Skipping status check...")
            retcode = JobStatusCode.OK
            job_status = {}

        LOGGER.debug("Checked status (retcode %s)-- %s", retcode, job_status)

        # For now, if we can't check the status something is wrong.
        # Don't modify the DAG.
        if retcode == JobStatusCode.ERROR:
            msg = "Job status check failed -- Aborting."
            LOGGER.error(msg)
            raise RuntimeError(msg)
        elif retcode == JobStatusCode.OK:
            # For the status of each currently in progress job, check its
            # state.
            cleanup_steps = set()  # Steps that are in progress showing failed.
            cancel_steps = set()   # Steps that have dependencies to mark cancelled
            for name, status in job_status.items():
                LOGGER.debug("Checking job '%s' with status %s.", name, status)
                record = self.values[name]

                if status == State.FINISHED:
                    # Mark the step complete and notate its end time.
                    record.mark_end(State.FINISHED)
                    LOGGER.info("Step '%s' marked as finished. Adding to "
                                "complete set.", name)
                    self.completed_steps.add(name)
                    self.in_progress.remove(name)

                elif status == State.RUNNING:
                    # When detect that a step is running, mark it.
                    LOGGER.info("Step '%s' found to be running.", record.name)
                    record.mark_running()

                elif status == State.TIMEDOUT:
                    # Execute the restart script.
                    # If a restart script doesn't exist, re-run the command.
                    # If we're under the restart limit, attempt a restart.
                    if record.can_restart:
                        if record.mark_restart():
                            LOGGER.info(
                                "Step '%s' timed out. Restarting (%s of %s).",
                                name, record.restarts, record.restart_limit
                            )
                            self._execute_record(record, adapter, restart=True)
                        else:
                            LOGGER.info("'%s' has been restarted %s of %s "
                                        "times. Marking step and all "
                                        "descendents as failed.",
                                        name,
                                        record.restarts,
                                        record.restart_limit)
                            self.in_progress.remove(name)
                            cleanup_steps.update(self.bfs_subtree(name)[0])
                    # Otherwise, we can't restart so mark the step timed out.
                    else:
                        LOGGER.info("'%s' timed out, but cannot be restarted."
                                    " Marked as TIMEDOUT.", name)
                        # Mark that the step ended due to TIMEOUT.
                        record.mark_end(State.TIMEDOUT)
                        # Remove from in progress since it no longer is.
                        self.in_progress.remove(name)
                        # Add the subtree to the clean up steps
                        cleanup_steps.update(self.bfs_subtree(name)[0])
                        # Remove the current step, clean up is used to mark
                        # steps definitively as failed.
                        cleanup_steps.remove(name)
                        # Add the current step to failed.
                        self.failed_steps.add(name)

                elif status == State.HWFAILURE:
                    # TODO: Need to make sure that we do this a finite number
                    # of times.
                    # Resubmit the cmd.
                    LOGGER.warning("Hardware failure detected. Attempting to "
                                   "resubmit step '%s'.", name)
                    # We can just let the logic below handle submission with
                    # everything else.
                    self.ready_steps.append(name)

                elif status == State.FAILED:
                    LOGGER.warning(
                        "Job failure reported. Aborting %s -- flagging all "
                        "dependent jobs as failed.",
                        name
                    )
                    self.in_progress.remove(name)
                    record.mark_end(State.FAILED)
                    cleanup_steps.update(self.bfs_subtree(name)[0])

                elif status == State.UNKNOWN:
                    record.mark_end(State.UNKNOWN)
                    LOGGER.info(
                        "Step '%s' found in UNKNOWN state. Step was found "
                        "in '%s' state previously, marking as UNKNOWN. "
                        "Adding to failed steps.",
                        name, record.status)
                    cleanup_steps.update(self.bfs_subtree(name)[0])
                    self.in_progress.remove(name)

                elif status == State.CANCELLED:
                    LOGGER.info("Step '%s' was cancelled.", name)
                    self.in_progress.remove(name)
                    record.mark_end(State.CANCELLED)
                    cancel_steps.update(self.bfs_subtree(name)[0])

            # Let's handle all the failed steps in one go.
            for node in cleanup_steps:
                self.failed_steps.add(node)
                self.values[node].mark_end(State.FAILED)

            # Handle dependent steps that need cancelling
            for node in cancel_steps:
                self.cancelled_steps.add(node)
                self.values[node].mark_end(State.CANCELLED)

        # Now that we've checked the statuses of existing jobs we need to make
        # sure dependencies haven't been met.
        for key in self.values.keys():
            # We MUST dereference from the key. If we use values.items(), a
            # generator gets produced which will give us a COPY of a record and
            # not the actual record.
            record = self.values[key]

            # A completed step by definition has had its dependencies met.
            # Skip it.
            if key in self.completed_steps:
                LOGGER.debug("'%s' in completed set, skipping.", key)
                continue

            LOGGER.debug("Checking %s -- %s", key, record.jobid)
            # If the record is only INITIALIZED, we have encountered a step
            # that needs consideration.
            if record.status == State.INITIALIZED:
                LOGGER.debug("'%s' found to be initialized. Checking "
                             "dependencies. ", key)

                LOGGER.debug(
                    "Unfulfilled dependencies: %s",
                    self._dependencies[key])

                s_completed = list(filter(
                    lambda x: x in self.completed_steps,
                    self._dependencies[key]))
                self._dependencies[key] = \
                    self._dependencies[key] - set(s_completed)
                LOGGER.debug(
                    "Completed dependencies: %s\n"
                    "Remaining dependencies: %s",
                    s_completed, self._dependencies[key])

                # If the gating dependencies set is empty, we can execute.
                if not self._dependencies[key]:
                    if key not in self.ready_steps:
                        LOGGER.debug("All dependencies completed. Staging.")
                        self.ready_steps.append(key)
                    else:
                        LOGGER.debug("Already staged. Passing.")
                        continue

        # We now have a collection of ready steps. Execute.
        # If we don't have a submission limit, go ahead and submit all.
        if self._submission_throttle == 0:
            LOGGER.info("Launching all ready steps...")
            _available = len(self.ready_steps)
        # Else, we have a limit -- adhere to it.
        else:
            # Compute the number of available slots we have for execution.
            _available = self._submission_throttle - len(self.in_progress)
            # Available slots should never be negative, but on the off chance
            # we are in a slot deficit, then we will just say none are free.
            _available = max(0, _available)
            # Now, we need to take the min of the length of the queue and the
            # computed number of slots. We could have free slots, but have less
            # in the queue.
            _available = min(_available, len(self.ready_steps))
            LOGGER.info("Found %d available slots...", _available)

        for i in range(0, _available):
            # Pop the record and execute using the helper method.
            _record = self.values[self.ready_steps.popleft()]

            # If we get to this point and we've cancelled, cancel the record.
            if self.is_canceled:
                LOGGER.info("Cancelling '%s' -- continuing.", _record.name)
                _record.mark_end(State.CANCELLED)
                self.cancelled_steps.add(_record.name)
                continue

            LOGGER.debug("Launching job %d -- %s", i, _record.name)
            self._execute_record(_record, adapter)

        # check the status of the study upon finishing this round of execution
        completion_status = self._check_study_completion()
        return completion_status

    def check_study_status(self):
        """
        Check the status of currently executing steps in the graph.

        This method is used to check the status of all currently in progress
        steps in the ExecutionGraph. Each ExecutionGraph stores the adapter
        used to generate and execute its scripts.
        """
        # Set up the job list and the map to get back to step names.
        joblist = []
        jobmap = {}
        for step in self.in_progress:
            jobid = self.values[step].jobid[-1]
            joblist.append(jobid)
            jobmap[jobid] = step

        # Grab the adapter from the ScriptAdapterFactory.
        adapter = ScriptAdapterFactory.get_adapter(self._adapter["type"])
        adapter = adapter(**self._adapter)
        # Use the adapter to grab the job statuses.
        retcode, job_status = adapter.check_jobs(joblist)
        # Map the job identifiers back to step names.
        step_status = {jobmap[jobid]: status
                       for jobid, status in job_status.items()}

        # Based on return code, log something different.
        if retcode == JobStatusCode.OK:
            LOGGER.info("Jobs found for user '%s'.", getpass.getuser())
            return retcode, step_status
        elif retcode == JobStatusCode.NOJOBS:
            LOGGER.info("No jobs found.")
            return retcode, step_status
        else:
            msg = "Unknown Error (Code = {})".format(retcode)
            LOGGER.error(msg)
            return retcode, step_status

    def cancel_study(self):
        """Cancel the study."""
        joblist = []
        for step in self.in_progress:
            jobid = self.values[step].jobid[-1]
            joblist.append(jobid)

        # Grab the adapter from the ScriptAdapterFactory.
        adapter = ScriptAdapterFactory.get_adapter(self._adapter["type"])
        adapter = adapter(**self._adapter)

        # cancel our jobs
        crecord = adapter.cancel_jobs(joblist)
        self.is_canceled = True

        if crecord.cancel_status == CancelCode.OK:
            LOGGER.info("Successfully requested to cancel all jobs.")
        elif crecord.cancel_status == CancelCode.ERROR:
            LOGGER.error(
                "Failed to cancel jobs. (Code = %s)", crecord.return_code)
        else:
            LOGGER.error("Unknown Error (Code = %s)", crecord.return_code)

        return crecord.cancel_status

    def cleanup(self):
        """Clean up output produced by the ExecutionGraph."""
        if self._tmp_dir:
            shutil.rmtree(self._tmp_dir, ignore_errors=True)

description property writable

Return the description for the study in the ExecutionGraph instance.

Returns:

Type Description

A string of the description for the study.

name property writable

Return the name for the study in the ExecutionGraph instance.

Returns:

Type Description

A string of the name of the study.

status_subtree property

Cache the status ordering to improve scaling

__init__(submission_attempts=1, submission_throttle=0, use_tmp=False, dry_run=False)

Initialize a new instance of an ExecutionGraph.

Parameters:

Name Type Description Default
submission_attempts

Number of attempted submissions before marking a step as failed.

1
submission_throttle

Maximum number of scheduled in progress submissions.

0
use_tmp

A Boolean value that when set to 'True' designates that ExecutionGraph should use temporary files for output.

False
Source code in maestrowf/datastructures/core/executiongraph.py
def __init__(self, submission_attempts=1, submission_throttle=0,
             use_tmp=False, dry_run=False):
    """
    Initialize a new instance of an ExecutionGraph.

    :param submission_attempts: Number of attempted submissions before
        marking a step as failed.
    :param submission_throttle: Maximum number of scheduled in progress
    submissions.
    :param use_tmp: A Boolean value that when set to 'True' designates
    that ExecutionGraph should use temporary files for output.
    """
    super(ExecutionGraph, self).__init__()
    # Member variables for execution.
    self._adapter = None
    self._description = OrderedDict()

    # Generate tempdir (if specfied)
    if use_tmp:
        self._tmp_dir = tempfile.mkdtemp()
    else:
        self._tmp_dir = ""

    # Sets to track progress.
    self.completed_steps = set([SOURCE])
    self.in_progress = set()
    self.failed_steps = set()
    self.cancelled_steps = set()
    self.ready_steps = deque()
    self.is_canceled = False

    self._status_order = 'bfs'  # Set status order type
    self._status_subtree = None  # Cache bfs_subtree for status writing

    # Values for management of the DAG. Things like submission attempts,
    # throttling, etc. should be listed here.
    self._submission_attempts = submission_attempts
    self._submission_throttle = submission_throttle
    self.dry_run = dry_run

    # A map that tracks the dependencies of a step.
    # NOTE: I don't know how performant the Python dict structure is, but
    # we'll use it for now. I think this may want to be changed to an AVL
    # tree or something of that nature to guarantee worst case performance.
    self._dependencies = {}

    LOGGER.info(
        "\n------------------------------------------\n"
        "Submission attempts =       %d\n"
        "Submission throttle limit = %d\n"
        "Use temporary directory =   %s\n"
        "Tmp Dir = %s\n"
        "------------------------------------------",
        submission_attempts, submission_throttle, use_tmp, self._tmp_dir
    )

    # Error check that the submission values are valid.
    if self._submission_attempts < 1:
        _msg = "Submission attempts should always be greater than 0. " \
               "Received a value of {}.".format(self._submission_attempts)
        LOGGER.error(_msg)
        raise ValueError(_msg)

    if self._submission_throttle < 0:
        _msg = "Throttling should be 0 for unthrottled or a positive " \
               "integer for the number of allowed inflight jobs. " \
               "Received a value of {}.".format(self._submission_throttle)
        LOGGER.error(_msg)
        raise ValueError(_msg)

add_connection(parent, step)

Add a connection between two steps in the ExecutionGraph.

Parameters:

Name Type Description Default
parent

The parent step that is required to execute 'step'

required
step

The dependent step that relies on parent.

required
Source code in maestrowf/datastructures/core/executiongraph.py
def add_connection(self, parent, step):
    """
    Add a connection between two steps in the ExecutionGraph.

    :param parent: The parent step that is required to execute 'step'
    :param step: The dependent step that relies on parent.
    """
    self.add_edge(parent, step)
    self._dependencies[step].add(parent)

add_description(name, description, **kwargs)

Add a study description to the ExecutionGraph instance.

Parameters:

Name Type Description Default
name

Name of the study.

required
description

Description of the study.

required
Source code in maestrowf/datastructures/core/executiongraph.py
def add_description(self, name, description, **kwargs):
    """
    Add a study description to the ExecutionGraph instance.

    :param name: Name of the study.
    :param description: Description of the study.
    """
    self._description["name"] = name
    self._description["description"] = description
    self._description.update(kwargs)

add_step(name, step, workspace, restart_limit, params=None)

Add a StepRecord to the ExecutionGraph.

Parameters:

Name Type Description Default
name

Name of the step to be added.

required
step

StudyStep instance to be recorded.

required
workspace

Directory path for the step's working directory.

required
restart_limit

Upper limit on the number of restart attempts.

required
params

Iterable of tuples of step parameter names, values

None
Source code in maestrowf/datastructures/core/executiongraph.py
def add_step(self, name, step, workspace, restart_limit, params=None):
    """
    Add a StepRecord to the ExecutionGraph.

    :param name: Name of the step to be added.
    :param step: StudyStep instance to be recorded.
    :param workspace: Directory path for the step's working directory.
    :param restart_limit: Upper limit on the number of restart attempts.
    :param params: Iterable of tuples of step parameter names, values
    """
    data = {
                "step":          step,
                "state":         State.INITIALIZED,
                "workspace":     workspace,
                "restart_limit": restart_limit,
            }
    record = _StepRecord(**data)
    if params:
        record.add_params(params)

    self._dependencies[name] = set()
    super(ExecutionGraph, self).add_node(name, record)

cancel_study()

Cancel the study.

Source code in maestrowf/datastructures/core/executiongraph.py
def cancel_study(self):
    """Cancel the study."""
    joblist = []
    for step in self.in_progress:
        jobid = self.values[step].jobid[-1]
        joblist.append(jobid)

    # Grab the adapter from the ScriptAdapterFactory.
    adapter = ScriptAdapterFactory.get_adapter(self._adapter["type"])
    adapter = adapter(**self._adapter)

    # cancel our jobs
    crecord = adapter.cancel_jobs(joblist)
    self.is_canceled = True

    if crecord.cancel_status == CancelCode.OK:
        LOGGER.info("Successfully requested to cancel all jobs.")
    elif crecord.cancel_status == CancelCode.ERROR:
        LOGGER.error(
            "Failed to cancel jobs. (Code = %s)", crecord.return_code)
    else:
        LOGGER.error("Unknown Error (Code = %s)", crecord.return_code)

    return crecord.cancel_status

check_study_status()

Check the status of currently executing steps in the graph.

This method is used to check the status of all currently in progress steps in the ExecutionGraph. Each ExecutionGraph stores the adapter used to generate and execute its scripts.

Source code in maestrowf/datastructures/core/executiongraph.py
def check_study_status(self):
    """
    Check the status of currently executing steps in the graph.

    This method is used to check the status of all currently in progress
    steps in the ExecutionGraph. Each ExecutionGraph stores the adapter
    used to generate and execute its scripts.
    """
    # Set up the job list and the map to get back to step names.
    joblist = []
    jobmap = {}
    for step in self.in_progress:
        jobid = self.values[step].jobid[-1]
        joblist.append(jobid)
        jobmap[jobid] = step

    # Grab the adapter from the ScriptAdapterFactory.
    adapter = ScriptAdapterFactory.get_adapter(self._adapter["type"])
    adapter = adapter(**self._adapter)
    # Use the adapter to grab the job statuses.
    retcode, job_status = adapter.check_jobs(joblist)
    # Map the job identifiers back to step names.
    step_status = {jobmap[jobid]: status
                   for jobid, status in job_status.items()}

    # Based on return code, log something different.
    if retcode == JobStatusCode.OK:
        LOGGER.info("Jobs found for user '%s'.", getpass.getuser())
        return retcode, step_status
    elif retcode == JobStatusCode.NOJOBS:
        LOGGER.info("No jobs found.")
        return retcode, step_status
    else:
        msg = "Unknown Error (Code = {})".format(retcode)
        LOGGER.error(msg)
        return retcode, step_status

cleanup()

Clean up output produced by the ExecutionGraph.

Source code in maestrowf/datastructures/core/executiongraph.py
def cleanup(self):
    """Clean up output produced by the ExecutionGraph."""
    if self._tmp_dir:
        shutil.rmtree(self._tmp_dir, ignore_errors=True)

execute_ready_steps()

Execute any steps whose dependencies are satisfied.

The 'execute_ready_steps' method is the core of how the ExecutionGraph manages execution. This method does the following:

  • Checks the status of existing jobs that are executing and updates the state if changed.
  • Finds steps that are initialized and determines what can be run based on satisfied dependencies and executes steps whose dependencies are met.

Returns:

Type Description

True if the study has completed, False otherwise.

Source code in maestrowf/datastructures/core/executiongraph.py
def execute_ready_steps(self):
    """
    Execute any steps whose dependencies are satisfied.

    The 'execute_ready_steps' method is the core of how the ExecutionGraph
    manages execution. This method does the following:

    * Checks the status of existing jobs that are executing and updates
      the state if changed.
    * Finds steps that are initialized and determines what can be run
      based on satisfied dependencies and executes steps whose
      dependencies are met.

    :returns: True if the study has completed, False otherwise.
    """
    # TODO: We may want to move this to a singleton somewhere
    # so we can guarantee that all steps use the same adapter.
    adapter = ScriptAdapterFactory.get_adapter(self._adapter["type"])
    adapter = adapter(**self._adapter)

    if not self.dry_run:
        LOGGER.debug("Checking status check...")
        retcode, job_status = self.check_study_status()
    else:
        LOGGER.debug("DRYRUN: Skipping status check...")
        retcode = JobStatusCode.OK
        job_status = {}

    LOGGER.debug("Checked status (retcode %s)-- %s", retcode, job_status)

    # For now, if we can't check the status something is wrong.
    # Don't modify the DAG.
    if retcode == JobStatusCode.ERROR:
        msg = "Job status check failed -- Aborting."
        LOGGER.error(msg)
        raise RuntimeError(msg)
    elif retcode == JobStatusCode.OK:
        # For the status of each currently in progress job, check its
        # state.
        cleanup_steps = set()  # Steps that are in progress showing failed.
        cancel_steps = set()   # Steps that have dependencies to mark cancelled
        for name, status in job_status.items():
            LOGGER.debug("Checking job '%s' with status %s.", name, status)
            record = self.values[name]

            if status == State.FINISHED:
                # Mark the step complete and notate its end time.
                record.mark_end(State.FINISHED)
                LOGGER.info("Step '%s' marked as finished. Adding to "
                            "complete set.", name)
                self.completed_steps.add(name)
                self.in_progress.remove(name)

            elif status == State.RUNNING:
                # When detect that a step is running, mark it.
                LOGGER.info("Step '%s' found to be running.", record.name)
                record.mark_running()

            elif status == State.TIMEDOUT:
                # Execute the restart script.
                # If a restart script doesn't exist, re-run the command.
                # If we're under the restart limit, attempt a restart.
                if record.can_restart:
                    if record.mark_restart():
                        LOGGER.info(
                            "Step '%s' timed out. Restarting (%s of %s).",
                            name, record.restarts, record.restart_limit
                        )
                        self._execute_record(record, adapter, restart=True)
                    else:
                        LOGGER.info("'%s' has been restarted %s of %s "
                                    "times. Marking step and all "
                                    "descendents as failed.",
                                    name,
                                    record.restarts,
                                    record.restart_limit)
                        self.in_progress.remove(name)
                        cleanup_steps.update(self.bfs_subtree(name)[0])
                # Otherwise, we can't restart so mark the step timed out.
                else:
                    LOGGER.info("'%s' timed out, but cannot be restarted."
                                " Marked as TIMEDOUT.", name)
                    # Mark that the step ended due to TIMEOUT.
                    record.mark_end(State.TIMEDOUT)
                    # Remove from in progress since it no longer is.
                    self.in_progress.remove(name)
                    # Add the subtree to the clean up steps
                    cleanup_steps.update(self.bfs_subtree(name)[0])
                    # Remove the current step, clean up is used to mark
                    # steps definitively as failed.
                    cleanup_steps.remove(name)
                    # Add the current step to failed.
                    self.failed_steps.add(name)

            elif status == State.HWFAILURE:
                # TODO: Need to make sure that we do this a finite number
                # of times.
                # Resubmit the cmd.
                LOGGER.warning("Hardware failure detected. Attempting to "
                               "resubmit step '%s'.", name)
                # We can just let the logic below handle submission with
                # everything else.
                self.ready_steps.append(name)

            elif status == State.FAILED:
                LOGGER.warning(
                    "Job failure reported. Aborting %s -- flagging all "
                    "dependent jobs as failed.",
                    name
                )
                self.in_progress.remove(name)
                record.mark_end(State.FAILED)
                cleanup_steps.update(self.bfs_subtree(name)[0])

            elif status == State.UNKNOWN:
                record.mark_end(State.UNKNOWN)
                LOGGER.info(
                    "Step '%s' found in UNKNOWN state. Step was found "
                    "in '%s' state previously, marking as UNKNOWN. "
                    "Adding to failed steps.",
                    name, record.status)
                cleanup_steps.update(self.bfs_subtree(name)[0])
                self.in_progress.remove(name)

            elif status == State.CANCELLED:
                LOGGER.info("Step '%s' was cancelled.", name)
                self.in_progress.remove(name)
                record.mark_end(State.CANCELLED)
                cancel_steps.update(self.bfs_subtree(name)[0])

        # Let's handle all the failed steps in one go.
        for node in cleanup_steps:
            self.failed_steps.add(node)
            self.values[node].mark_end(State.FAILED)

        # Handle dependent steps that need cancelling
        for node in cancel_steps:
            self.cancelled_steps.add(node)
            self.values[node].mark_end(State.CANCELLED)

    # Now that we've checked the statuses of existing jobs we need to make
    # sure dependencies haven't been met.
    for key in self.values.keys():
        # We MUST dereference from the key. If we use values.items(), a
        # generator gets produced which will give us a COPY of a record and
        # not the actual record.
        record = self.values[key]

        # A completed step by definition has had its dependencies met.
        # Skip it.
        if key in self.completed_steps:
            LOGGER.debug("'%s' in completed set, skipping.", key)
            continue

        LOGGER.debug("Checking %s -- %s", key, record.jobid)
        # If the record is only INITIALIZED, we have encountered a step
        # that needs consideration.
        if record.status == State.INITIALIZED:
            LOGGER.debug("'%s' found to be initialized. Checking "
                         "dependencies. ", key)

            LOGGER.debug(
                "Unfulfilled dependencies: %s",
                self._dependencies[key])

            s_completed = list(filter(
                lambda x: x in self.completed_steps,
                self._dependencies[key]))
            self._dependencies[key] = \
                self._dependencies[key] - set(s_completed)
            LOGGER.debug(
                "Completed dependencies: %s\n"
                "Remaining dependencies: %s",
                s_completed, self._dependencies[key])

            # If the gating dependencies set is empty, we can execute.
            if not self._dependencies[key]:
                if key not in self.ready_steps:
                    LOGGER.debug("All dependencies completed. Staging.")
                    self.ready_steps.append(key)
                else:
                    LOGGER.debug("Already staged. Passing.")
                    continue

    # We now have a collection of ready steps. Execute.
    # If we don't have a submission limit, go ahead and submit all.
    if self._submission_throttle == 0:
        LOGGER.info("Launching all ready steps...")
        _available = len(self.ready_steps)
    # Else, we have a limit -- adhere to it.
    else:
        # Compute the number of available slots we have for execution.
        _available = self._submission_throttle - len(self.in_progress)
        # Available slots should never be negative, but on the off chance
        # we are in a slot deficit, then we will just say none are free.
        _available = max(0, _available)
        # Now, we need to take the min of the length of the queue and the
        # computed number of slots. We could have free slots, but have less
        # in the queue.
        _available = min(_available, len(self.ready_steps))
        LOGGER.info("Found %d available slots...", _available)

    for i in range(0, _available):
        # Pop the record and execute using the helper method.
        _record = self.values[self.ready_steps.popleft()]

        # If we get to this point and we've cancelled, cancel the record.
        if self.is_canceled:
            LOGGER.info("Cancelling '%s' -- continuing.", _record.name)
            _record.mark_end(State.CANCELLED)
            self.cancelled_steps.add(_record.name)
            continue

        LOGGER.debug("Launching job %d -- %s", i, _record.name)
        self._execute_record(_record, adapter)

    # check the status of the study upon finishing this round of execution
    completion_status = self._check_study_completion()
    return completion_status

generate_scripts()

Generate the scripts for all steps in the ExecutionGraph.

The generate_scripts method scans the ExecutionGraph instance and uses the stored adapter to write executable scripts for either local or scheduled execution. If a restart command is specified, a restart script will be generated for that record.

Source code in maestrowf/datastructures/core/executiongraph.py
def generate_scripts(self):
    """
    Generate the scripts for all steps in the ExecutionGraph.

    The generate_scripts method scans the ExecutionGraph instance and uses
    the stored adapter to write executable scripts for either local or
    scheduled execution. If a restart command is specified, a restart
    script will be generated for that record.
    """
    # An adapter must be specified
    if not self._adapter:
        msg = "Adapter not found. Specify a ScriptAdapter using " \
              "set_adapter."
        LOGGER.error(msg)
        raise ValueError(msg)

    # Set up the adapter.
    LOGGER.info("Generating scripts...")
    adapter = ScriptAdapterFactory.get_adapter(self._adapter["type"])
    adapter = adapter(**self._adapter)

    self._check_tmp_dir()
    for key, record in self.values.items():
        if key == SOURCE:
            continue

        # Record generates its own script.
        record.setup_workspace()
        record.generate_script(adapter, self._tmp_dir)

log_description()

Log the description of the ExecutionGraph.

Source code in maestrowf/datastructures/core/executiongraph.py
def log_description(self):
    """Log the description of the ExecutionGraph."""
    desc = ["{}: {}".format(key, value)
            for key, value in self._description.items()]
    desc = "\n".join(desc)
    LOGGER.info(
        "\n==================================================\n"
        "%s\n"
        "==================================================\n",
        desc
    )

set_adapter(adapter)

Set the adapter used to interface for scheduling tasks.

Parameters:

Name Type Description Default
adapter

Adapter name to be used when launching the graph.

required
Source code in maestrowf/datastructures/core/executiongraph.py
def set_adapter(self, adapter):
    """
    Set the adapter used to interface for scheduling tasks.

    :param adapter: Adapter name to be used when launching the graph.
    """
    if not adapter:
        # If we have no adapter specified, assume sequential execution.
        self._adapter = None
        return

    if not isinstance(adapter, dict):
        msg = "Adapter settings must be contained in a dictionary."
        LOGGER.error(msg)
        raise TypeError(msg)

    # Check to see that the adapter type is something the
    if adapter["type"] not in ScriptAdapterFactory.get_valid_adapters():
        msg = "'{}' adapter must be specfied in ScriptAdapterFactory." \
              .format(adapter)
        LOGGER.error(msg)
        raise TypeError(msg)

    self._adapter = adapter

write_status(path)

Write the status of the DAG to a CSV file.

Source code in maestrowf/datastructures/core/executiongraph.py
def write_status(self, path):
    """Write the status of the DAG to a CSV file."""
    header = "Step Name,Job ID,Workspace,State,Run Time,Elapsed Time," \
             "Start Time,Submit Time,End Time,Number Restarts,Params"
    status = [header]

    for key in self.status_subtree:
        value = self.values[key]

        jobid_str = "--"
        if value.jobid:
            jobid_str = str(value.jobid[-1])

        # Include step root in workspace when parameterized
        if list(value.params.items()):
            ws = os.path.join(
                * os.path.normpath(
                    value.workspace.value).split(os.sep)[-2:]
            )
        else:
            ws = os.path.split(value.workspace.value)[1]

        _ = [
                value.name, jobid_str,
                ws,
                str(value.status.name), value.run_time, value.elapsed_time,
                value.time_start, value.time_submitted, value.time_end,
                str(value.restarts),
                ";".join(["{}:{}".format(param, value)
                          for param, value in value.params.items()])
            ]
        _ = ",".join(_)
        status.append(_)

    stat_path = os.path.join(path, "status.csv")
    lock_path = os.path.join(path, ".status.lock")
    lock = FileLock(lock_path)
    try:
        with lock.acquire(timeout=10):
            with open(stat_path, "w+") as stat_file:
                stat_file.write("\n".join(status))
    except Timeout:
        pass

ParameterGenerator

Class for containing parameters and generating combinations.

The goal of this class is to provide one centralized location for managing and storing parameters. This implementation of the ParameterGenerator, currently, is very basic. It takes lists of parameters and uses those to construct combinations, meaning that if you were to view this as an Excel table, you would have a row for each valid combination you wanted to study.

The other goal is to make it so that by having the ParameterGenerator manage parameters, functionality can be added without affecting how the end user interacts with this class. The ParameterGenerator has an Iterator defined and will generate each combination one by one. The end user should NEVER SEE AN INVALID COMBINATION. Because this class generates the combinations as specified by the parameters added (eventually with types or enforced inheritance), and eventually constraints, it opens up being able to quietly change how this class generates its combinations.

Easily convert studies to other types of studies. Because the API doesn't change from its nice Pythonic style, you can in theory swap out a ParameterGenerator that performs completely differently. All of a sudden, you can get the following for simply deriving from this class:

  • Uncertainty Quantification (UQ): Add the ability to statistically sample parameters behind the scenes. Let the ParameterGenerator constraint solve behind the scenes and return the Combination objects it was going to return in the first place. If you can't find a valid sampling, just return nothing and the study won't run.
  • Boundary and constraint testing: Like UQ above, hide the solving from the user. Simply add parameters to be constraint solved on behind the API and all the user sees is combinations on the frontend.

Ideally, all parameter generation schemes should boil down as follows:

  1. Derive from this class, add constraint solving.
  2. Construct a study how you would otherwise do so, just use the new ParameterGenerator and add parameters.
  3. Setup, stage, and execute your study.
  4. Profit.
Source code in maestrowf/datastructures/core/parameters.py
class ParameterGenerator:
    """
    Class for containing parameters and generating combinations.

    The goal of this class is to provide one centralized location for managing
    and storing parameters. This implementation of the ParameterGenerator,
    currently, is very basic. It takes lists of parameters and uses those to
    construct combinations, meaning that if you were to view this as an Excel
    table, you would have a row for each valid combination you wanted to study.

    The other goal is to make it so that by having the ParameterGenerator
    manage parameters, functionality can be added without affecting how the
    end user interacts with this class. The ParameterGenerator has an Iterator
    defined and will generate each combination one by one. The end user should
    NEVER SEE AN INVALID COMBINATION. Because this class generates the
    combinations as specified by the parameters added (eventually with types
    or enforced inheritance), and eventually constraints, it opens up being
    able to quietly change how this class generates its combinations.

    Easily convert studies to other types of studies. Because the API doesn't
    change from its nice Pythonic style, you can in theory swap out a
    ParameterGenerator that performs completely differently. All of a sudden,
    you can get the following for simply deriving from this class:

    * Uncertainty Quantification (UQ): Add the ability to statistically
      sample parameters behind the scenes. Let the ParameterGenerator
      constraint solve behind the scenes and return the Combination
      objects it was going to return in the first place. If you can't
      find a valid sampling, just return nothing and the study won't run.
    * Boundary and constraint testing: Like UQ above, hide the solving
      from the user. Simply add parameters to be constraint solved on
      behind the API and all the user sees is combinations on the frontend.

    Ideally, all parameter generation schemes should boil down as follows:

    1. Derive from this class, add constraint solving.
    2. Construct a study how you would otherwise do so, just use
       the new ParameterGenerator and add parameters.
    3. Setup, stage, and execute your study.
    4. Profit.
    """

    def __init__(self, token="$", ltoken="%%"):
        """
        Initialize an empty ParameterGenerator object.

        The ParameterGenerator is instantiated with two token values, one for
        parameters and one for labels. The 'token' parameter represents the
        character(s) expected in front of parameterized strings. For example,
        if 'token' is left at its default of '$' and we have a parameter named
        'COMP1', then the instance of the ParameterGenerator will replace the
        value '$(COMP1)' in any item passed to the apply method. The 'ltoken'
        parameter functions in much the same way, except that instead of
        substituting for a parameter, this character(s) is what is found in a
        parameter label. The label for the parameter 'COMP1' is specified as
        '$(COMP.label)' where the label may have a value of 'COMP1.%%' (where
        %% is the default value of ltoken). For any combination, '%%' will be
        replaced by the value of the parameter 'COMP1' for that given instance
        when the label is specified in a item.

        :param token: Leading token that denotes a parameter (Default: '$').
        :param ltoken: Token that represents where to place a value in a label
            (Default: '%%').
        """
        self.parameters = OrderedDict()
        self.labels = {}
        self.names = {}
        self.label_token = ltoken
        self.token = token

        self.length = 0

    def add_parameter(self, key, values, label=None, name=None):
        """
        Add a parameter to the ParameterGenerator.

        Currently, all parameters added to a ParameterGenerator instance must
        have a list of values that are the same length. Future improvements
        will add the ability to specify either types of parameters or provide
        different ParameterGenerators derivations that have unique behavior.

        :param key: Parameter key to find for replacement.
        :param values: List of values the parameter can take.
        :param label: Label string for labeling the parameter.
        :param name: Custom name for identifying parameter.
        """
        if key in self.parameters:
            logger.warning("'%s' already in parameter set. Overriding.", key)

        self.parameters[key] = values
        if self.length == 0:
            self.length = len(values)

        elif len(values) != self.length:
            error = "Length of values list must be the same size as " \
                    "the other parameters that exist in the " \
                    "generators. Length of '{}' is {}. Aborting." \
                    .format(name, len(values))
            logger.exception(error)
            raise ValueError(error)

        if label:
            self.labels[key] = label
        else:
            self.labels[key] = "{}.{}".format(key, self.label_token)

        if name:
            self.names[key] = name
        else:
            self.names[key] = key

    def __iter__(self):
        """
        Return the iterator for the ParameterGenerator.

        :returns: Iterator for walking parameter combinations.
        """
        return self.get_combinations()

    def __bool__(self):
        """
        Override for the __bool__ operator.

        :returns: True if the ParameterGenerator instance has values, False
            otherwise.
        """
        return bool(self.parameters)

    __nonzero__ = __bool__

    def get_combinations(self):
        """
        Generate all combinations of parameters.

        :returns: A generator with all combinations of parameters.
        """
        for i in range(0, self.length):
            combo = Combination()
            for key in self.parameters.keys():
                pvalue = self.parameters[key][i]
                if isinstance(self.labels[key], list):
                    tlabel = self.labels[key][i]
                else:
                    tlabel = self.labels[key].replace(self.label_token,
                                                      str(pvalue))
                name = self.names[key]
                combo.add(key, name, pvalue, tlabel)
            yield combo

    def _get_used_parameters(self, item, params):
        """
        Find the parameters used by an item in a StudyStep.

        :param item: The item to search for parameters.
        :param params: The current set of found parameters.
        """
        if not item:
            return
        elif isinstance(item, str):
            for key in self.parameters.keys():
                _ = r"\{}\({}\.*\w*\)".format(self.token, key)
                matches = re.findall(_, item)
                if matches:
                    params.add(key)
        elif isinstance(item, list):
            for each in item:
                self._get_used_parameters(each, params)
        elif isinstance(item, dict):
            for each in item.values():
                self._get_used_parameters(each, params)
        else:
            msg = \
                "Encountered an object of type '{}'. Passing."\
                .format(type(item))
            logger.debug(msg)
            return

    def get_used_parameters(self, step):
        """
        Return the parameters used by a StudyStep.

        :param step: A StudyStep instance to be checked.
        :returns: A set of the parameter names used within the step parameter.
        """
        params = set()
        self._get_used_parameters(step.__dict__, params)
        return params

    def get_metadata(self):
        """
        Produce metadata for the parameters in a generator instance.

        :returns: A dictionary containing metadata about the instance.
        """
        meta = {}
        for combo in self.get_combinations():
            meta[str(combo)] = {}
            meta[str(combo)]["params"] = combo._params
            meta[str(combo)]["labels"] = combo._labels

        return meta

__bool__()

Override for the bool operator.

Returns:

Type Description

True if the ParameterGenerator instance has values, False otherwise.

Source code in maestrowf/datastructures/core/parameters.py
def __bool__(self):
    """
    Override for the __bool__ operator.

    :returns: True if the ParameterGenerator instance has values, False
        otherwise.
    """
    return bool(self.parameters)

__init__(token='$', ltoken='%%')

Initialize an empty ParameterGenerator object.

The ParameterGenerator is instantiated with two token values, one for parameters and one for labels. The 'token' parameter represents the character(s) expected in front of parameterized strings. For example, if 'token' is left at its default of '$' and we have a parameter named 'COMP1', then the instance of the ParameterGenerator will replace the value '$(COMP1)' in any item passed to the apply method. The 'ltoken' parameter functions in much the same way, except that instead of substituting for a parameter, this character(s) is what is found in a parameter label. The label for the parameter 'COMP1' is specified as '$(COMP.label)' where the label may have a value of 'COMP1.%%' (where %% is the default value of ltoken). For any combination, '%%' will be replaced by the value of the parameter 'COMP1' for that given instance when the label is specified in a item.

Parameters:

Name Type Description Default
token

Leading token that denotes a parameter (Default: '$').

'$'
ltoken

Token that represents where to place a value in a label (Default: '%%').

'%%'
Source code in maestrowf/datastructures/core/parameters.py
def __init__(self, token="$", ltoken="%%"):
    """
    Initialize an empty ParameterGenerator object.

    The ParameterGenerator is instantiated with two token values, one for
    parameters and one for labels. The 'token' parameter represents the
    character(s) expected in front of parameterized strings. For example,
    if 'token' is left at its default of '$' and we have a parameter named
    'COMP1', then the instance of the ParameterGenerator will replace the
    value '$(COMP1)' in any item passed to the apply method. The 'ltoken'
    parameter functions in much the same way, except that instead of
    substituting for a parameter, this character(s) is what is found in a
    parameter label. The label for the parameter 'COMP1' is specified as
    '$(COMP.label)' where the label may have a value of 'COMP1.%%' (where
    %% is the default value of ltoken). For any combination, '%%' will be
    replaced by the value of the parameter 'COMP1' for that given instance
    when the label is specified in a item.

    :param token: Leading token that denotes a parameter (Default: '$').
    :param ltoken: Token that represents where to place a value in a label
        (Default: '%%').
    """
    self.parameters = OrderedDict()
    self.labels = {}
    self.names = {}
    self.label_token = ltoken
    self.token = token

    self.length = 0

__iter__()

Return the iterator for the ParameterGenerator.

Returns:

Type Description

Iterator for walking parameter combinations.

Source code in maestrowf/datastructures/core/parameters.py
def __iter__(self):
    """
    Return the iterator for the ParameterGenerator.

    :returns: Iterator for walking parameter combinations.
    """
    return self.get_combinations()

add_parameter(key, values, label=None, name=None)

Add a parameter to the ParameterGenerator.

Currently, all parameters added to a ParameterGenerator instance must have a list of values that are the same length. Future improvements will add the ability to specify either types of parameters or provide different ParameterGenerators derivations that have unique behavior.

Parameters:

Name Type Description Default
key

Parameter key to find for replacement.

required
values

List of values the parameter can take.

required
label

Label string for labeling the parameter.

None
name

Custom name for identifying parameter.

None
Source code in maestrowf/datastructures/core/parameters.py
def add_parameter(self, key, values, label=None, name=None):
    """
    Add a parameter to the ParameterGenerator.

    Currently, all parameters added to a ParameterGenerator instance must
    have a list of values that are the same length. Future improvements
    will add the ability to specify either types of parameters or provide
    different ParameterGenerators derivations that have unique behavior.

    :param key: Parameter key to find for replacement.
    :param values: List of values the parameter can take.
    :param label: Label string for labeling the parameter.
    :param name: Custom name for identifying parameter.
    """
    if key in self.parameters:
        logger.warning("'%s' already in parameter set. Overriding.", key)

    self.parameters[key] = values
    if self.length == 0:
        self.length = len(values)

    elif len(values) != self.length:
        error = "Length of values list must be the same size as " \
                "the other parameters that exist in the " \
                "generators. Length of '{}' is {}. Aborting." \
                .format(name, len(values))
        logger.exception(error)
        raise ValueError(error)

    if label:
        self.labels[key] = label
    else:
        self.labels[key] = "{}.{}".format(key, self.label_token)

    if name:
        self.names[key] = name
    else:
        self.names[key] = key

get_combinations()

Generate all combinations of parameters.

Returns:

Type Description

A generator with all combinations of parameters.

Source code in maestrowf/datastructures/core/parameters.py
def get_combinations(self):
    """
    Generate all combinations of parameters.

    :returns: A generator with all combinations of parameters.
    """
    for i in range(0, self.length):
        combo = Combination()
        for key in self.parameters.keys():
            pvalue = self.parameters[key][i]
            if isinstance(self.labels[key], list):
                tlabel = self.labels[key][i]
            else:
                tlabel = self.labels[key].replace(self.label_token,
                                                  str(pvalue))
            name = self.names[key]
            combo.add(key, name, pvalue, tlabel)
        yield combo

get_metadata()

Produce metadata for the parameters in a generator instance.

Returns:

Type Description

A dictionary containing metadata about the instance.

Source code in maestrowf/datastructures/core/parameters.py
def get_metadata(self):
    """
    Produce metadata for the parameters in a generator instance.

    :returns: A dictionary containing metadata about the instance.
    """
    meta = {}
    for combo in self.get_combinations():
        meta[str(combo)] = {}
        meta[str(combo)]["params"] = combo._params
        meta[str(combo)]["labels"] = combo._labels

    return meta

get_used_parameters(step)

Return the parameters used by a StudyStep.

Parameters:

Name Type Description Default
step

A StudyStep instance to be checked.

required

Returns:

Type Description

A set of the parameter names used within the step parameter.

Source code in maestrowf/datastructures/core/parameters.py
def get_used_parameters(self, step):
    """
    Return the parameters used by a StudyStep.

    :param step: A StudyStep instance to be checked.
    :returns: A set of the parameter names used within the step parameter.
    """
    params = set()
    self._get_used_parameters(step.__dict__, params)
    return params

Study

Bases: DAG, PickleInterface

Collection of high level objects to perform study construction.

The Study class is part of the meat and potatoes of this whole package. A Study object is where the intersection of the major moving parts are collected. These moving parts include:

  • ParameterGenerator for getting combinations of user parameters
  • StudyEnvironment for managing and applying the environment to studies
  • Study flow, which is a DAG of the abstract workflow

The class is responsible for a number of the major key steps in study setup as well. Those responsibilities include (but are not limited to):

  • Setting up the workspace where a simulation campaign will be run.
  • Applying the StudyEnvionment to the abstract flow DAG:

    • Creating the global workspace for a study.
    • Setting up the parameterized workspaces for each combination.
    • Acquiring dependencies as specified in the StudyEnvironment.
  • Intelligently constructing the expanded DAG to be able to:

    • Recognize when a step executes in a parameterized workspace
    • Recognize when a step executes in the global workspace
  • Expanding the abstract flow to the full set of specified parameters.

Future functionality that makes sense to add here:

  • Metadata collection. If we're setting things up here, collect the general information. We might even want to venture to say that a set of directives may be useful so that they could be placed into Dependency classes as hooks for dumping that data automatically.
  • A way of packaging an instance of the class up into something that is easy to store in the ExecutionDAG class so that an API can be designed in whatever class ends up managing all of this to have machine learning applications pipe messages to spin up new studies using the same environment.
Source code in maestrowf/datastructures/core/study.py
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
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
501
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
class Study(DAG, PickleInterface):
    """
    Collection of high level objects to perform study construction.

    The Study class is part of the meat and potatoes of this whole package. A
    Study object is where the intersection of the major moving parts are
    collected. These moving parts include:

    * ParameterGenerator for getting combinations of user parameters
    * StudyEnvironment for managing and applying the environment to studies
    * Study flow, which is a DAG of the abstract workflow

    The class is responsible for a number of the major key steps in study setup
    as well. Those responsibilities include (but are not limited to):

    * Setting up the workspace where a simulation campaign will be run.
    * Applying the StudyEnvionment to the abstract flow DAG:
        * Creating the global workspace for a study.
        * Setting up the parameterized workspaces for each combination.
        * Acquiring dependencies as specified in the StudyEnvironment.

    * Intelligently constructing the expanded DAG to be able to:
        * Recognize when a step executes in a parameterized workspace
        * Recognize when a step executes in the global workspace

    * Expanding the abstract flow to the full set of specified parameters.

    Future functionality that makes sense to add here:

    * Metadata collection. If we're setting things up here, collect the
      general information. We might even want to venture to say that a set
      of directives may be useful so that they could be placed into
      Dependency classes as hooks for dumping that data automatically.
    * A way of packaging an instance of the class up into something that is
      easy to store in the ExecutionDAG class so that an API can be
      designed in whatever class ends up managing all of this to have
      machine learning applications pipe messages to spin up new studies
      using the same environment.
    """

    def __init__(self, name, description,
                 studyenv=None, parameters=None, steps=None, out_path="./"):
        """
        Study object used to represent the full workflow of a study.

        Derived from the DAG data structure. Contains everything that a study
        requires to be expanded with the appropriate substitutions and with
        parameters inserted. This data structure should be the instance the
        future daemon loads in to track progress on a workflow.

        :param name: String representing the name of the Study.
        :param description: A text description of what the study does.
        :param steps: A list of StudySteps in proper workflow order.
        :param studyenv: A populated StudyEnvironment instance.
        :param parameters: A populated Parameters instance.
        :param outpath: The path where the output of the study is written.
        """
        # The basic study information
        self.name = name
        self.description = description

        # Initialized the DAG so we have those structures to be used.
        super(Study, self).__init__()

        # We want deep copies so that properties don't change out from under
        # the Sudy data structure.
        self.environment = studyenv
        self.parameters = parameters
        self._out_path = out_path
        self._meta_path = os.path.join(out_path, "meta")

        LOGGER.debug("OUTPUT_PATH = %s", out_path)
        # Flag the study as not having been set up and add the source node.
        self._issetup = False
        self.is_configured = False
        self.add_node(SOURCE, None)

        # Settings for handling restarts and submission attempts.
        self._restart_limit = 0
        self._submission_attempts = 0
        self._use_tmp = False
        self._dry_run = False

        # Management structures
        # The workspace used by each step.
        self.workspaces = {SOURCE: self._out_path}
        # Parameter independent dependencies by step.
        self.hub_depends = {SOURCE: set()}
        # Other dependencies per step.
        self.depends = {SOURCE: set()}
        # Parameters that each step depends on.
        self.used_params = {SOURCE: set()}
        # Combinations seen per step.
        self.step_combos = {SOURCE: set()}

        # If the user specified a flow in the form of steps, copy those into
        # into the Study object.
        if steps:
            for step in steps:
                # Deep copy because it prevents modifications after the fact.
                self.add_step(step)

    @property
    def output_path(self):
        """
        Property method for the OUTPUT_PATH specified for the study.

        :returns: The string path stored in the OUTPUT_PATH variable.
        """
        return self._out_path

    def store_metadata(self):
        """Store metadata related to the study."""
        # Create the metadata directory.
        create_parentdir(self._meta_path)

        # Store the environment object in order to preserve it.
        path = os.path.join(self._meta_path, "study")
        create_parentdir(path)
        path = os.path.join(path, "env.pkl")
        with open(path, 'wb') as pkl:
            pickle.dump(self, pkl)

        # Construct other metadata related to study construction.
        _workspaces = {}
        for key, value in self.workspaces.items():
            if key == "_source":
                _workspaces[key] = value
            elif key in self.step_combos:
                _workspaces[key] = os.path.split(value)[-1]
            else:
                _workspaces[key] = \
                    os.path.sep.join(value.rsplit(os.path.sep)[-2:])

        # Construct relative paths for the combinations and nest them in the
        # same way as the step combinations dictionary.
        _step_combos = {}
        for key, value in self.step_combos.items():
            if key == SOURCE:
                _step_combos[key] = self.workspaces[key]
            elif not self.used_params[key]:
                _ws = self.workspaces[key]
                _step_combos[key] = {key: os.path.split(_ws)[-1]}
            else:
                _step_combos[key] = {}
                for combo in value:
                    _ws = self.workspaces[combo]
                    _step_combos[key][combo] = \
                        os.path.sep.join(_ws.rsplit(os.path.sep)[-2:])

        metadata = {
            "dependencies": self.depends,
            "hub_dependencies": self.hub_depends,
            "workspaces": _workspaces,
            "used_parameters": self.used_params,
            "step_combinations": _step_combos,
        }
        # Write out the study construction metadata.
        path = os.path.join(self._meta_path, "metadata.yaml")
        with open(path, "wb") as metafile:
            metafile.write(yaml.dump(metadata).encode("utf-8"))

        # Write out parameter metadata.
        metadata = self.parameters.get_metadata()
        path = os.path.join(self._meta_path, "parameters.yaml")
        with open(path, "wb") as metafile:
            metafile.write(yaml.dump(metadata).encode("utf-8"))

        # Write out environment metadata
        path = os.path.join(self._meta_path, "environment.yaml")
        with open(path, "wb") as metafile:
            metafile.write(yaml.dump(os.environ.copy()).encode("utf-8"))

    def load_metadata(self):
        """Load metadata for the study."""
        if not os.path.exists(self._meta_path):
            return

        path = os.path.join(self._meta_path, "study", "env.pkl")
        with open(path, 'rb') as pkl:
            env = pickle.load(pkl)

        if not isinstance(env, type(self)):
            msg = "Object loaded from {path} is of type {type}. Expected an" \
                  " object of type '{cls}.'".format(path=path, type=type(env),
                                                    cls=type(self))
            LOGGER.error(msg)
            raise TypeError(msg)

        metapath = os.path.join(self._meta_path, "metadata.yaml")
        with open(metapath, "rb") as metafile:
            metadata = yaml.load(metafile)

        self.depends = metadata["dependencies"]
        self.hub_depends = metadata["hub_dependencies"]
        self.workspaces = metadata["workspaces"]
        self.used_params = metadata["used_parameters"]
        self.step_combos = metadata["step_combinations"]

    def add_step(self, step):
        """
        Add a step to a study.

        For this helper to be most effective, it recommended to apply steps in
        the order that they will be encountered. The method attempts to be
        intelligent and make the intended edge based on the 'depends' entry in
        a step. When adding steps out of order it's recommended to just use the
        base class DAG functionality and manually make connections.

        :param step: A StudyStep instance to be added to the Study instance.
        """
        # Add the node to the DAG.
        self.add_node(step.real_name, step)
        LOGGER.info(
            "Adding step '%s' to study '%s'...", step.name, self.name)
        # Apply the environment to the incoming step.
        step.__dict__ = \
            apply_function(step.__dict__, self.environment.apply_environment)

        # If the step depends on a prior step, create an edge.
        if "depends" in step.run and step.run["depends"]:
            for dependency in step.run["depends"]:
                LOGGER.info("{0} is dependent on {1}. Creating edge ("
                            "{1}, {0})...".format(step.real_name, dependency))
                if "*" not in dependency:
                    self.add_edge(dependency, step.real_name)
                else:
                    self.add_edge(
                        re.sub(ALL_COMBOS, "", dependency),
                        step.real_name
                    )
        else:
            # Otherwise, if no other dependency, just execute the step.
            self.add_edge(SOURCE, step.real_name)

    def walk_study(self, src=SOURCE):
        """
        Walk the study and create a spanning tree.

        :param src: Source node to start the walk.
        :returns: A generator of (parent, node name, node value) tuples.
        """
        # Get a DFS spanning tree of the study. This method should always
        # return a complete tree because _source is flagged as a dependency
        # if a step is added without one.
        # TODO: This method should be fixed to return both parents and nodes.
        path, parents = self.dfs_subtree(src)
        for node in path:
            yield parents[node], node, self.values[node]

    def setup_workspace(self):
        """Set up the study's main workspace directory."""
        try:
            LOGGER.debug("Setting up study workspace in '%s'", self._out_path)
            create_parentdir(self._out_path)
        except Exception as e:
            LOGGER.error(e.args)
            return False

    def setup_environment(self):
        """Set up the environment by acquiring outside dependencies."""
        # Set up the environment if it hasn't been already.
        if not self.environment.is_set_up:
            LOGGER.debug("Environment is setting up.")
            self.environment.acquire_environment()

    def configure_study(self, submission_attempts=1, restart_limit=1,
                        throttle=0, use_tmp=False, hash_ws=False,
                        dry_run=False):
        """
        Perform initial configuration of a study. \

        The method is used for going through and actually acquiring each \
        dependency, substituting variables, sources and labels. \

        :param submission_attempts: Number of attempted submissions before \
        marking a step as failed. \
        :param restart_limit: Upper limit on the number of times a step with \
        a restart command can be resubmitted before it is considered failed. \
        :param throttle: The maximum number of in-progress jobs allowed. [0 \
        denotes no cap].\
        :param use_tmp: Boolean value specifying if the generated \
        ExecutionGraph dumps its information into a temporary directory. \
        :param dry_run: Boolean value that toggles dry run to just generate \
        study workspaces and scripts without execution or status checking. \
        :returns: True if the Study is successfully setup, False otherwise. \
        """

        self._submission_attempts = submission_attempts
        self._restart_limit = restart_limit
        self._submission_throttle = throttle
        self._use_tmp = use_tmp
        self._hash_ws = hash_ws
        self._dry_run = dry_run

        LOGGER.info(
            "\n------------------------------------------\n"
            "Submission attempts =       %d\n"
            "Submission restart limit =  %d\n"
            "Submission throttle limit = %d\n"
            "Use temporary directory =   %s\n"
            "Hash workspaces =           %s\n"
            "Dry run enabled =           %s\n"
            "Output path =               %s\n"
            "------------------------------------------",
            submission_attempts, restart_limit, throttle,
            use_tmp, hash_ws, dry_run, self._out_path
        )

        self.is_configured = True

    def _stage(self, dag):
        """
        Set up the ExecutionGraph of a parameterized study.

        :param throttle: Maximum number of in progress jobs allowed.
        :returns: The path to the study's global workspace and an expanded
            ExecutionGraph based on the parameters and parameterized workflow
            steps.
        """
        # Items to store that should be reset.
        LOGGER.info(
            "\n==================================================\n"
            "Constructing parameter study '%s'\n"
            "==================================================\n",
            self.name
        )

        # Topological sorted list of steps.
        t_sorted = self.topological_sort()

        # For each step, we need to assess what type of step it is.
        # So far we've seen five types of steps:
        # 1. Linear - The step uses no parameters, so we can add it as it is.
        # 2. Parameterized - The step uses or is dependent on steps that use
        # parameters.
        # 3. Parameter Independent - A step who only uses hub dependencies; or
        # phrased more concisely, is not directly dependent on the parameters
        # of a parent step but simply makes use of all of its combinations.
        # 4. Parameter Dependent - A step that may or may not be parameterized
        # itself, but whose combinations also depend on the combinations of its
        # parents.
        # 5. Parameterized and Parameter Independent - A step that is a combo
        # of #2 and #3 which requires the step to be expanded based on the
        # used parameters of the step, and then adding all parameterized
        # combinations of funneled steps.
        for step in t_sorted:
            LOGGER.info(
                "\n==================================================\n"
                "Processing step '%s'\n"
                "==================================================\n",
                step
            )
            # If we encounter SOURCE, just add it and continue.
            if step == SOURCE:
                LOGGER.info("Encountered '%s'. Adding and continuing.", SOURCE)
                dag.add_node(SOURCE, None)
                continue

            # We're dealing with an actual step. So we have to:
            # Update our management structures.
            node = self.values[step]
            self.hub_depends[step] = set()
            self.depends[step] = set()
            self.step_combos[step] = set()

            s_params = self.parameters.get_used_parameters(node)
            p_params = set()    # Used parameters excluding the current step.
            # Iterate through dependencies to update the p_params
            LOGGER.debug("\n*** Processing dependencies ***")
            for parent in node.run["depends"]:
                # If we have a dependency that is parameter independent, add
                # it to the hub dependency set.
                if "*" in parent:
                    LOGGER.debug("Found funnel dependency -- %s", parent)
                    self.hub_depends[step].add(re.sub(ALL_COMBOS, "", parent))
                else:
                    LOGGER.debug("Found dependency -- %s", parent)
                    # Otherwise, just note the parameters used by the step.
                    self.depends[step].add(parent)
                    p_params |= self.used_params[parent]

            # Search for workspace matches. These affect the expansion of a
            # node because they may use parameters. These are likely to cause
            # a node to fall into the 'Parameter Dependent' case.
            used_spaces = re.findall(
                WSREGEX, "{} {}".format(node.run["cmd"], node.run["restart"]))
            for ws in used_spaces:
                if ws not in self.used_params:
                    msg = "Workspace for '{}' is being used before it would" \
                          " be generated.".format(ws)
                    LOGGER.error(msg)
                    raise Exception(msg)

                # We have the case that if we're using a workspace of a step
                # that is a parameter independent dependency, we can skip it.
                # The parameters don't affect the combinations.
                if ws in self.hub_depends[step]:
                    LOGGER.info(
                        "'%s' parameter independent association found. "
                        "Skipping.", ws)
                    continue

                LOGGER.debug(
                    "Found workspace '%s' using parameters %s",
                    ws, self.used_params[ws])
                p_params |= self.used_params[ws]

            # Total parameters used for this step are the union of each parent
            # and the union of the parameters used by this step.
            self.used_params[step] = p_params | s_params

            # Check for a restart and set the rlimit accordingly.
            if node.run["restart"]:
                rlimit = self._restart_limit
            else:
                rlimit = 0

            # 1. The step and all its preceding parents use no parameters.
            if not self.used_params[step]:
                LOGGER.info(
                    "\n-------------------------------------------------\n"
                    "Adding step '%s' (No parameters used)\n"
                    "-------------------------------------------------\n",
                    step
                )
                # If we're not using any parameters at all, we do:
                # Copy the step and set to not modified.
                self.step_combos[step].add(step)

                workspace = make_safe_path(self._out_path, *[step])
                self.workspaces[step] = workspace
                LOGGER.debug("Workspace: %s", workspace)

                # NOTE: I don't think it's valid to have a specific workspace
                # since a step with no parameters operates at the global level.
                # NOTE: Opting to save the old command for provenence reasons.
                cmd = node.run["cmd"]
                r_cmd = node.run["restart"]
                LOGGER.info("Searching for workspaces...\ncmd = %s", cmd)
                for match in used_spaces:
                    LOGGER.info("Workspace found -- %s", match)
                    workspace_var = "$({}.workspace)".format(match)
                    if match in self.hub_depends[step]:
                        # If we're looking at a parameter independent match
                        # the workspace is the folder that contains all of
                        # the outputs of all combinations for the step.
                        ws = make_safe_path(self._out_path, *[match])
                        LOGGER.info("Found funnel workspace -- %s", ws)
                    else:
                        ws = self.workspaces[match]
                    cmd = cmd.replace(workspace_var, ws)
                    r_cmd = r_cmd.replace(workspace_var, ws)
                # We have to deepcopy the node, otherwise when we modify it
                # here, it's reflected in the ExecutionGraph.
                node = copy.deepcopy(node)
                node.run["cmd"] = cmd
                node.run["restart"] = r_cmd
                LOGGER.debug("New cmd = %s", cmd)
                LOGGER.debug("New restart = %s", r_cmd)
                dag.add_step(step, node, workspace, rlimit)

                if self.depends[step] or self.hub_depends[step]:
                    # So, because we don't have used parameters, we can just
                    # loop over the dependencies and add them.
                    LOGGER.debug("Processing regular dependencies.")
                    for parent in self.depends[step]:
                        LOGGER.info("Adding edge (%s, %s)...", parent, step)
                        dag.add_connection(parent, step)

                    # We can still have a case where we have steps that do
                    # funnel into this one even though this particular step
                    # is not parameterized.
                    LOGGER.debug("Processing hub dependencies.")
                    for parent in self.hub_depends[step]:
                        for item in self.step_combos[parent]:
                            LOGGER.info("Adding edge (%s, %s)...", item, step)
                            dag.add_connection(item, step)
                else:
                    # Otherwise, just add source since we're not dependent.
                    LOGGER.debug("Adding edge (%s, %s)...", SOURCE, step)
                    dag.add_connection(SOURCE, step)

            # 2. The step has used parameters.
            else:
                LOGGER.info(
                    "\n==================================================\n"
                    "Expanding step '%s'\n"
                    "==================================================\n"
                    "-------- Used Parameters --------\n"
                    "%s\n"
                    "---------------------------------",
                    step, self.used_params[step]
                )
                # Now we iterate over the combinations and expand the step.
                for combo in self.parameters:
                    LOGGER.info("\n**********************************\n"
                                "Combo [%s]\n"
                                "**********************************",
                                str(combo))
                    # Compute this step's combination name and workspace.
                    nickname = None
                    combo_str = combo.get_param_string(self.used_params[step])
                    # We must encode explicitly to utf-8
                    # combo_str = combo_str.encode("utf-8")
                    if self._hash_ws:
                        nickname = md5(combo_str.encode("utf-8")).hexdigest()
                        workspace = make_safe_path(
                                        self._out_path,
                                        *[step, nickname])
                    else:
                        workspace = \
                            make_safe_path(self._out_path, *[step, combo_str])
                        LOGGER.debug("Workspace: %s", workspace)
                    combo_str = "{}_{}".format(step, combo_str)
                    self.workspaces[combo_str] = workspace

                    # Check if the step combination has been processed.
                    if combo_str in self.step_combos:
                        continue
                    # Add this step to the combinations seen.
                    self.step_combos[step].add(combo_str)

                    modified, step_exp = node.apply_parameters(combo)
                    step_exp.name = combo_str
                    step_exp.nickname = nickname

                    # Substitute workspaces into the combination.
                    cmd = step_exp.run["cmd"]
                    r_cmd = step_exp.run["restart"]
                    LOGGER.info("Searching for workspaces...\ncmd = %s", cmd)
                    for match in used_spaces:
                        # Construct the workspace variable.
                        LOGGER.info("Workspace found -- %s", ws)
                        workspace_var = "$({}.workspace)".format(match)
                        if match in self.hub_depends[step]:
                            # If we're looking at a parameter independent match
                            # the workspace is the folder that contains all of
                            # the outputs of all combinations for the step.
                            ws = make_safe_path(self._out_path, *[match])
                            LOGGER.info("Found funnel workspace -- %s", ws)
                        elif not self.used_params[match]:
                            # If it's not a funneled dependency and the match
                            # is not parameterized, then the workspace is just
                            # the unparameterized match.
                            ws = self.workspaces[match]
                            LOGGER.info(
                                "Found unparameterized workspace -- %s", match)
                        else:
                            # Otherwise, we're dealing with a combination.
                            ws = "{}_{}".format(
                                match,
                                combo.get_param_string(self.used_params[match])
                            )
                            LOGGER.info(
                                "Found parameterized workspace -- %s", ws)
                            ws = self.workspaces[ws]

                        # Replace in both the command and restart command.
                        cmd = cmd.replace(workspace_var, ws)
                        r_cmd = r_cmd.replace(workspace_var, ws)
                    LOGGER.info("New cmd = %s", cmd)

                    step_exp.run["cmd"] = cmd
                    step_exp.run["restart"] = r_cmd
                    # Add to the step to the DAG.
                    dag.add_step(
                        step_exp.real_name, step_exp, workspace, rlimit,
                        params=combo.get_param_values(self.used_params[step]))

                    if self.depends[step] or self.hub_depends[step]:
                        # So, because we don't have used parameters, we can
                        # just loop over the dependencies and add them.
                        LOGGER.info("Processing regular dependencies.")
                        for p in self.depends[step]:
                            if self.used_params[p]:
                                p = "{}_{}".format(
                                    p,
                                    combo.get_param_string(self.used_params[p])
                                )
                            LOGGER.info(
                                "Adding edge (%s, %s)...", p, combo_str
                            )
                            dag.add_connection(p, combo_str)

                        # We can still have a case where we have steps that do
                        # funnel into this one even though this particular step
                        # is not parameterized.
                        LOGGER.debug("Processing hub dependencies.")
                        for parent in self.hub_depends[step]:
                            for item in self.step_combos[parent]:
                                LOGGER.info(
                                    "Adding edge (%s, %s)...", item, combo_str
                                )
                                dag.add_connection(item, combo_str)
                    else:
                        # Otherwise, just add source since we're not dependent.
                        LOGGER.debug(
                            "Adding edge (%s, %s)...", SOURCE, combo_str
                        )
                        dag.add_connection(SOURCE, combo_str)

        return dag

    def _stage_linear(self, dag):
        """
        Execute a linear workflow without parameters.

        :param throttle: Maximum number of in progress jobs allowed.
        :returns: The path to the study's global workspace and an
            ExecutionGraph based on linear steps in the study.
        """
        # For each step in the Study
        # Walk the study and add the steps to the ExecutionGraph.
        t_sorted = self.topological_sort()
        for step in t_sorted:
            # If we find the source node, we can just add it and continue.
            if step == SOURCE:
                LOGGER.debug("Source node found.")
                dag.add_node(SOURCE, None)
                continue

            # Initialize management structures.
            ws = make_safe_path(self._out_path, *[step])
            self.workspaces[step] = ws
            self.depends[step] = set()
            # Hub dependencies are not possible in linear studies. Empty set
            # for completion.
            self.hub_depends[step] = set()
            self.used_params[step] = set()
            self.step_combos[step] = set([step])

            node = self.values[step]
            # If the step has a restart cmd, set the limit.
            if node.run["restart"]:
                rlimit = self._restart_limit
            else:
                rlimit = 0

            cmd = node.run["cmd"]
            r_cmd = node.run["restart"]
            LOGGER.info("Searching for workspaces...\ncmd = %s", cmd)
            used_spaces = re.findall(WSREGEX, cmd)
            for match in used_spaces:
                # In this case we don't need to look for any parameters, or
                # combination dependent ("funnel") steps. It's a simple sub.
                LOGGER.info("Workspace found -- %s", match)
                workspace_var = "$({}.workspace)".format(match)
                ws = self.workspaces[match]
                cmd = cmd.replace(workspace_var, ws)
                r_cmd = r_cmd.replace(workspace_var, ws)
            node.run["cmd"] = cmd
            node.run["restart"] = r_cmd

            # Add the step
            dag.add_step(step, node, ws, rlimit)
            # If the node does not depend on any other steps, make it so that
            # if connects to SOURCE.
            if not node.run["depends"]:
                dag.add_connection(SOURCE, step)
            else:
                # In this case, since our step names are not parameterized,
                # and due to topological sort, we can guarantee that our
                # dependencies have been added. Go through and add each edge.
                for parent in node.run["depends"]:
                    self.depends[step].add(parent)
                    dag.add_connection(parent, step)

        return dag

    def stage(self):
        """
        Generate the execution graph for a Study.

        Staging creates an ExecutionGraph based on the combinations generated
        by the ParameterGeneration object stored in an instance of a Study.
        The stage method also sets up individual working directories (or
        workspaces) for each node in the workflow that requires it.

        :returns: An ExecutionGraph object with the expanded workflow.
        """
        # If the workspace doesn't exist, raise an exception.
        if not os.path.exists(self._out_path):
            msg = "Study {} is not set up for staging. Workspace does not " \
                  "exists (Output Dir = {}).".format(self.name, self._out_path)
            LOGGER.error(msg)
            raise Exception(msg)

        # If the environment isn't set up, raise an exception.
        if not self.environment.is_set_up:
            msg = "Study {} is not set up for staging. Environment is not " \
                  "set up. Aborting.".format(self.name)
            LOGGER.error(msg)
            raise Exception(msg)

        # After substituting, we should start getting combinations and
        # iterating. Two options here:
        # 1. Just create a new DAG with the step names altered to reflect the
        #    parameters they use.
        # 2. Create a derived DAG that has look up tables for each node based
        #    parameters. This might reduce to the same as 1, but retains the
        #    same original naming. Though that doesn't matter since the actual
        #    object has the original name.
        # NOTE: fdinatal - 2/6/17: Looks like 1 is the easiest to get done,
        # going with that for now.
        # NOTE: fdinatal - 3/28/17: Revisiting this method.. my previous logic
        # was flawed.
        # NOTE: fdinatal - 5/17/17: There is the strong possibility this method
        # will need to be reworked some in the future. It likely won't need to
        # be a complete gutting of the method, but there may need to be logic
        # for different styles of launching since it's the ExecutionGraph that
        # will need to be formatted properly so that scripts get generated in
        # the appropriate fashion.

        # Construct ExecutionGraph
        dag = ExecutionGraph(
            submission_attempts=self._submission_attempts,
            submission_throttle=self._submission_throttle,
            use_tmp=self._use_tmp, dry_run=self._dry_run)
        dag.add_description(**self.description)
        dag.log_description()

        # Because we're working within a Study class whose steps have already
        # been verified to not contain a cycle, we can override the check for
        # the execution graph. Because the execution graph is constructed from
        # the study steps, it won't contain a cycle.
        def _pass_detect_cycle(self):
            pass

        dag.detect_cycle = MethodType(_pass_detect_cycle, dag)

        return self._out_path, self._stage(dag)

output_path property

Property method for the OUTPUT_PATH specified for the study.

Returns:

Type Description

The string path stored in the OUTPUT_PATH variable.

__init__(name, description, studyenv=None, parameters=None, steps=None, out_path='./')

Study object used to represent the full workflow of a study.

Derived from the DAG data structure. Contains everything that a study requires to be expanded with the appropriate substitutions and with parameters inserted. This data structure should be the instance the future daemon loads in to track progress on a workflow.

Parameters:

Name Type Description Default
name

String representing the name of the Study.

required
description

A text description of what the study does.

required
steps

A list of StudySteps in proper workflow order.

None
studyenv

A populated StudyEnvironment instance.

None
parameters

A populated Parameters instance.

None
outpath

The path where the output of the study is written.

required
Source code in maestrowf/datastructures/core/study.py
def __init__(self, name, description,
             studyenv=None, parameters=None, steps=None, out_path="./"):
    """
    Study object used to represent the full workflow of a study.

    Derived from the DAG data structure. Contains everything that a study
    requires to be expanded with the appropriate substitutions and with
    parameters inserted. This data structure should be the instance the
    future daemon loads in to track progress on a workflow.

    :param name: String representing the name of the Study.
    :param description: A text description of what the study does.
    :param steps: A list of StudySteps in proper workflow order.
    :param studyenv: A populated StudyEnvironment instance.
    :param parameters: A populated Parameters instance.
    :param outpath: The path where the output of the study is written.
    """
    # The basic study information
    self.name = name
    self.description = description

    # Initialized the DAG so we have those structures to be used.
    super(Study, self).__init__()

    # We want deep copies so that properties don't change out from under
    # the Sudy data structure.
    self.environment = studyenv
    self.parameters = parameters
    self._out_path = out_path
    self._meta_path = os.path.join(out_path, "meta")

    LOGGER.debug("OUTPUT_PATH = %s", out_path)
    # Flag the study as not having been set up and add the source node.
    self._issetup = False
    self.is_configured = False
    self.add_node(SOURCE, None)

    # Settings for handling restarts and submission attempts.
    self._restart_limit = 0
    self._submission_attempts = 0
    self._use_tmp = False
    self._dry_run = False

    # Management structures
    # The workspace used by each step.
    self.workspaces = {SOURCE: self._out_path}
    # Parameter independent dependencies by step.
    self.hub_depends = {SOURCE: set()}
    # Other dependencies per step.
    self.depends = {SOURCE: set()}
    # Parameters that each step depends on.
    self.used_params = {SOURCE: set()}
    # Combinations seen per step.
    self.step_combos = {SOURCE: set()}

    # If the user specified a flow in the form of steps, copy those into
    # into the Study object.
    if steps:
        for step in steps:
            # Deep copy because it prevents modifications after the fact.
            self.add_step(step)

add_step(step)

Add a step to a study.

For this helper to be most effective, it recommended to apply steps in the order that they will be encountered. The method attempts to be intelligent and make the intended edge based on the 'depends' entry in a step. When adding steps out of order it's recommended to just use the base class DAG functionality and manually make connections.

Parameters:

Name Type Description Default
step

A StudyStep instance to be added to the Study instance.

required
Source code in maestrowf/datastructures/core/study.py
def add_step(self, step):
    """
    Add a step to a study.

    For this helper to be most effective, it recommended to apply steps in
    the order that they will be encountered. The method attempts to be
    intelligent and make the intended edge based on the 'depends' entry in
    a step. When adding steps out of order it's recommended to just use the
    base class DAG functionality and manually make connections.

    :param step: A StudyStep instance to be added to the Study instance.
    """
    # Add the node to the DAG.
    self.add_node(step.real_name, step)
    LOGGER.info(
        "Adding step '%s' to study '%s'...", step.name, self.name)
    # Apply the environment to the incoming step.
    step.__dict__ = \
        apply_function(step.__dict__, self.environment.apply_environment)

    # If the step depends on a prior step, create an edge.
    if "depends" in step.run and step.run["depends"]:
        for dependency in step.run["depends"]:
            LOGGER.info("{0} is dependent on {1}. Creating edge ("
                        "{1}, {0})...".format(step.real_name, dependency))
            if "*" not in dependency:
                self.add_edge(dependency, step.real_name)
            else:
                self.add_edge(
                    re.sub(ALL_COMBOS, "", dependency),
                    step.real_name
                )
    else:
        # Otherwise, if no other dependency, just execute the step.
        self.add_edge(SOURCE, step.real_name)

configure_study(submission_attempts=1, restart_limit=1, throttle=0, use_tmp=False, hash_ws=False, dry_run=False)

Perform initial configuration of a study. The method is used for going through and actually acquiring each dependency, substituting variables, sources and labels.

Parameters:

Name Type Description Default
submission_attempts

Number of attempted submissions before marking a step as failed. :param restart_limit: Upper limit on the number of times a step with a restart command can be resubmitted before it is considered failed. :param throttle: The maximum number of in-progress jobs allowed. [0 denotes no cap]. :param use_tmp: Boolean value specifying if the generated ExecutionGraph dumps its information into a temporary directory. :param dry_run: Boolean value that toggles dry run to just generate study workspaces and scripts without execution or status checking. :returns: True if the Study is successfully setup, False otherwise.

1
Source code in maestrowf/datastructures/core/study.py
def configure_study(self, submission_attempts=1, restart_limit=1,
                    throttle=0, use_tmp=False, hash_ws=False,
                    dry_run=False):
    """
    Perform initial configuration of a study. \

    The method is used for going through and actually acquiring each \
    dependency, substituting variables, sources and labels. \

    :param submission_attempts: Number of attempted submissions before \
    marking a step as failed. \
    :param restart_limit: Upper limit on the number of times a step with \
    a restart command can be resubmitted before it is considered failed. \
    :param throttle: The maximum number of in-progress jobs allowed. [0 \
    denotes no cap].\
    :param use_tmp: Boolean value specifying if the generated \
    ExecutionGraph dumps its information into a temporary directory. \
    :param dry_run: Boolean value that toggles dry run to just generate \
    study workspaces and scripts without execution or status checking. \
    :returns: True if the Study is successfully setup, False otherwise. \
    """

    self._submission_attempts = submission_attempts
    self._restart_limit = restart_limit
    self._submission_throttle = throttle
    self._use_tmp = use_tmp
    self._hash_ws = hash_ws
    self._dry_run = dry_run

    LOGGER.info(
        "\n------------------------------------------\n"
        "Submission attempts =       %d\n"
        "Submission restart limit =  %d\n"
        "Submission throttle limit = %d\n"
        "Use temporary directory =   %s\n"
        "Hash workspaces =           %s\n"
        "Dry run enabled =           %s\n"
        "Output path =               %s\n"
        "------------------------------------------",
        submission_attempts, restart_limit, throttle,
        use_tmp, hash_ws, dry_run, self._out_path
    )

    self.is_configured = True

load_metadata()

Load metadata for the study.

Source code in maestrowf/datastructures/core/study.py
def load_metadata(self):
    """Load metadata for the study."""
    if not os.path.exists(self._meta_path):
        return

    path = os.path.join(self._meta_path, "study", "env.pkl")
    with open(path, 'rb') as pkl:
        env = pickle.load(pkl)

    if not isinstance(env, type(self)):
        msg = "Object loaded from {path} is of type {type}. Expected an" \
              " object of type '{cls}.'".format(path=path, type=type(env),
                                                cls=type(self))
        LOGGER.error(msg)
        raise TypeError(msg)

    metapath = os.path.join(self._meta_path, "metadata.yaml")
    with open(metapath, "rb") as metafile:
        metadata = yaml.load(metafile)

    self.depends = metadata["dependencies"]
    self.hub_depends = metadata["hub_dependencies"]
    self.workspaces = metadata["workspaces"]
    self.used_params = metadata["used_parameters"]
    self.step_combos = metadata["step_combinations"]

setup_environment()

Set up the environment by acquiring outside dependencies.

Source code in maestrowf/datastructures/core/study.py
def setup_environment(self):
    """Set up the environment by acquiring outside dependencies."""
    # Set up the environment if it hasn't been already.
    if not self.environment.is_set_up:
        LOGGER.debug("Environment is setting up.")
        self.environment.acquire_environment()

setup_workspace()

Set up the study's main workspace directory.

Source code in maestrowf/datastructures/core/study.py
def setup_workspace(self):
    """Set up the study's main workspace directory."""
    try:
        LOGGER.debug("Setting up study workspace in '%s'", self._out_path)
        create_parentdir(self._out_path)
    except Exception as e:
        LOGGER.error(e.args)
        return False

stage()

Generate the execution graph for a Study.

Staging creates an ExecutionGraph based on the combinations generated by the ParameterGeneration object stored in an instance of a Study. The stage method also sets up individual working directories (or workspaces) for each node in the workflow that requires it.

Returns:

Type Description

An ExecutionGraph object with the expanded workflow.

Source code in maestrowf/datastructures/core/study.py
def stage(self):
    """
    Generate the execution graph for a Study.

    Staging creates an ExecutionGraph based on the combinations generated
    by the ParameterGeneration object stored in an instance of a Study.
    The stage method also sets up individual working directories (or
    workspaces) for each node in the workflow that requires it.

    :returns: An ExecutionGraph object with the expanded workflow.
    """
    # If the workspace doesn't exist, raise an exception.
    if not os.path.exists(self._out_path):
        msg = "Study {} is not set up for staging. Workspace does not " \
              "exists (Output Dir = {}).".format(self.name, self._out_path)
        LOGGER.error(msg)
        raise Exception(msg)

    # If the environment isn't set up, raise an exception.
    if not self.environment.is_set_up:
        msg = "Study {} is not set up for staging. Environment is not " \
              "set up. Aborting.".format(self.name)
        LOGGER.error(msg)
        raise Exception(msg)

    # After substituting, we should start getting combinations and
    # iterating. Two options here:
    # 1. Just create a new DAG with the step names altered to reflect the
    #    parameters they use.
    # 2. Create a derived DAG that has look up tables for each node based
    #    parameters. This might reduce to the same as 1, but retains the
    #    same original naming. Though that doesn't matter since the actual
    #    object has the original name.
    # NOTE: fdinatal - 2/6/17: Looks like 1 is the easiest to get done,
    # going with that for now.
    # NOTE: fdinatal - 3/28/17: Revisiting this method.. my previous logic
    # was flawed.
    # NOTE: fdinatal - 5/17/17: There is the strong possibility this method
    # will need to be reworked some in the future. It likely won't need to
    # be a complete gutting of the method, but there may need to be logic
    # for different styles of launching since it's the ExecutionGraph that
    # will need to be formatted properly so that scripts get generated in
    # the appropriate fashion.

    # Construct ExecutionGraph
    dag = ExecutionGraph(
        submission_attempts=self._submission_attempts,
        submission_throttle=self._submission_throttle,
        use_tmp=self._use_tmp, dry_run=self._dry_run)
    dag.add_description(**self.description)
    dag.log_description()

    # Because we're working within a Study class whose steps have already
    # been verified to not contain a cycle, we can override the check for
    # the execution graph. Because the execution graph is constructed from
    # the study steps, it won't contain a cycle.
    def _pass_detect_cycle(self):
        pass

    dag.detect_cycle = MethodType(_pass_detect_cycle, dag)

    return self._out_path, self._stage(dag)

store_metadata()

Store metadata related to the study.

Source code in maestrowf/datastructures/core/study.py
def store_metadata(self):
    """Store metadata related to the study."""
    # Create the metadata directory.
    create_parentdir(self._meta_path)

    # Store the environment object in order to preserve it.
    path = os.path.join(self._meta_path, "study")
    create_parentdir(path)
    path = os.path.join(path, "env.pkl")
    with open(path, 'wb') as pkl:
        pickle.dump(self, pkl)

    # Construct other metadata related to study construction.
    _workspaces = {}
    for key, value in self.workspaces.items():
        if key == "_source":
            _workspaces[key] = value
        elif key in self.step_combos:
            _workspaces[key] = os.path.split(value)[-1]
        else:
            _workspaces[key] = \
                os.path.sep.join(value.rsplit(os.path.sep)[-2:])

    # Construct relative paths for the combinations and nest them in the
    # same way as the step combinations dictionary.
    _step_combos = {}
    for key, value in self.step_combos.items():
        if key == SOURCE:
            _step_combos[key] = self.workspaces[key]
        elif not self.used_params[key]:
            _ws = self.workspaces[key]
            _step_combos[key] = {key: os.path.split(_ws)[-1]}
        else:
            _step_combos[key] = {}
            for combo in value:
                _ws = self.workspaces[combo]
                _step_combos[key][combo] = \
                    os.path.sep.join(_ws.rsplit(os.path.sep)[-2:])

    metadata = {
        "dependencies": self.depends,
        "hub_dependencies": self.hub_depends,
        "workspaces": _workspaces,
        "used_parameters": self.used_params,
        "step_combinations": _step_combos,
    }
    # Write out the study construction metadata.
    path = os.path.join(self._meta_path, "metadata.yaml")
    with open(path, "wb") as metafile:
        metafile.write(yaml.dump(metadata).encode("utf-8"))

    # Write out parameter metadata.
    metadata = self.parameters.get_metadata()
    path = os.path.join(self._meta_path, "parameters.yaml")
    with open(path, "wb") as metafile:
        metafile.write(yaml.dump(metadata).encode("utf-8"))

    # Write out environment metadata
    path = os.path.join(self._meta_path, "environment.yaml")
    with open(path, "wb") as metafile:
        metafile.write(yaml.dump(os.environ.copy()).encode("utf-8"))

walk_study(src=SOURCE)

Walk the study and create a spanning tree.

Parameters:

Name Type Description Default
src

Source node to start the walk.

SOURCE

Returns:

Type Description

A generator of (parent, node name, node value) tuples.

Source code in maestrowf/datastructures/core/study.py
def walk_study(self, src=SOURCE):
    """
    Walk the study and create a spanning tree.

    :param src: Source node to start the walk.
    :returns: A generator of (parent, node name, node value) tuples.
    """
    # Get a DFS spanning tree of the study. This method should always
    # return a complete tree because _source is flagged as a dependency
    # if a step is added without one.
    # TODO: This method should be fixed to return both parents and nodes.
    path, parents = self.dfs_subtree(src)
    for node in path:
        yield parents[node], node, self.values[node]

StudyEnvironment

StudyEnvironment for managing a study environment.

The StudyEnvironment provides the context where all study steps can find variables, sources, dependencies, etc.

Source code in maestrowf/datastructures/core/studyenvironment.py
class StudyEnvironment:
    """
    StudyEnvironment for managing a study environment.

    The StudyEnvironment provides the context where all study
    steps can find variables, sources, dependencies, etc.
    """

    def __init__(self):
        """Initialize an empty StudyEnvironment."""
        # Types of environment objects.
        self.substitutions = {}
        self.labels = {}
        self.sources = []
        self.dependencies = {}

        # Private members
        self._tokens = set()
        self._names = set()
        # Boolean that tracks if dependencies have been acquired.
        self._is_set_up = False

        LOGGER.debug("Initialized an empty StudyEnvironment.")

    def __bool__(self):
        """
        Override for the __bool__ operator.

        :returns: True if the StudyEnvironment instance has values, False
            otherwise.
        """
        return bool(self._names)

    @property
    def is_set_up(self):
        """
        Check that the StudyEnvironment is set up.

        :returns: True is the instance is set up, False otherwise.
        """
        return self._is_set_up

    def add(self, item):
        """
        Add the item parameter to the StudyEnvironment.

        :param item: EnvObject to be added to the environment.
        """
        # TODO: Need to revist this to make this better. A label can get lost
        # because the necessary variable could have not been added yet
        # and there's too much of a need to process a dependency first.
        name = None
        LOGGER.debug("Calling add with %s", str(item))
        if isinstance(item, Dependency):
            LOGGER.debug("Adding %s of type %s.", item.name, type(item))
            LOGGER.debug("Value: %s.", item.__dict__)
            self.dependencies[item.name] = item
            name = item.name
            self._is_set_up = False
        elif isinstance(item, Substitution):
            LOGGER.debug("Value: %s", item.value)
            LOGGER.debug("Tokens: %s", self._tokens)
            name = item.name
            LOGGER.debug("Adding %s of type %s.", item.name, type(item))
            if (
                    isinstance(item.value, str) and
                    any(token in item.value for token in self._tokens)):
                LOGGER.debug("Label detected. Adding %s to labels", item.name)
                self.labels[item.name] = item
            else:
                self._tokens.add(item.token)
                self.substitutions[item.name] = item
        elif isinstance(item, Source):
            LOGGER.debug("Adding source %s", item.source)
            LOGGER.debug("Item source: %s", item.source)
            self.sources.append(item)
        else:
            error = "Received an item of type {}. Expected an item of base " \
                    "type Substitution, Source, or Dependency." \
                    .format(type(item))
            LOGGER.exception(error)
            raise TypeError(error)

        if name and name in self._names:
            error = "A duplicate name '{}' has been detected. All names " \
                    "must be unique. Aborting.".format(name)
            LOGGER.exception(error)
            raise ValueError(error)
        else:
            LOGGER.debug("{} added to set of names.".format(name))
            self._names.add(name)

    def find(self, key):
        """
        Find the environment object labeled by the specified key.

        :param key: Name of the environment object to find.
        :returns: The environment object labeled by key, None if key is not
            found.
        """
        LOGGER.debug("Looking for '%s'...", key)
        if key in self.dependencies:
            LOGGER.debug("Found '%s' in environment dependencies.", key)
            return self.dependencies[key]

        if key in self.substitutions:
            LOGGER.debug("Found '%s' in environment substitutions.", key)
            return self.substitutions[key]

        if key in self.labels:
            LOGGER.debug("Found '%s' in environment labels.", key)
            return self.labels[key]

        LOGGER.debug("'%s' not found -- \n%s", key, self)
        return None

    def remove(self, key):
        """
        Remove the environment object labeled by the specified key.

        :param key: Name of the environment object to remove.
        :returns: The environment object labeled by key.
        """
        LOGGER.debug("Looking to remove '%s'...", key)

        if key not in self._names:
            return None

        _ = self.dependencies.pop(key, None)
        if _ is not None:
            self._names.remove(key)
            return _

        _ = self.substitutions.pop(key, None)
        if _ is not None:
            self._names.remove(key)
            return _

        _ = self.labels.pop(key, None)
        if _ is not None:
            self._names.remove(key)
            return _

        LOGGER.debug("'%s' not found -- \n%s", key, self)
        return None

    def acquire_environment(self):
        """Acquire any environment items that may be stored remotely."""
        if self._is_set_up:
            LOGGER.info("Environment already set up. Returning.")
            return

        LOGGER.debug("Acquiring dependencies")
        for dependency, value in self.dependencies.items():
            LOGGER.info("Acquiring -- %s", dependency)
            value.acquire(substitutions=self.substitutions.values())

        self._is_set_up = True

    def apply_environment(self, item):
        """
        Apply the environment to the specified item.

        :param item: String to apply environment to.
        :returns: String with the environment applied.
        """
        if not item:
            return item

        LOGGER.debug("Applying environment to %s", item)
        LOGGER.debug("Processing labels...")
        for label, value in self.labels.items():
            LOGGER.debug("Looking for %s in %s", label, item)
            item = value.substitute(item)
            LOGGER.debug("After substitution: %s", item)

        LOGGER.debug("Processing dependencies...")
        for label, dependency in self.dependencies.items():
            LOGGER.debug("Looking for %s in %s", label, item)
            item = dependency.substitute(item)
            LOGGER.debug("After substitution: %s", item)
            LOGGER.debug("Acquiring %s.", label)

        LOGGER.debug("Processing substitutions...")
        for substitution, value in self.substitutions.items():
            LOGGER.debug("Looking for %s in %s", substitution, item)
            item = value.substitute(item)
            LOGGER.debug("After substitution: %s", item)

        return item

is_set_up property

Check that the StudyEnvironment is set up.

Returns:

Type Description

True is the instance is set up, False otherwise.

__bool__()

Override for the bool operator.

Returns:

Type Description

True if the StudyEnvironment instance has values, False otherwise.

Source code in maestrowf/datastructures/core/studyenvironment.py
def __bool__(self):
    """
    Override for the __bool__ operator.

    :returns: True if the StudyEnvironment instance has values, False
        otherwise.
    """
    return bool(self._names)

__init__()

Initialize an empty StudyEnvironment.

Source code in maestrowf/datastructures/core/studyenvironment.py
def __init__(self):
    """Initialize an empty StudyEnvironment."""
    # Types of environment objects.
    self.substitutions = {}
    self.labels = {}
    self.sources = []
    self.dependencies = {}

    # Private members
    self._tokens = set()
    self._names = set()
    # Boolean that tracks if dependencies have been acquired.
    self._is_set_up = False

    LOGGER.debug("Initialized an empty StudyEnvironment.")

acquire_environment()

Acquire any environment items that may be stored remotely.

Source code in maestrowf/datastructures/core/studyenvironment.py
def acquire_environment(self):
    """Acquire any environment items that may be stored remotely."""
    if self._is_set_up:
        LOGGER.info("Environment already set up. Returning.")
        return

    LOGGER.debug("Acquiring dependencies")
    for dependency, value in self.dependencies.items():
        LOGGER.info("Acquiring -- %s", dependency)
        value.acquire(substitutions=self.substitutions.values())

    self._is_set_up = True

add(item)

Add the item parameter to the StudyEnvironment.

Parameters:

Name Type Description Default
item

EnvObject to be added to the environment.

required
Source code in maestrowf/datastructures/core/studyenvironment.py
def add(self, item):
    """
    Add the item parameter to the StudyEnvironment.

    :param item: EnvObject to be added to the environment.
    """
    # TODO: Need to revist this to make this better. A label can get lost
    # because the necessary variable could have not been added yet
    # and there's too much of a need to process a dependency first.
    name = None
    LOGGER.debug("Calling add with %s", str(item))
    if isinstance(item, Dependency):
        LOGGER.debug("Adding %s of type %s.", item.name, type(item))
        LOGGER.debug("Value: %s.", item.__dict__)
        self.dependencies[item.name] = item
        name = item.name
        self._is_set_up = False
    elif isinstance(item, Substitution):
        LOGGER.debug("Value: %s", item.value)
        LOGGER.debug("Tokens: %s", self._tokens)
        name = item.name
        LOGGER.debug("Adding %s of type %s.", item.name, type(item))
        if (
                isinstance(item.value, str) and
                any(token in item.value for token in self._tokens)):
            LOGGER.debug("Label detected. Adding %s to labels", item.name)
            self.labels[item.name] = item
        else:
            self._tokens.add(item.token)
            self.substitutions[item.name] = item
    elif isinstance(item, Source):
        LOGGER.debug("Adding source %s", item.source)
        LOGGER.debug("Item source: %s", item.source)
        self.sources.append(item)
    else:
        error = "Received an item of type {}. Expected an item of base " \
                "type Substitution, Source, or Dependency." \
                .format(type(item))
        LOGGER.exception(error)
        raise TypeError(error)

    if name and name in self._names:
        error = "A duplicate name '{}' has been detected. All names " \
                "must be unique. Aborting.".format(name)
        LOGGER.exception(error)
        raise ValueError(error)
    else:
        LOGGER.debug("{} added to set of names.".format(name))
        self._names.add(name)

apply_environment(item)

Apply the environment to the specified item.

Parameters:

Name Type Description Default
item

String to apply environment to.

required

Returns:

Type Description

String with the environment applied.

Source code in maestrowf/datastructures/core/studyenvironment.py
def apply_environment(self, item):
    """
    Apply the environment to the specified item.

    :param item: String to apply environment to.
    :returns: String with the environment applied.
    """
    if not item:
        return item

    LOGGER.debug("Applying environment to %s", item)
    LOGGER.debug("Processing labels...")
    for label, value in self.labels.items():
        LOGGER.debug("Looking for %s in %s", label, item)
        item = value.substitute(item)
        LOGGER.debug("After substitution: %s", item)

    LOGGER.debug("Processing dependencies...")
    for label, dependency in self.dependencies.items():
        LOGGER.debug("Looking for %s in %s", label, item)
        item = dependency.substitute(item)
        LOGGER.debug("After substitution: %s", item)
        LOGGER.debug("Acquiring %s.", label)

    LOGGER.debug("Processing substitutions...")
    for substitution, value in self.substitutions.items():
        LOGGER.debug("Looking for %s in %s", substitution, item)
        item = value.substitute(item)
        LOGGER.debug("After substitution: %s", item)

    return item

find(key)

Find the environment object labeled by the specified key.

Parameters:

Name Type Description Default
key

Name of the environment object to find.

required

Returns:

Type Description

The environment object labeled by key, None if key is not found.

Source code in maestrowf/datastructures/core/studyenvironment.py
def find(self, key):
    """
    Find the environment object labeled by the specified key.

    :param key: Name of the environment object to find.
    :returns: The environment object labeled by key, None if key is not
        found.
    """
    LOGGER.debug("Looking for '%s'...", key)
    if key in self.dependencies:
        LOGGER.debug("Found '%s' in environment dependencies.", key)
        return self.dependencies[key]

    if key in self.substitutions:
        LOGGER.debug("Found '%s' in environment substitutions.", key)
        return self.substitutions[key]

    if key in self.labels:
        LOGGER.debug("Found '%s' in environment labels.", key)
        return self.labels[key]

    LOGGER.debug("'%s' not found -- \n%s", key, self)
    return None

remove(key)

Remove the environment object labeled by the specified key.

Parameters:

Name Type Description Default
key

Name of the environment object to remove.

required

Returns:

Type Description

The environment object labeled by key.

Source code in maestrowf/datastructures/core/studyenvironment.py
def remove(self, key):
    """
    Remove the environment object labeled by the specified key.

    :param key: Name of the environment object to remove.
    :returns: The environment object labeled by key.
    """
    LOGGER.debug("Looking to remove '%s'...", key)

    if key not in self._names:
        return None

    _ = self.dependencies.pop(key, None)
    if _ is not None:
        self._names.remove(key)
        return _

    _ = self.substitutions.pop(key, None)
    if _ is not None:
        self._names.remove(key)
        return _

    _ = self.labels.pop(key, None)
    if _ is not None:
        self._names.remove(key)
        return _

    LOGGER.debug("'%s' not found -- \n%s", key, self)
    return None

StudyStep

Class that represents the data and API for a single study step.

This class is primarily a 1:1 mapping of a study step in the YAML spec in terms of data. The StudyStep's class API should capture all functions that a step can be expected to perform, including:

  • Applying a combination of parameters to itself.
  • Tests for equality and non-equality to check for changes.
  • Other -- WIP
Source code in maestrowf/datastructures/core/study.py
class StudyStep:
    """
    Class that represents the data and API for a single study step.

    This class is primarily a 1:1 mapping of a study step in the YAML spec in
    terms of data. The StudyStep's class API should capture all functions that
    a step can be expected to perform, including:

    * Applying a combination of parameters to itself.
    * Tests for equality and non-equality to check for changes.
    * Other -- WIP
    """

    def __init__(self):
        """Object that represents a single workflow step."""
        self._name = ""
        self.description = ""
        self.nickname = ""
        self.run = {
                        "cmd":              "",
                        "depends":          "",
                        "pre":              "",
                        "post":             "",
                        "restart":          "",
                        "nodes":            "",
                        "procs":            "",
                        "gpus":             "",
                        "cores per task":   "",
                        "walltime":         "",
                        "reservation":      ""
                    }

    def apply_parameters(self, combo):
        """
        Apply a parameter combination to the StudyStep.

        :param combo: A Combination instance to be applied to a StudyStep.
        :returns: A new StudyStep instance with combo applied to its members.
        """
        # Create a new StudyStep and populate it with substituted values.
        tmp = StudyStep()
        tmp.__dict__ = apply_function(self.__dict__, combo.apply)
        # Return if the new step is modified and the step itself.

        return self.__ne__(tmp), tmp

    @property
    def name(self):
        """
        Get the name to assign to a task for this step.

        :returns: A utf-8 formatted string of the task name.
        """
        if self.nickname:
            return self.nickname
        return self._name

    @name.setter
    def name(self, value):
        """
        Set the name of a StudyStep instance.

        :param value: A string value representing the name to give the step.
        """
        self._name = value

    @property
    def real_name(self):
        """
        Get the real name of the step (ignore nickname).

        :returns: A string of the true name of a StudyStep instance.
        """
        return self._name

    def __eq__(self, other):
        """
        Equality operator for the StudyStep class.

        :param other: Object to compare self to.
        : returns: True if other is equal to self, False otherwise.
        """
        if isinstance(other, self.__class__):
            # This works because the classes are currently interfaces over
            # internals that are all based on Python builtin classes.
            # NOTE: This method will need to be reworked if something more
            # complex is done with the class.
            return self.__dict__ == other.__dict__

        return False

    def __ne__(self, other):
        """
        Non-equality operator for the StudyStep class.

        :param other: Object to compare self to.
        : returns: True if other is not equal to self, False otherwise.
        """
        return not self.__eq__(other)

name property writable

Get the name to assign to a task for this step.

Returns:

Type Description

A utf-8 formatted string of the task name.

real_name property

Get the real name of the step (ignore nickname).

Returns:

Type Description

A string of the true name of a StudyStep instance.

__eq__(other)

Equality operator for the StudyStep class.

: returns: True if other is equal to self, False otherwise.

Parameters:

Name Type Description Default
other

Object to compare self to.

required
Source code in maestrowf/datastructures/core/study.py
def __eq__(self, other):
    """
    Equality operator for the StudyStep class.

    :param other: Object to compare self to.
    : returns: True if other is equal to self, False otherwise.
    """
    if isinstance(other, self.__class__):
        # This works because the classes are currently interfaces over
        # internals that are all based on Python builtin classes.
        # NOTE: This method will need to be reworked if something more
        # complex is done with the class.
        return self.__dict__ == other.__dict__

    return False

__init__()

Object that represents a single workflow step.

Source code in maestrowf/datastructures/core/study.py
def __init__(self):
    """Object that represents a single workflow step."""
    self._name = ""
    self.description = ""
    self.nickname = ""
    self.run = {
                    "cmd":              "",
                    "depends":          "",
                    "pre":              "",
                    "post":             "",
                    "restart":          "",
                    "nodes":            "",
                    "procs":            "",
                    "gpus":             "",
                    "cores per task":   "",
                    "walltime":         "",
                    "reservation":      ""
                }

__ne__(other)

Non-equality operator for the StudyStep class.

: returns: True if other is not equal to self, False otherwise.

Parameters:

Name Type Description Default
other

Object to compare self to.

required
Source code in maestrowf/datastructures/core/study.py
def __ne__(self, other):
    """
    Non-equality operator for the StudyStep class.

    :param other: Object to compare self to.
    : returns: True if other is not equal to self, False otherwise.
    """
    return not self.__eq__(other)

apply_parameters(combo)

Apply a parameter combination to the StudyStep.

Parameters:

Name Type Description Default
combo

A Combination instance to be applied to a StudyStep.

required

Returns:

Type Description

A new StudyStep instance with combo applied to its members.

Source code in maestrowf/datastructures/core/study.py
def apply_parameters(self, combo):
    """
    Apply a parameter combination to the StudyStep.

    :param combo: A Combination instance to be applied to a StudyStep.
    :returns: A new StudyStep instance with combo applied to its members.
    """
    # Create a new StudyStep and populate it with substituted values.
    tmp = StudyStep()
    tmp.__dict__ = apply_function(self.__dict__, combo.apply)
    # Return if the new step is modified and the step itself.

    return self.__ne__(tmp), tmp