Create a simple ForceField object for hydrocarbons based on the graph.
15117
def setup_hydrocarbon_ff(graph):
    """"""
    # A) Define parameters.
    # the bond parameters:
    bond_params = {
        (6, 1): 310*kcalmol/angstrom**2,
        (6, 6): 220*kcalmol/angstrom**2,
    }
    # for every (a, b), also add (b, a)
    for key, val in list(bond_params.items()):
        if key[0] != key[1]:
            bond_params[(key[1], key[0])] = val
    # the bend parameters
    bend_params = {
        (1, 6, 1): 35*kcalmol/rad**2,
        (1, 6, 6): 30*kcalmol/rad**2,
        (6, 6, 6): 60*kcalmol/rad**2,
    }
    # for every (a, b, c), also add (c, b, a)
    for key, val in list(bend_params.items()):
        if key[0] != key[2]:
            bend_params[(key[2], key[1], key[0])] = val

    # B) detect all internal coordinates and corresponding energy terms.
    terms = []
    # bonds
    for i0, i1 in graph.edges:
        K = bond_params[(graph.numbers[i0], graph.numbers[i1])]
        terms.append(BondStretchTerm(K, i0, i1))
    # bends (see b_bending_angles.py for the explanation)
    for i1 in range(graph.num_vertices):
        n = list(graph.neighbors[i1])
        for index, i0 in enumerate(n):
            for i2 in n[:index]:
                K = bend_params[(graph.numbers[i0], graph.numbers[i1], graph.numbers[i2])]
                terms.append(BendAngleTerm(K, i0, i1, i2))

    # C) Create and return the force field
    return ForceField(terms)
