How to use the openmdao.main.mp_support.has_interface function in openmdao

To help you get started, we’ve selected a few openmdao examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github OpenMDAO / OpenMDAO-Framework / openmdao.main / src / openmdao / main / assembly.py View on Github external
of its children that are local to the current MPI process.
        """
        all_locs = set()
        all_locs.update(self.list_inputs())
        all_locs.update(self.list_outputs())

        for s in [self._system] + list(self._system.local_subsystems(recurse=True)):
            if isinstance(s, SimpleSystem):
                try:
                    obj = self.get(s.name)
                except:
                    continue
                if has_interface(obj, IAssembly):
                    all_locs.update(['.'.join([obj.name, n])
                                          for n in obj.get_all_local_vars()])
                elif has_interface(obj, IComponent):
                    lvars = ['.'.join([obj.name, n])
                                          for n in obj.list_inputs() +
                                                   obj.list_outputs()]
                    for i, v in enumerate(lvars):
                        if v in s.distrib_idxs:
                            lvars[i] = (v,)  # wrap in tuple to indicate its a distrib var
                    all_locs.update(lvars)

                elif isinstance(s, ParamSystem):
                    all_locs.add(s.name)

        return all_locs
github OpenMDAO / OpenMDAO-Framework / openmdao.main / src / openmdao / main / datatypes / instance.py View on Github external
default_value = None
        try:
            iszopeiface = issubclass(klass, zope.interface.Interface)
        except TypeError:
            iszopeiface = False
            if not isclass(klass):
                default_value = klass
                klass = klass.__class__

        metadata.setdefault('copy', 'deep')

        self._allow_none = allow_none
        self.klass = klass

        if has_interface(klass, IContainer) or \
           (isclass(klass) and IContainer.implementedBy(klass)):
            self._is_container = True
        else:
            self._is_container = False

        if iszopeiface:
            self._instance = None
            self.factory = factory
            self.args = args
            self.kw = kw
        else:
            self._instance = traits.api.Instance(klass=klass, allow_none=allow_none,
                                      factory=factory, args=args, kw=kw,
                                      **metadata)
            if default_value:
                self._instance.default_value = default_value
github OpenMDAO / OpenMDAO-Framework / openmdao.main / src / openmdao / main / variable.py View on Github external
def __init__(self, default_value=NoDefaultSpecified, **metadata):
        if 'vartypename' not in metadata:
            metadata['vartypename'] = self.__class__.__name__

        is_vt = False
        # force default value to a value that will always be different
        # than any value assigned to the variable so that the callback
        # will always fire the first time the variable is set.
        if metadata['vartypename'] != 'Slot' and metadata.get('required') == True:
            if default_value is not NoDefaultSpecified:
                is_vt = has_interface(default_value, IVariableTree)
                if not is_vt:
                    # set a marker in the metadata that we can check for later
                    # since we don't know the variable name yet and can't generate
                    # a good error message from here.
                    metadata['_illegal_default_'] = True

            if not is_vt:
                default_value = _missing
        super(Variable, self).__init__(default_value=default_value, **metadata)
github OpenMDAO / OpenMDAO-Framework / openmdao.main / src / openmdao / main / workflow.py View on Github external
except:
                print "Unexpected error:", sys.exc_info()[0]
                import traceback
                tb = traceback.format_exc()
                print tb
                raise

            for output_name, aliases in successors:


                # From Bret: it does make sense to skip subdrivers like you said, except for the
                #      case where a driver has actual outputs of its own.  So you may have to keep
                #  subdriver successors if the edge between the subdriver and the successor
                #  is an actual data connection.
                # look at the edge metadata to see if there's maybe a 'conn' in there for real connections.
                if has_interface(comp, IDriver):
                    if not is_connection(driver._reduced_graph, comp.name, output_name):
                        continue

                if '.in' in output_name: # look for something that is not a pseudo input
                    for n in aliases:
                        if not ".in" in n:
                            output_name = n
                            break
                #output_name = prefix + output_name
                if output_name not in outputs and self._check_path(prefix + output_name, includes, excludes) :
                    self._rec_outputs.append(output_name)
                    outputs.append(output_name)
                    #outputs.append(prefix + output_name)
                    #self._rec_all_outputs.append(output_name)

        for cname in driver._ordering:
github OpenMDAO / OpenMDAO-Framework / openmdao.main / src / openmdao / main / systems.py View on Github external
shared_int_nodes = ograph.internal_nodes(full, shared=True)
        #ograph.add_node(tuple(nodes), comp='opaque')
        collapse_nodes(ograph, tuple(nodes), int_nodes)

        super(OpaqueSystem, self).__init__(scope, ograph, tuple(nodes))

        graph = pgraph.subgraph(shared_int_nodes)

        dests = set()
        nodeset = set()
        internal_comps = set()
        subdrivers = []
        for n in nodes:
            obj = getattr(scope, n, None)
            if obj is not None:
                if has_interface(obj, IDriver):
                    internal_comps.update([c.name for c in obj.iteration_set()])
                    subdrivers.append(obj)
                else:
                    internal_comps.add(n)

        for node in self._in_nodes:
            for d in node[1]:
                cname, _, vname = d.partition('.')
                if vname and cname in internal_comps and node not in nodeset:
                    dests.add((d, node))
                    nodeset.add(node)

        # sort so that base vars will be before subvars
        dests = sorted(dests)

        graph.collapse_subdrivers([], subdrivers)
github OpenMDAO / OpenMDAO-Framework / openmdao.main / src / openmdao / main / pseudocomp.py View on Github external
def _get_new_name(parent):
    while not has_interface(parent, IAssembly):
        parent = parent.parent

    return parent.new_pseudo_name()
github OpenMDAO / OpenMDAO-Framework / openmdao.main / src / openmdao / main / assembly.py View on Github external
def _check_input_collisions(self, graph):
        dests = set([v for u, v in graph.list_connections() if
                        'drv_conn_ext' not in graph[u][v] and
                        'drv_conn'  not in graph[u][v]])
        allbases = set([base_var(graph, v) for v in dests])
        unconnected_bases = allbases - dests
        connected_bases = allbases - unconnected_bases

        collisions = []
        for drv in chain([self._top_driver],
                          self._top_driver.subdrivers(recurse=True)):
            if has_interface(drv, IHasParameters):
                for target in drv.list_param_targets():
                    tbase = base_var(graph, target)
                    if target == tbase:  # target is a base var
                        if target in allbases:
                            collisions.append("%s in %s"
                                              % (target, drv.get_pathname()))
                    else:  # target is a sub var
                        if target in dests or tbase in connected_bases:
                            collisions.append("%s in %s"
                                              % (target, drv.get_pathname()))

        if collisions:
            self.raise_exception("The following parameters collide with"
                                 " connected inputs: %s" % ','.join(collisions),
                                 RuntimeError)
github OpenMDAO / OpenMDAO-Framework / openmdao.main / src / openmdao / main / component.py View on Github external
def _pre_execute(self):
        """Prepares for execution by calling various initialization methods
        if necessary.

        Overrides of this function must call this version.
        """

        if self._call_cpath_updated:
            self.cpath_updated()

        if self._new_config:
            self._setup()

        if self.parent is None and has_interface(self, IAssembly):
            self.configure_recording(self.recording_options)
github OpenMDAO / OpenMDAO-Framework / openmdao.main / src / openmdao / main / systems.py View on Github external
def _create_simple_sys(scope, graph, name):
    """Given a Component or Variable node, create the
    appropriate type of simple System.
    """
    comp = getattr(scope, name, None)

    if has_interface(comp, ISolver):
        sub = SolverSystem(graph, comp)
    elif has_interface(comp, IDriver):
        from openmdao.main.driver import Driver
        if comp.__class__ == Driver:
            sub = TransparentDriverSystem(graph, comp)
        else:
            sub = FiniteDiffDriverSystem(graph, comp)
    elif has_interface(comp, IAssembly):
        sub = AssemblySystem(scope, graph, name)
    elif has_interface(comp, IPseudoComp) and comp._pseudo_type=='constraint' \
               and comp._subtype == 'equality':
        sub = EqConstraintSystem(scope, graph, name)
    elif has_interface(comp, IComponent):
        sub = SimpleSystem(scope, graph, name)
    elif graph.node[name].get('comp') == 'param':
        sub = ParamSystem(scope, graph, name)
    elif graph.node[name].get('comp') == 'invar':
        sub = InVarSystem(scope, graph, name)
    elif graph.node[name].get('comp') == 'outvar':
        sub = OutVarSystem(scope, graph, name)
    elif graph.node[name].get('comp') == 'dumbvar':
        sub = VarSystem(scope, graph, name)
    else:
        raise RuntimeError("don't know how to create a System for '%s'" % name)
github OpenMDAO / OpenMDAO-Framework / openmdao.main / src / openmdao / main / assembly.py View on Github external
def get_all_local_vars(self):
        """Return the set of all variables in this Assembly and any
        of its children that are local to the current MPI process.
        """
        all_locs = set()
        all_locs.update(self.list_inputs())
        all_locs.update(self.list_outputs())

        for s in [self._system] + list(self._system.local_subsystems(recurse=True)):
            if isinstance(s, SimpleSystem):
                try:
                    obj = self.get(s.name)
                except:
                    continue
                if has_interface(obj, IAssembly):
                    all_locs.update(['.'.join([obj.name, n])
                                          for n in obj.get_all_local_vars()])
                elif has_interface(obj, IComponent):
                    lvars = ['.'.join([obj.name, n])
                                          for n in obj.list_inputs() +
                                                   obj.list_outputs()]
                    for i, v in enumerate(lvars):
                        if v in s.distrib_idxs:
                            lvars[i] = (v,)  # wrap in tuple to indicate its a distrib var
                    all_locs.update(lvars)

                elif isinstance(s, ParamSystem):
                    all_locs.add(s.name)

        return all_locs