def calc_derivatives(self,
                         first=False,
                         second=False,
                         savebase=False,
                         required_inputs=None,
                         required_outputs=None):
        """ Calculate derivatives and save baseline states for all components
        in this workflow.
        """

        self._stop = False

        dgraph = self.derivative_graph(required_inputs, required_outputs)
        comps = dgraph.edge_dict_to_comp_list(
            edges_to_dict(dgraph.list_connections()))
        for compname, data in comps.iteritems():
            if '~' in compname:
                comp = self._derivative_graph.node[compname]['pa_object']
            elif compname.startswith('@'):
                continue
            else:
                comp = self.scope.get(compname)

            J = self._J_cache.get(compname)
            if compname not in self._shape_cache:
                self._shape_cache[compname] = {}
            if J is None:
                J = comp.calc_derivatives(first, second, savebase,
                                          data['inputs'], data['outputs'])
                if J is not None:
                    self._J_cache[compname] = J

            if self._stop:
                raise RunStopped('Stop requested')
 def run(self, ffd_order=0, case_id=''):
     """ Run the Components in this Workflow. """
     self._stop = False
     self._iterator = self.__iter__()
     for node in self._iterator:
         node.run(ffd_order=ffd_order, case_id=case_id)
         if self._stop:
             raise RunStopped('Stop requested')
     self._iterator = None
Example #3
0
    def calc_derivatives(self, first=False, second=False, savebase=False):
        """ Calculate derivatives and save baseline states for all components
        in this workflow."""

        self._stop = False
        for node in self.__iter__():
            node.calc_derivatives(first, second, savebase)
            if self._stop:
                raise RunStopped('Stop requested')
    def run(self, case_uuid=None):
        """ Run the Components in this Workflow. """
        if not self._system.is_active():
            return

        self._stop = False
        self._exec_count += 1

        iterbase = self._iterbase()

        if case_uuid is None:
            # We record the case and are responsible for unique case ids.
            record_case = True
            case_uuid = Case.next_uuid()
        else:
            record_case = False

        err = None
        try:
            uvec = self._system.vec['u']
            fvec = self._system.vec['f']

            if self._need_prescatter:
                self._system.scatter('u', 'p')

            # save old value of u to compute resids
            for node in self._cycle_vars:
                fvec[node][:] = uvec[node][:]

            self._system.run(iterbase=iterbase, case_uuid=case_uuid)

            # update resid vector for cyclic vars
            for node in self._cycle_vars:
                fvec[node][:] -= uvec[node][:]

            if self._stop:
                raise RunStopped('Stop requested')
        except Exception:
            err = sys.exc_info()

        if record_case and self._rec_required:
            try:
                self._record_case(case_uuid, err)
            except Exception as exc:
                if err is None:
                    err = sys.exc_info()
                self.parent._logger.error("Can't record case: %s", exc)

        # reraise exception with proper traceback if one occurred
        if err is not None:
            # NOTE: cannot use 'raise err' here for some reason.  Must separate
            # the parts of the tuple.
            raise err[0], err[1], err[2]
Example #5
0
 def step(self):
     """Similar to the 'execute' function, but this one only
     executes a single Component from the workflow each time
     it's called.
     """
     if self._iter is None:
         self.start_iteration()
         self._iter = self._step()
     try:
         self._iter.next()
     except StopIteration:
         self._iter = None
         raise
     raise RunStopped('Step complete')
Example #6
0
 def run(self, ffd_order=0, case_id=''):
     """ Run the Components in this Workflow. """
     self._stop = False
     self._iterator = self.__iter__()
     self._exec_count += 1
     self._comp_count = 0
     iterbase = self._iterbase(case_id)
     for comp in self._iterator:
         self._comp_count += 1
         comp.set_itername('%s-%d' % (iterbase, self._comp_count))
         comp.run(ffd_order=ffd_order, case_id=case_id)
         if self._stop:
             raise RunStopped('Stop requested')
     self._iterator = None
Example #7
0
    def run(self, ffd_order=0, case_uuid=None):
        """ Run the Components in this Workflow. """
        self._stop = False
        self._exec_count += 1

        iterbase = self._iterbase()

        if case_uuid is None:
            # We record the case and are responsible for unique case ids.
            record_case = True
            case_uuid = Case.next_uuid()
        else:
            record_case = False

        err = None
        scope = self.scope
        try:
            for comp in self:
                # before the workflow runs each component, update that
                # component's inputs based on the graph
                scope.update_inputs(comp.name, graph=self._var_graph)
                if isinstance(comp, PseudoComponent):
                    comp.run(ffd_order=ffd_order)
                else:
                    comp.set_itername('%s-%s' % (iterbase, comp.name))
                    comp.run(ffd_order=ffd_order, case_uuid=case_uuid)
                if self._stop:
                    raise RunStopped('Stop requested')
        except Exception:
            err = sys.exc_info()

        if record_case and self._rec_required:
            try:
                self._record_case(case_uuid, err)
            except Exception as exc:
                if err is None:
                    err = sys.exc_info()
                self.parent._logger.error("Can't record case: %s", exc)

        # reraise exception with proper traceback if one occurred
        if err is not None:
            # NOTE: cannot use 'raise err' here for some reason.  Must separate
            # the parts of the tuple.
            raise err[0], err[1], err[2]