81806
private JComponent createJComponent(final DirectedGraph<Object, JobGraphLink> graph) {
        final int vertexCount = graph.getVertexCount();
        logger.debug("Rendering graph with {} vertices", vertexCount);

        final JobGraphLayoutTransformer layoutTransformer = new JobGraphLayoutTransformer(_analysisJobBuilder, graph);
        final Dimension preferredSize = layoutTransformer.getPreferredSize();

        final StaticLayout<Object, JobGraphLink> layout = new StaticLayout<>(graph, layoutTransformer, preferredSize);

        final Collection<Object> vertices = graph.getVertices();
        for (final Object vertex : vertices) {
            // manually initialize all vertices
            layout.apply(vertex);
        }

        if (!vertices.isEmpty() && !layoutTransformer.isTransformed()) {
            throw new IllegalStateException("Layout transformer was never invoked!");
        }

        final VisualizationViewer<Object, JobGraphLink> visualizationViewer =
                new VisualizationViewer<>(layout, preferredSize);
        visualizationViewer.setTransferHandler(new TransferHandler() {

            private static final long serialVersionUID = 1L;

            public boolean canImport(final TransferSupport support) {
                return support.isDataFlavorSupported(DragDropUtils.MODEL_DATA_FLAVOR);
            }

            public boolean importData(final TransferSupport support) {
                final Transferable transferable = support.getTransferable();

                final Object data;
                try {
                    data = transferable.getTransferData(DragDropUtils.MODEL_DATA_FLAVOR);
                } catch (final Exception ex) {
                    logger.warn("Unexpected error while dropping data", ex);
                    return false;
                }

                if (data == null) {
                    return false;
                }

                final Point dropPoint = support.getDropLocation().getDropPoint();

                if (data instanceof Table) {
                    final Table table = (Table) data;
                    // position the table
                    JobGraphMetadata.setPointForTable(_analysisJobBuilder, table, dropPoint.x, dropPoint.y);
                    _analysisJobBuilder.addSourceColumns(table.getColumns());
                }

                if (data instanceof Column) {
                    final Column column = (Column) data;
                    final Table table = column.getTable();
                    final List<MetaModelInputColumn> columnsOfSameTable =
                            _analysisJobBuilder.getSourceColumnsOfTable(table);
                    if (columnsOfSameTable.isEmpty()) {
                        // the table is new - position it
                        JobGraphMetadata.setPointForTable(_analysisJobBuilder, table, dropPoint.x, dropPoint.y);
                    }
                    _analysisJobBuilder.addSourceColumn(column);
                }

                if (data instanceof ComponentDescriptor<?>) {
                    final ComponentDescriptor<?> descriptor = (ComponentDescriptor<?>) data;
                    final Map<String, String> metadata = JobGraphMetadata.createMetadataProperties(dropPoint);
                    _analysisJobBuilder.addComponent(descriptor, null, null, metadata);
                }
                return true;
            }

        });

        GraphUtils.applyStyles(visualizationViewer);
        visualizationViewer.addPreRenderPaintable(new Paintable() {
            @Override
            public boolean useTransform() {
                return false;
            }

            @Override
            public void paint(final Graphics g) {
                final GradientPaint paint = new GradientPaint(0, 0, WidgetUtils.BG_COLOR_BRIGHTEST, 0,
                        visualizationViewer.getHeight(), WidgetUtils.BG_COLOR_BRIGHTEST);
                if (g instanceof Graphics2D) {
                    final Graphics2D g2d = (Graphics2D) g;
                    g2d.setPaint(paint);
                } else {
                    g.setColor(WidgetUtils.BG_COLOR_BRIGHT);
                }
                g.fillRect(0, 0, visualizationViewer.getWidth(), visualizationViewer.getHeight());

                final Dimension size = _panel.getSize();
                if (size.height < adjuster.adjust(300) || size.width < adjuster.adjust(500)) {
                    // don't show the background hints - it will be too
                    // disturbing
                    return;
                }

                final String showCanvasHints = _userPreferences.getAdditionalProperties()
                        .get(JobGraphTransformers.USER_PREFERENCES_PROPERTY_SHOW_CANVAS_HINTS);
                if ("false".equals(showCanvasHints)) {
                    // don't show the background hints - the user has decided
                    // not to have them.
                    return;
                }

                String title;
                String subTitle;
                String imagePath;

                g.setColor(WidgetUtils.BG_COLOR_MEDIUM);
                if (_analysisJobBuilder.getSourceColumns().size() == 0) {
                    title = "Select source ...";
                    subTitle = "Pick table/columns in the tree to the left.\n"
                            + "You can drag it onto this canvas with your mouse.";
                    imagePath = "images/window/canvas-bg-table.png";
                } else if (_analysisJobBuilder.getComponentCount() == 0) {
                    title = "Start building ...";
                    subTitle = "Add components to your job. Right-click the canvas\n"
                            + "to explore the library of available components.";
                    imagePath = "images/window/canvas-bg-plus.png";
                } else if (graph.getEdgeCount() == 0) {
                    title = "Connect the pieces ...";
                    subTitle = "Right-click the source table and select 'Link to ...'.\n"
                            + "This directs the flow of data to the component.";
                    imagePath = "images/window/canvas-bg-connect.png";
                } else if (_analysisJobBuilder.getResultProducingComponentBuilders().size() == 0
                        && _analysisJobBuilder.getConsumedOutputDataStreamsJobBuilders().size() == 0
                        && _analysisJobBuilder.getComponentCount() <= 3) {
                    title = "Your job is almost ready.";
                    subTitle = "Jobs need to either 'Analyze' or 'Write' something.\n"
                            + "So add one or more such components.";
                    imagePath = "images/window/canvas-bg-plus.png";
                } else {
                    title = null;
                    subTitle = null;
                    imagePath = null;

                    try {
                        if (_analysisJobBuilder.isConfigured(true)) {
                            title = "Ready to execute";
                            subTitle =
                                    "Click the 'Execute' button in the upper-right\ncorner when you're ready to run the job.";
                            imagePath = "images/window/canvas-bg-execute.png";
                            g.drawImage(ImageManager.get().getImage("images/window/canvas-bg-execute-hint.png"),
                                    size.width - adjuster.adjust(175), 0, null);
                        } else {
                            title = "Configure the job ...";
                            subTitle = "Job is not correctly configured";
                            imagePath = "images/window/canvas-bg-error.png";
                        }
                    } catch (final Exception ex) {
                        logger.debug("Job not correctly configured", ex);
                        final String errorMessage;
                        if (ex instanceof UnconfiguredConfiguredPropertyException) {
                            final UnconfiguredConfiguredPropertyException unconfiguredConfiguredPropertyException =
                                    (UnconfiguredConfiguredPropertyException) ex;
                            final ConfiguredPropertyDescriptor configuredProperty =
                                    unconfiguredConfiguredPropertyException.getConfiguredProperty();
                            final ComponentBuilder componentBuilder =
                                    unconfiguredConfiguredPropertyException.getComponentBuilder();
                            title = "Configure " + "'" + LabelUtils.getLabel(componentBuilder) + "' ...";
                            errorMessage = "Please set '" + configuredProperty.getName() + "' to continue";
                        } else {
                            title = "Something went wrong ...";
                            errorMessage = ex.getMessage();
                        }
                        subTitle = errorMessage;
                        imagePath = "images/window/canvas-bg-error.png";
                    }
                }

                final int yOffset = size.height - adjuster.adjust(150);
                final int xOffset = adjuster.adjust(150);

                final float titleFontSize;
                final float subTitleFontSize;
                if (size.width < adjuster.adjust(650)) {
                    titleFontSize = adjuster.adjust(30f);
                    subTitleFontSize = adjuster.adjust(17f);
                } else {
                    titleFontSize = adjuster.adjust(35f);
                    subTitleFontSize = adjuster.adjust(20f);
                }

                if (title != null) {
                    g.setFont(WidgetUtils.FONT_BANNER.deriveFont(titleFontSize));
                    g.drawString(title, xOffset, yOffset);
                }

                if (subTitle != null) {
                    final String[] lines = subTitle.split("\n");
                    g.setFont(WidgetUtils.FONT_BANNER.deriveFont(subTitleFontSize));
                    int y = yOffset + adjuster.adjust(10);
                    for (final String line : lines) {
                        y = y + adjuster.adjust(30);
                        g.drawString(line, xOffset, y);
                    }
                }

                if (imagePath != null) {
                    g.drawImage(ImageManager.get().getImage(imagePath), xOffset - adjuster.adjust(120),
                            yOffset - adjuster.adjust(30), null);
                }
            }
        });

        final JobGraphContext graphContext = new JobGraphContext(this, visualizationViewer, _analysisJobBuilder);

        final JobGraphActions actions = new JobGraphActions(graphContext, _windowContext, _presenterRendererFactory,
                _componentConfigurationDialogs, _tableConfigurationDialogs);
        final JobGraphLinkPainter linkPainter = new JobGraphLinkPainter(graphContext, actions);

        final JobGraphLinkPainterMousePlugin linkPainterMousePlugin =
                new JobGraphLinkPainterMousePlugin(linkPainter, graphContext);
        final GraphMouse graphMouse = visualizationViewer.getGraphMouse();
        if (graphMouse instanceof PluggableGraphMouse) {
            final PluggableGraphMouse pluggableGraphMouse = (PluggableGraphMouse) graphMouse;
            pluggableGraphMouse.add(linkPainterMousePlugin);
        }

        final JobGraphMouseListener graphMouseListener =
                new JobGraphMouseListener(graphContext, linkPainter, actions, _windowContext);

        visualizationViewer.addGraphMouseListener(graphMouseListener);
        visualizationViewer.addMouseListener(graphMouseListener);

        final RenderContext<Object, JobGraphLink> renderContext = visualizationViewer.getRenderContext();

        final JobGraphTransformers transformers = new JobGraphTransformers(graph, _userPreferences, _highlighedVertexes);

        // instrument the render context with all our transformers and stuff
        renderContext.setVertexFontTransformer(transformers.getVertexFontTransformer());
        renderContext.setVertexLabelTransformer(JobGraphTransformers.VERTEX_LABEL_TRANSFORMER);
        renderContext.setEdgeArrowPredicate(JobGraphTransformers.EDGE_ARROW_PREDICATE);
        renderContext.setEdgeArrowTransformer(JobGraphTransformers.EDGE_ARROW_TRANSFORMER);
        renderContext.setEdgeLabelTransformer(JobGraphTransformers.EDGE_LABEL_TRANSFORMER);
        renderContext.setEdgeShapeTransformer(transformers.getEdgeShapeTransformer());
        renderContext.setEdgeLabelClosenessTransformer(JobGraphTransformers.EDGE_LABEL_CLOSENESS_TRANSFORMER);
        renderContext.setEdgeLabelRenderer(transformers.getEdgeLabelRenderer());
        renderContext.setVertexIconTransformer(JobGraphTransformers.VERTEX_ICON_TRANSFORMER);
        renderContext.setVertexShapeTransformer(JobGraphTransformers.VERTEX_SHAPE_TRANSFORMER);

        final JButton graphPreferencesButton = createGraphPreferencesButton();
        visualizationViewer.setLayout(new BorderLayout());
        visualizationViewer.add(DCPanel.flow(Alignment.RIGHT, 0, 0, graphPreferencesButton), BorderLayout.SOUTH);

        // we save the values of the scrollbars in order to allow refreshes to
        // retain scroll position.
        final GraphZoomScrollPane scrollPane = new GraphZoomScrollPane(visualizationViewer);
        scrollPane.setCorner(new DCPanel(WidgetUtils.COLOR_DEFAULT_BACKGROUND));
        if (_scrollHorizontal > 0) {
            setScrollbarValue(scrollPane.getHorizontalScrollBar(), _scrollHorizontal);
        }
        if (_scrollVertical > 0) {
            setScrollbarValue(scrollPane.getVerticalScrollBar(), _scrollVertical);
        }
        final AdjustmentListener adjustmentListener = e -> {
            _scrollHorizontal = scrollPane.getHorizontalScrollBar().getValue();
            _scrollVertical = scrollPane.getVerticalScrollBar().getValue();
        };
        scrollPane.getHorizontalScrollBar().addAdjustmentListener(adjustmentListener);
        scrollPane.getVerticalScrollBar().addAdjustmentListener(adjustmentListener);
        new JobGraphBindingsManager(graphContext, actions, scrollPane).register();

        return scrollPane;
    }