Example #8
0
class Workflow(object):
    """
    A Workflow consists of a collection of Components which are to be executed
    in some order.
    """
    def __init__(self, parent=None, scope=None, members=None):
        """Create a Workflow.
        
        parent: Driver (optional)
            The Driver that contains this Workflow.  This option is normally
            passed instead of scope because scope usually isn't known at
            initialization time.  If scope is not provided, it will be
            set to parent.parent, which should be the Assembly that contains
            the parent Driver.
            
        scope: Component (optional)
            The scope can be explicitly specified here, but this is not 
            typically known at initialization time.

        members: list of str (optional)
            A list of names of Components to add to this workflow.
        """
        self._iterator = None
        self._stop = False
        self._parent = parent
        self._scope = scope
        self._exec_count = 0  # Workflow executions since reset.
        self._initial_count = 0  # Value to reset to (typically zero).
        self._comp_count = 0  # Component index in workflow.
        if members:
            for member in members:
                if not isinstance(member, basestring):
                    raise TypeError(
                        "Components must be added to a workflow by name.")
                self.add(member)

    @property
    def scope(self):
        """The scoping Component that is used to resolve the Component names in 
        this Workflow.
        """
        if self._scope is None and self._parent is not None:
            self._scope = self._parent.parent
        if self._scope is None:
            raise RuntimeError("workflow has no scope!")
        return self._scope

    @scope.setter
    def scope(self, scope):
        self._scope = scope
        self.config_changed()

    def set_initial_count(self, count):
        """
        Set initial value for execution count.  Only needed if the iteration
        coordinates must be initialized, such as for CaseIterDriverBase.

        count: int
            Initial value for workflow execution count.
        """
        self._initial_count = count - 1  # run() and step() will increment.

    def reset(self):
        """ Reset execution count. """
        self._exec_count = self._initial_count

    def run(self, ffd_order=0, case_id=''):
        """ Run the Components in this Workflow. """
        self._stop = False
        self._iterator = self.__iter__()
        self._exec_count += 1
        self._comp_count = 0
        iterbase = self._iterbase(case_id)
        for comp in self._iterator:
            self._comp_count += 1
            comp.set_itername('%s-%d' % (iterbase, self._comp_count))
            comp.run(ffd_order=ffd_order, case_id=case_id)
            if self._stop:
                raise RunStopped('Stop requested')
        self._iterator = None

    def _iterbase(self, case_id):
        """ Return base for 'iteration coordinates'. """
        if self._parent is None:
            return str(self._exec_count)  # An unusual case.
        else:
            prefix = self._parent.get_itername()
            if not prefix:
                prefix = case_id
            if prefix:
                prefix += '.'
            return '%s%d' % (prefix, self._exec_count)

    def step(self, ffd_order=0, case_id=''):
        """Run a single component in this Workflow."""
        if self._iterator is None:
            self._iterator = self.__iter__()
            self._exec_count += 1
            self._comp_count = 0

        comp = self._iterator.next()
        self._comp_count += 1
        iterbase = self._iterbase(case_id)
        comp.set_itername('%s-%d' % (iterbase, self._comp_count))
        try:
            comp.run(ffd_order=ffd_order, case_id=case_id)
        except StopIteration, err:
            self._iterator = None
            raise err
        raise RunStopped('Step complete')
class Workflow(object):
    """
    A Workflow consists of a collection of Components which are to be executed
    in some order.
    """
    def __init__(self, parent=None, scope=None, members=None):
        """Create a Workflow.
        
        parent: Driver (optional)
            The Driver that contains this Workflow.  This option is normally
            passed instead of scope because scope usually isn't known at
            initialization time.  If scope is not provided, it will be
            set to parent.parent, which should be the Assembly that contains
            the parent Driver.
            
        scope: Component (optional)
            The scope can be explicitly specified here, but this is not 
            typically known at initialization time.

        members: list of str (optional)
            A list of names of Components to add to this workflow.
        """
        self._iterator = None
        self._stop = False
        self._parent = parent
        self._scope = scope
        if members:
            for member in members:
                if not isinstance(member, basestring):
                    raise TypeError(
                        "Components must be added to a workflow by name.")
                self.add(member)

    @property
    def scope(self):
        """The scoping Component that is used to resolve the Component names in 
        this Workflow.
        """
        if self._scope is None and self._parent is not None:
            self._scope = self._parent.parent
        if self._scope is None:
            raise RuntimeError("workflow has no scope!")
        return self._scope

    @scope.setter
    def scope(self, scope):
        self._scope = scope
        self.config_changed()

    def run(self, ffd_order=0, case_id=''):
        """ Run the Components in this Workflow. """
        self._stop = False
        self._iterator = self.__iter__()
        for node in self._iterator:
            node.run(ffd_order=ffd_order, case_id=case_id)
            if self._stop:
                raise RunStopped('Stop requested')
        self._iterator = None

    def step(self, ffd_order=0, case_id=''):
        """Run a single component in this Workflow."""
        if self._iterator is None:
            self._iterator = self.__iter__()

        comp = self._iterator.next()
        try:
            comp.run(ffd_order=ffd_order, case_id='')
        except StopIteration, err:
            self._iterator = None
            raise err
        raise RunStopped('Step complete')