89778
def _instantiate_app(self, target_cls, kwargs):
    """"""
    parse_context = ParseContext(kwargs['address'].spec_path, dict())
    bundleprops_factory = Bundle(parse_context)
    kwargs['bundles'] = [
      bundleprops_factory.create_bundle_props(bundle)
      for bundle in kwargs['bundles']
    ]

    return target_cls(build_graph=self, **kwargs)
178250
def import_graph(self, t_input=None, scope='import', forget_xy_shape=True):
    """"""
    graph = tf.get_default_graph()
    assert graph.unique_name(scope, False) == scope, (
        'Scope "%s" already exists. Provide explicit scope names when '
        'importing multiple instances of the model.') % scope
    t_input, t_prep_input = self.create_input(t_input, forget_xy_shape)
    tf.import_graph_def(
        self.graph_def, {self.input_name: t_prep_input}, name=scope)
    self.post_import(scope)
1130060
def write_model(self, file, model, pretty=False):
        
        ET.register_namespace('mathml', MATHML_NS)
        ET.register_namespace('xhtml', XHTML_NS)
        ET.register_namespace('fbc', FBC_V2)

        # Load compound information
        compound_name = {}
        compound_properties = {}
        for compound in model.compounds:
            compound_name[compound.id] = (
                compound.name if compound.name is not None else compound.id)
            compound_properties[compound.id] = compound.properties

        model_reactions = set(model.model)

        reaction_properties = {}
        biomass_id = None
        for r in model.reactions:
            if (model_reactions is not None and
                    r.id not in model_reactions):
                continue

            reaction_id = util.create_unique_id(
                self._make_safe_id(r.id), reaction_properties)
            if r.id == model.biomass_reaction:
                biomass_id = reaction_id

            reaction_properties[reaction_id] = r.properties

        # Add exchange reactions to reaction_properties,
        # also add flux limit info to flux_limits
        flux_limits = {}
        for compound, reaction_id, lower, upper in itervalues(model.exchange):
            # Create exchange reaction
            if reaction_id is None:
                reaction_id = create_exchange_id(reaction_properties, compound)
            reaction_id = util.create_unique_id(
                self._make_safe_id(reaction_id), reaction_properties)

            reaction_properties[reaction_id] = {
                'id': reaction_id,
                'equation': Reaction(Direction.Both, {compound: -1})
            }

            if lower is None:
                lower = -model.default_flux_limit
            if upper is None:
                upper = model.default_flux_limit
            flux_limits[reaction_id] = (lower, upper)

            # Create a dummy properties dict for undefined compounds
            if compound.name not in compound_properties:
                compound_properties[compound.name] = {
                    'id': compound.name
                }

        root = ET.Element(self._sbml_tag('sbml'))
        root.set(self._sbml_tag('level'), '3')
        root.set(self._sbml_tag('version'), '1')
        root.set(_tag('required', FBC_V2), 'false')
        if model.version_string is not None:
            notes_tag = ET.SubElement(root, self._sbml_tag('notes'))
            body_tag = ET.SubElement(notes_tag, _tag('body', XHTML_NS))
            self._add_properties_notes(
                body_tag, {'model version': model.version_string})

        model_tag = ET.SubElement(root, self._sbml_tag('model'))
        model_tag.set(_tag('strict', FBC_V2), 'true')
        if model.name is not None:
            model_tag.set(self._sbml_tag('name'), model.name)

        # Build mapping from Compound to species ID
        model_compartments = {}
        model_species = {}
        species_ids = set()
        for _, properties in iteritems(reaction_properties):
            for compound, _ in properties['equation'].compounds:
                if compound in model_species:
                    continue

                # Create a dummy properties dict for undefined compounds
                if compound.name not in compound_properties:
                    compound_properties[compound.name] = {
                        'id': compound.name
                    }

                compound_id = util.create_unique_id(
                    self._make_safe_id(compound.name), species_ids)
                model_species[compound] = compound_id
                species_ids.add(compound_id)
                if compound.compartment not in model_compartments:
                    model_compartments[
                        compound.compartment] = 'C_' + util.create_unique_id(
                            self._make_safe_id(compound.compartment),
                            model_compartments)

        # Create list of compartments
        compartments = ET.SubElement(
            model_tag, self._sbml_tag('listOfCompartments'))
        for _, compartment_id in iteritems(model_compartments):
            compartment_tag = ET.SubElement(
                compartments, self._sbml_tag('compartment'))
            compartment_tag.set(self._sbml_tag('id'), compartment_id)
            compartment_tag.set(self._sbml_tag('constant'), 'true')

        # Create list of species
        species_list = ET.SubElement(
            model_tag, self._sbml_tag('listOfSpecies'))
        for species, species_id in sorted(
                iteritems(model_species), key=lambda x: x[1]):
            species_tag = ET.SubElement(species_list,
                                        self._sbml_tag('species'))
            species_tag.set(self._sbml_tag('id'), 'M_' + species_id)
            species_tag.set(
                self._sbml_tag('name'),
                compound_name.get(species.name, species.name))
            species_tag.set(
                self._sbml_tag('compartment'),
                model_compartments[species.compartment])
            species_tag.set(self._sbml_tag('constant'), 'false')
            species_tag.set(self._sbml_tag('boundaryCondition'), 'false')
            species_tag.set(self._sbml_tag('hasOnlySubstanceUnits'), 'true')
            if 'charge' in compound_properties[species.name]:
                species_tag.set(_tag('charge', FBC_V2), text_type(
                    compound_properties[species.name]['charge']))
            if 'formula' in compound_properties[species.name]:
                species_tag.set(_tag(
                    'chemicalFormula', FBC_V2), text_type(
                        compound_properties[species.name]['formula']))

            notes_tag = ET.SubElement(species_tag, self._sbml_tag('notes'))
            body_tag = ET.SubElement(notes_tag, _tag('body', XHTML_NS))
            self._add_properties_notes(
                body_tag, compound_properties[species.name])

        params_list = ET.SubElement(
            model_tag, self._sbml_tag('listOfParameters'))

        # Create mapping for reactions containing flux limit definitions
        for rxn_id, lower_lim, upper_lim in itervalues(model.limits):
            flux_limits[rxn_id] = lower_lim, upper_lim

        params = {}
        gene_ids = {}

        if biomass_id is not None:
            self._add_fbc_objective(model_tag, biomass_id)

        # Create list of reactions
        reactions = ET.SubElement(model_tag, self._sbml_tag('listOfReactions'))
        for eq_id, properties in sorted(iteritems(reaction_properties)):
            reaction_tag = ET.SubElement(reactions, self._sbml_tag('reaction'))
            equation = properties['equation']

            reaction_tag.set(self._sbml_tag('id'), 'R_' + eq_id)
            if 'name' in properties:
                reaction_tag.set(self._sbml_tag('name'), properties['name'])
            reaction_tag.set(self._sbml_tag('reversible'), text_type(
                equation.direction == Direction.Both).lower())
            reaction_tag.set(self._sbml_tag('fast'), 'false')
            lower_str, upper_str = self._get_flux_bounds(
                eq_id, model, flux_limits, equation)

            params[upper_str] = 'P_'+self._make_safe_numerical_id(upper_str)
            params[lower_str] = 'P_'+self._make_safe_numerical_id(lower_str)
            reaction_tag.set(
                _tag('upperFluxBound', FBC_V2), params[upper_str])
            reaction_tag.set(
                _tag('lowerFluxBound', FBC_V2), params[lower_str])

            if 'genes' in properties:
                self._add_gene_associations(
                    eq_id, properties['genes'], gene_ids, reaction_tag)

            if any(value < 0 for _, value in equation.compounds):
                reactants = ET.SubElement(
                    reaction_tag, self._sbml_tag('listOfReactants'))

            if any(value > 0 for _, value in equation.compounds):
                products = ET.SubElement(
                    reaction_tag, self._sbml_tag('listOfProducts'))

            for compound, value in sorted(equation.compounds):
                dest_list = reactants if value < 0 else products
                spec_ref = ET.SubElement(
                    dest_list, self._sbml_tag('speciesReference'))
                spec_ref.set(
                    self._sbml_tag('species'), 'M_' + model_species[compound])
                spec_ref.set(
                    self._sbml_tag('constant'), 'true')
                spec_ref.set(
                    self._sbml_tag('stoichiometry'), text_type(abs(value)))

            notes_tag = ET.SubElement(reaction_tag, self._sbml_tag('notes'))
            body_tag = ET.SubElement(notes_tag, _tag('body', XHTML_NS))
            self._add_properties_notes(body_tag, reaction_properties[eq_id])

            if self._cobra_flux_bounds is True:
                # Create COBRA-compliant parameter list
                kl_tag = ET.SubElement(
                    reaction_tag, self._sbml_tag('kineticLaw'))
                math_tag = ET.SubElement(kl_tag, self._sbml_tag('math'))
                ci_tag = ET.SubElement(math_tag, _tag('ci', MATHML_NS))
                ci_tag.text = 'FLUX_VALUE'
                param_list = ET.SubElement(
                    kl_tag, self._sbml_tag('listOfParameters'))

                ET.SubElement(param_list, self._sbml_tag('parameter'), {
                    self._sbml_tag('id'): 'LOWER_BOUND',
                    self._sbml_tag('name'): 'LOWER_BOUND',
                    self._sbml_tag('value'): lower_str,
                    self._sbml_tag('constant'): 'true'
                })
                ET.SubElement(param_list, self._sbml_tag('parameter'), {
                    self._sbml_tag('id'): 'UPPER_BOUND',
                    self._sbml_tag('name'): 'UPPER_BOUND',
                    self._sbml_tag('value'): upper_str,
                    self._sbml_tag('constant'): 'true'
                })

        for val, id in iteritems(params):
            param_tag = ET.SubElement(params_list, self._sbml_tag('parameter'))
            param_tag.set(self._sbml_tag('id'), id)
            param_tag.set(self._sbml_tag('value'), val)
            param_tag.set(self._sbml_tag('constant'), 'true')

        self._add_gene_list(model_tag, gene_ids)

        tree = ET.ElementTree(root)
        if pretty:
            self._indent(root)

        write_options = dict(
            encoding='utf-8',
            default_namespace=self._namespace)
        if PY3:
            write_options['encoding'] = 'unicode'
        tree.write(file, **write_options)
1254626
private static CyclicVertexSearch makeSearcher(int[][] graph) {

        if (graph == null) throw new NullPointerException("graph[][] must not be null");

        // if the molecule has 64 or less atoms we can use single 64 bit long
        // values to represent our sets of vertices
        if (graph.length <= 64) {
            return new RegularCyclicVertexSearch(graph);
        } else {
            return new JumboCyclicVertexSearch(graph);
        }
    }
692925
def _create_field_specification(schema_graph, graphql_types, field_type_overrides,
                                hidden_classes, cls_name):
    """"""
    def field_maker_func():
        """Create and return the fields for the given GraphQL type."""
        result = EXTENDED_META_FIELD_DEFINITIONS.copy()
        result.update(OrderedDict([
            (name, GraphQLField(value))
            for name, value in sorted(six.iteritems(_get_fields_for_class(
                schema_graph, graphql_types, field_type_overrides, hidden_classes, cls_name)),
                key=lambda x: x[0])
        ]))
        return result

    return field_maker_func
593955
def create_apply_graph(self, signature, input_tensors, name):
    """"""
    signature_def = self._meta_graph.signature_def.get(signature)
    meta_graph = meta_graph_pb2.MetaGraphDef()
    meta_graph.CopyFrom(self._meta_graph)
    apply_graph = tf_v1.get_default_graph()
    infeed_map = tensor_info.build_input_map(signature_def.inputs,
                                             input_tensors)

    # Build a input map to feed when importing the apply-graph by augmenting the
    # state_map with the input args. This allows an input to override a tensor
    # from the state-graph.
    feed_map = dict(self._state_map)
    # If we are applying the module in a function with a TPUReplicateContext, we
    # must capture the state tensors in generating our feedmap and prune out
    # assign ops. Function graph semantics are different in that all ops are
    # executed regardless of dependency.
    # TODO(b/112575006): The following adds functionality of function call
    # within a TPU context. Work to generalize this for all function calls is
    # ongoing.
    if self._is_tpu_graph_function():
      for k, v in self._state_map.items():
        feed_map[k] = apply_graph.capture(v)
      meta_graph_lib.prune_unused_nodes(meta_graph, signature_def)
      # After we prune the metagraph def, we might need to prune away
      # infeeds which no longer exist.
      meta_graph_lib.prune_feed_map(meta_graph, infeed_map)
    elif apply_graph.building_function:
      raise NotImplementedError(
          "Using TF-Hub module within a TensorFlow defined function "
          "is currently not supported.")

    # As state ops in the apply graph are unused, replace them with Placeholders
    # so that in a heirarchical instantiation, apply_graph state ops are
    # ignored.
    replace_apply_state(meta_graph,
                        list_registered_stateful_ops_without_inputs(), feed_map)
    feed_map.update(infeed_map)

    # Make state tensors enter the current context. This way the Module can be
    # applied inside a control flow structure such as a while_loop.
    control_flow = apply_graph._get_control_flow_context()  # pylint: disable=protected-access
    if control_flow:
      for key, value in sorted(feed_map.items()):
        feed_map[key] = control_flow.AddValue(value)

    # Don't mark the name as used at this point - import_scoped_meta_graph will
    # start using it.
    absolute_scope_name = apply_graph.unique_name(name, mark_as_used=False)
    relative_scope_name = absolute_scope_name.split("/")[-1]

    import_collections = [
        # In most cases ASSET_FILEPATHS are only used for the TABLE_INITIALIZERS
        # ops, however one could create a graph that uses an asset at any other
        # time. As so everytime we bring the tensor with that has the asset
        # filename we must annotate it as so, so later re-exports have that
        # semantic information and can handle it.
        tf_v1.GraphKeys.ASSET_FILEPATHS,
        tf_v1.GraphKeys.COND_CONTEXT,
        tf_v1.GraphKeys.WHILE_CONTEXT,
    ]
    if self._trainable:
      import_collections.extend([tf_v1.GraphKeys.UPDATE_OPS])

    meta_graph_lib.filter_collections(meta_graph, import_collections)
    meta_graph_lib.prefix_shared_name_attributes(meta_graph,
                                                 absolute_scope_name)
    if len(meta_graph.collection_def) and self._is_tpu_graph_function():
      raise NotImplementedError(
          "Applying modules with collections inside TPU functions is not "
          "supported.")

    tf_v1.train.import_meta_graph(
        meta_graph,
        input_map=feed_map,
        import_scope=relative_scope_name)
    fix_colocation_after_import(input_map=feed_map,
                                absolute_import_scope=absolute_scope_name)

    def get_tensor(name):
      # When trying to output an input tensor there are no nodes created within
      # the apply scope. So one must look into the input map.
      try:
        return feed_map[name]
      except KeyError:
        return apply_graph.get_tensor_by_name(
            meta_graph_lib.prepend_name_scope(
                name, import_scope=absolute_scope_name))

    return tensor_info.build_output_map(signature_def.outputs, get_tensor)
995945
def create_from_flux_points(cls, txtfile):
        """"""

        tab = Table.read(txtfile, format='ascii.ecsv')
        dnde_unit = u.ph / (u.MeV * u.cm ** 2 * u.s)
        loge = np.log10(np.array(tab['e_ref'].to(u.MeV)))
        norm = np.array(tab['norm'].to(dnde_unit))
        norm_errp = np.array(tab['norm_errp'].to(dnde_unit))
        norm_errn = np.array(tab['norm_errn'].to(dnde_unit))
        norm_err = 0.5 * (norm_errp + norm_errn)
        dloge = loge[1:] - loge[:-1]
        dloge = np.insert(dloge, 0, dloge[0])
        emin = 10 ** (loge - dloge * 0.5)
        emax = 10 ** (loge + dloge * 0.5)
        ectr = 10 ** loge
        deltae = emax - emin
        flux = norm * deltae
        eflux = norm * deltae * ectr

        ones = np.ones(flux.shape)
        ref_spec = ReferenceSpec(emin, emax, ones, ones, ones, ones)

        spec_data = SpecData(ref_spec, norm, flux, eflux, norm_err)

        stephi = np.linspace(0, 1, 11)
        steplo = -np.linspace(0, 1, 11)[1:][::-1]

        loscale = 3 * norm_err
        hiscale = 3 * norm_err
        loscale[loscale > norm] = norm[loscale > norm]

        norm_vals_hi = norm[:, np.newaxis] + \
            stephi[np.newaxis, :] * hiscale[:, np.newaxis]
        norm_vals_lo = norm[:, np.newaxis] + \
            steplo[np.newaxis, :] * loscale[:, np.newaxis]

        norm_vals = np.hstack((norm_vals_lo, norm_vals_hi))
        nll_vals = 0.5 * \
            (norm_vals - norm[:, np.newaxis]) ** 2 / \
            norm_err[:, np.newaxis] ** 2

        norm_vals *= flux[:, np.newaxis] / norm[:, np.newaxis]

        return cls(norm_vals, nll_vals, spec_data, 'flux')
18205
def make_new_projection_values(self,width=160):
        
        #Make gap between residues bigger if plots have a lot of rings - each ring after the 4th
        #give extra 12.5px space
        start = timer()
        if self.topology_data.ring_number>4:
            width = width + (self.topology_data.ring_number-4)*12.5
        values = [v for v in self.nearest_points_projection.values()]
        xy_values = [v for v in self.nearest_points_coords.values()]
        coeff_value = [v for v in self.b_for_all.values()]
        energy = 100
        while energy > 0.2:
            values, energy = self.do_step(values,xy_values,coeff_value, width)
            time = timer() - start
            i=0
            xy_values =[]
            for residue in  self.nearest_points_coords:
                b = self.a.boundary.parallel_offset(self.topology_data.closest_atoms[residue][0][1]*50+50,"left",join_style=2).convex_hull
                self.nearest_points_projection[residue] = values[i]
                self.nearest_points[residue] = b.boundary.interpolate(self.nearest_points_projection[residue] % b.boundary.length)
                self.nearest_points_coords[residue] = self.nearest_points[residue].x, self.nearest_points[residue].y
                xy_values.append(self.nearest_points_coords[residue])
                i+=1
            values = [v for v in self.nearest_points_projection.values()]
            if time>30:
                self.molsize1 = self.molsize1 + self.molsize1 * 0.2 #Increase molecule svg size
                self.molsize2 = self.molsize2 + self.molsize2 * 0.2
                self.draw_molecule()
                break

        #Calculate the borders of the final image
        max_x = max(v[0] for k,v in self.nearest_points_coords.items())
        min_x = min(v[0] for k,v in self.nearest_points_coords.items())
        min_y = min(v[1] for k,v in self.nearest_points_coords.items())
        max_y = max(v[1] for k,v in self.nearest_points_coords.items())
        if min_x<0:
            self.x_dim =(max_x-min_x)+600 #600 acts as buffer
        elif max_x<self.molsize1 and min_x<0: #In case all residues are grouped on one end of the molecule
            self.x_dim = (self.molsize1-min_x)+600
        elif max_x<self.molsize1 and min_x>0:
            self.x_dim = self.molsize1+600
        else:
            self.x_dim = max_x+600
        if min_y<0:
            self.y_dim = (max_y-min_y)+400 #400 acts as buffer
        elif max_y<self.molsize2 and min_y<0:
            self.y_dim = (self.molsize2-min_y)+400
        elif max_y<self.molsize2 and min_y>0:
            self.y_dim = self.molsize2+400
        else:
            self.y_dim = max_y+400
        end = timer()
        print "Drawing molecule:"+str(end-start)
563746
def create(blocks, mode='basic', inplanes=64, cardinality=4, image_features=64, divisor=4, num_classes=1000):
    
    block_dict = {
        # 'basic': BasicBlock,
        'bottleneck': ResNeXtBottleneck
    }

    def instantiate(**_):
        return ResNeXt(block_dict[mode], blocks, inplanes=inplanes, image_features=image_features, cardinality=cardinality, divisor=divisor, num_classes=num_classes)

    return ModelFactory.generic(instantiate)
2974
def build_graph(self, image, label):
        """"""

        # In tensorflow, inputs to convolution function are assumed to be
        # NHWC. Add a single channel here.
        image = tf.expand_dims(image, 3)

        image = image * 2 - 1   # center the pixels values at zero
        # The context manager `argscope` sets the default option for all the layers under
        # this context. Here we use 32 channel convolution with shape 3x3
        with argscope(Conv2D, kernel_size=3, activation=tf.nn.relu, filters=32):
            logits = (LinearWrap(image)
                      .Conv2D('conv0')
                      .MaxPooling('pool0', 2)
                      .Conv2D('conv1')
                      .Conv2D('conv2')
                      .MaxPooling('pool1', 2)
                      .Conv2D('conv3')
                      .FullyConnected('fc0', 512, activation=tf.nn.relu)
                      .Dropout('dropout', rate=0.5)
                      .FullyConnected('fc1', 10, activation=tf.identity)())

        # a vector of length B with loss of each sample
        cost = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=label)
        cost = tf.reduce_mean(cost, name='cross_entropy_loss')  # the average cross-entropy loss

        correct = tf.cast(tf.nn.in_top_k(predictions=logits, targets=label, k=1), tf.float32, name='correct')
        accuracy = tf.reduce_mean(correct, name='accuracy')

        # This will monitor training error & accuracy (in a moving average fashion). The value will be automatically
        # 1. written to tensosrboard
        # 2. written to stat.json
        # 3. printed after each epoch
        train_error = tf.reduce_mean(1 - correct, name='train_error')
        summary.add_moving_summary(train_error, accuracy)

        # Use a regex to find parameters to apply weight decay.
        # Here we apply a weight decay on all W (weight matrix) of all fc layers
        # If you don't like regex, you can certainly define the cost in any other methods.
        wd_cost = tf.multiply(1e-5,
                              regularize_cost('fc.*/W', tf.nn.l2_loss),
                              name='regularize_loss')
        total_cost = tf.add_n([wd_cost, cost], name='total_cost')
        summary.add_moving_summary(cost, wd_cost, total_cost)

        # monitor histogram of all weight (of conv and fc layers) in tensorboard
        summary.add_param_summary(('.*/W', ['histogram', 'rms']))
        # the function should return the total cost to be optimized
        return total_cost
707088
def _make_graph(self, max_insert):
        ''''''
        if len(self.partial_links) != 0:
            raise Error('Error in _make_graph(). Cannot continue because there are partial links')
        
        self.contig_links = {}
        for key in self.links:
            for l in self.links[key]:
                insert_size = l.insert_size()
                if insert_size <= max_insert:
                    if key not in self.contig_links:
                        self.contig_links[key] = {}
                    dirs = ''.join(l.dirs)
                    self.contig_links[key][dirs] = self.contig_links[key].get(dirs, 0) + 1
789006
def create_model(self):
        """"""

        properties = {
            'name': self.name,
            'biomass': self.biomass_reaction,
            'extracellular': self.extracellular_compartment,
            'default_compartment': self.default_compartment,
            'default_flux_limit': self.default_flux_limit
        }

        if self.context is not None:
            git_version = util.git_try_describe(self.context.basepath)
            properties['version_string'] = git_version

        model = NativeModel(properties)

        # Load compartments into model
        compartment_iter, boundaries = self.parse_compartments()
        for compartment in compartment_iter:
            model.compartments.add_entry(compartment)
        model.compartment_boundaries.update(boundaries)

        # Load compounds into model
        for compound in self.parse_compounds():
            if compound.id in model.compounds:
                existing_entry = model.compounds[compound.id]
                common_props = set(compound.properties).intersection(
                    existing_entry.properties).difference({'id'})
                if len(common_props) > 0:
                    logger.warning(
                        'Compound entry {} at {} overrides already defined'
                        ' properties: {}'.format(
                            compound.id, compound.filemark, common_props))

                properties = dict(compound.properties)
                properties.update(existing_entry.properties)
                compound = CompoundEntry(
                    properties, filemark=compound.filemark)
            model.compounds.add_entry(compound)

        # Load reactions into model
        for reaction in self.parse_reactions():
            if reaction.id in model.reactions:
                existing_entry = model.reactions[reaction.id]
                common_props = set(reaction.properties).intersection(
                    existing_entry.properties).difference({'id'})
                if len(common_props) > 0:
                    logger.warning(
                        'Reaction entry {} at {} overrides already defined'
                        ' properties: {}'.format(
                            reaction.id, reaction.filemark, common_props))

                properties = dict(reaction.properties)
                properties.update(existing_entry.properties)
                reaction = ReactionEntry(
                    properties, filemark=reaction.filemark)
            model.reactions.add_entry(reaction)

        for exchange_def in self.parse_exchange():
            model.exchange[exchange_def[0]] = exchange_def

        for limit in self.parse_limits():
            model.limits[limit[0]] = limit

        if self.has_model_definition():
            for model_reaction in self.parse_model():
                model.model[model_reaction] = None
        else:
            for reaction in model.reactions:
                model.model[reaction.id] = None

        return model
1322169
def build_graph(self):
        
        for child, parents in self.dependencies.items():
            if child not in self.nodes:
                raise NodeNotFoundError(
                    "App %s SQL item dependencies reference nonexistent child node %r" % (
                        child[0], child),
                    child
                )
            for parent in parents:
                if parent not in self.nodes:
                    raise NodeNotFoundError(
                        "App %s SQL item dependencies reference nonexistent parent node %r" % (
                            child[0], parent),
                        parent
                    )
                self.node_map[child].add_parent(self.node_map[parent])
                self.node_map[parent].add_child(self.node_map[child])

        for node in self.nodes:
            self.ensure_not_cyclic(node,
                                   lambda x: (parent.key for parent in self.node_map[x].parents))
636719
def graph_from_edges(edges: Iterable[Edge], **kwargs) -> BELGraph:
    """"""
    graph = BELGraph(**kwargs)

    for edge in edges:
        edge.insert_into_graph(graph)

    return graph
297977
def main(graph):
    
    args = parse_args(graph)

    if args.drop:
        drop_all(graph)
    create_all(graph)