Return a whole network as a complex model.
197300
def get_network_by_name(project_id, network_name,**kwargs):
    

    try:
        res = db.DBSession.query(Network.id).filter(func.lower(Network.name).like(network_name.lower()), Network.project_id == project_id).one()
        net = get_network(res.id, 'Y', None, **kwargs)
        return net
    except NoResultFound:
        raise ResourceNotFoundError("Network with name %s not found"%(network_name))
495944
def extract_descriptor(self):
        """"""
        main_chain = self.get_main_chain()
        index_in_main_chain = {}
        for index, u in enumerate(main_chain):
            index_in_main_chain[u] = index

        ret = NetworkDescriptor()
        for u in main_chain:
            for v, layer_id in self.adj_list[u]:
                if v not in index_in_main_chain:
                    continue
                layer = self.layer_list[layer_id]
                copied_layer = copy(layer)
                copied_layer.weights = None
                ret.add_layer(deepcopy(copied_layer))

        for u in index_in_main_chain:
            for v, layer_id in self.adj_list[u]:
                if v not in index_in_main_chain:
                    temp_u = u
                    temp_v = v
                    temp_layer_id = layer_id
                    skip_type = None
                    while not (temp_v in index_in_main_chain and temp_u in index_in_main_chain):
                        if is_layer(self.layer_list[temp_layer_id], "Concatenate"):
                            skip_type = NetworkDescriptor.CONCAT_CONNECT
                        if is_layer(self.layer_list[temp_layer_id], "Add"):
                            skip_type = NetworkDescriptor.ADD_CONNECT
                        temp_u = temp_v
                        temp_v, temp_layer_id = self.adj_list[temp_v][0]
                    ret.add_skip_connection(
                        index_in_main_chain[u], index_in_main_chain[temp_u], skip_type
                    )

                elif index_in_main_chain[v] - index_in_main_chain[u] != 1:
                    skip_type = None
                    if is_layer(self.layer_list[layer_id], "Concatenate"):
                        skip_type = NetworkDescriptor.CONCAT_CONNECT
                    if is_layer(self.layer_list[layer_id], "Add"):
                        skip_type = NetworkDescriptor.ADD_CONNECT
                    ret.add_skip_connection(
                        index_in_main_chain[u], index_in_main_chain[v], skip_type
                    )

        return ret
188609
def model_fn(features, labels, mode, params):
  """"""
  del labels
  global_step = tf.train.get_global_step()
  graph = mtf.Graph()
  mesh_shape = mtf.convert_to_shape(FLAGS.mesh_shape)
  layout_rules = mtf.convert_to_layout_rules(FLAGS.layout)
  if FLAGS.use_tpu:
    ctx = params['context']
    num_hosts = ctx.num_hosts
    host_placement_fn = ctx.tpu_host_placement_function
    device_list = [host_placement_fn(host_id=t) for t in range(num_hosts)]
    tf.logging.info('device_list = %s' % device_list,)
    # TODO(ylc): Better estimation of replica cache size?
    replica_cache_size = 300 * 1000000  # 300M per replica
    # Worker 0 caches all the TPU binaries.
    worker0_mem = replica_cache_size * ctx.num_replicas
    devices_memeory_usage = [worker0_mem] + [0] * (num_hosts - 1)
    var_placer = mtf.utils.BalancedVariablePlacer(device_list,
                                                  devices_memeory_usage)
    mesh_devices = [''] * mesh_shape.size
    mesh_impl = mtf.simd_mesh_impl.SimdMeshImpl(
        mesh_shape, layout_rules, mesh_devices, ctx.device_assignment)
  else:
    var_placer = None
    mesh_devices = [''] * mesh_shape.size
    mesh_impl = mtf.placement_mesh_impl.PlacementMeshImpl(
        mesh_shape, layout_rules, mesh_devices)
  mesh = mtf.Mesh(graph, 'my_mesh', var_placer)

  with mtf.utils.outside_all_rewrites():
    logits, loss = toy_model(features, mesh)

  # TRAIN mode
  if mode == tf.estimator.ModeKeys.TRAIN:
    var_grads = mtf.gradients([loss],
                              [v.outputs[0] for v in graph.trainable_variables])
    if FLAGS.optimizer == 'Adafactor':
      optimizer = mtf.optimize.AdafactorOptimizer()
    else:
      assert FLAGS.optimizer == 'SGD'
      optimizer = mtf.optimize.SgdOptimizer(lr=FLAGS.lr)
    update_ops = optimizer.apply_grads(var_grads, graph.trainable_variables)
  else:
    # for now, we can only export fully-replicated tensors.
    fully_replicated_logits = mtf.anonymize(logits)

  lowering = mtf.Lowering(graph, {mesh: mesh_impl})

  tf_loss = tf.to_float(lowering.export_to_tf_tensor(loss))

  if mode == tf.estimator.ModeKeys.TRAIN:
    tf_update_ops = [lowering.lowered_operation(op) for op in update_ops]
    tf_update_ops.append(tf.assign_add(global_step, 1))
    tf.logging.info('tf_update_ops: {}'.format(tf_update_ops))
    train_op = tf.group(tf_update_ops)
  else:
    tf_logits = lowering.export_to_tf_tensor(fully_replicated_logits)

  with mtf.utils.outside_all_rewrites():
    # Copy master variables to slices. Must be called first.
    restore_hook = mtf.MtfRestoreHook(lowering)
    if mode == tf.estimator.ModeKeys.TRAIN:
      saver = tf.train.Saver(
          tf.global_variables(),
          sharded=True,
          max_to_keep=10,
          keep_checkpoint_every_n_hours=2,
          defer_build=False,
          save_relative_paths=True)
      tf.add_to_collection(tf.GraphKeys.SAVERS, saver)
      saver_listener = mtf.MtfCheckpointSaverListener(lowering)
      saver_hook = tf.train.CheckpointSaverHook(
          FLAGS.model_dir,
          save_steps=1000,
          saver=saver,
          listeners=[saver_listener])

      return tpu_estimator.TPUEstimatorSpec(
          tf.estimator.ModeKeys.TRAIN,
          loss=tf_loss,
          train_op=train_op,
          training_hooks=[restore_hook, saver_hook])
    elif mode == tf.estimator.ModeKeys.EVAL:

      def metric_fn(tf_logits):
        mean_logits = tf.metrics.mean(tf_logits)
        return {'mean_logits': mean_logits}

      eval_metrics = (metric_fn, [tf_logits])

      return tpu_estimator.TPUEstimatorSpec(
          tf.estimator.ModeKeys.EVAL,
          evaluation_hooks=[restore_hook],
          loss=tf_loss,
          eval_metrics=eval_metrics)
366955
def fetch_model_ndex():
    """"""
    if request.method == 'OPTIONS':
        return {}
    response = request.body.read().decode('utf-8')
    body = json.loads(response)
    network_id = body.get('network_id')
    cx = process_ndex_network(network_id)
    network_attr = [x for x in cx.cx if x.get('networkAttributes')]
    network_attr = network_attr[0]['networkAttributes']
    keep_keys = ['txt_input', 'parser',
                 'model_elements', 'preset_pos', 'stmts',
                 'sentences', 'evidence', 'cell_line', 'mrna', 'mutations']
    stored_data = {}
    for d in network_attr:
        if d['n'] in keep_keys:
            stored_data[d['n']] = d['v']
    return stored_data
851934
def load_graphdef(model_url, reset_device=True):
  """"""
  graph_def = load(model_url)

  if reset_device:
    for n in graph_def.node:
      n.device = ""

  return graph_def
529000
def conj(self):
        """"""
        complex_conj = [part.conj() for part in self.parts]
        return self.space.element(complex_conj)
111299
def mesh(self):
        """"""
        triangles = np.empty((self.f.shape[0], 4))
        triangles[:, -3:] = self.f
        triangles[:, 0] = 3
        return vtki.PolyData(self.v, triangles, deep=False)
1322267
def full(self):
        """"""

        # Compute tensor unfolding along first mode
        unf = sci.dot(self.factors[0], khatri_rao(self.factors[1:]).T)

        # Inverse unfolding along first mode
        return sci.reshape(unf, self.shape)
1179968
def _get_network(self):
        '''
        
        '''
        data = dict()
        data['interfaces'] = salt.utils.network.interfaces()
        data['subnets'] = salt.utils.network.subnets()

        return data
263612
def _fully_connected(self, x, out_dim):
        """"""
        x = tf.reshape(x, [self.hps.batch_size, -1])
        w = tf.get_variable(
            "DW", [x.get_shape()[1], out_dim],
            initializer=tf.uniform_unit_scaling_initializer(factor=1.0))
        b = tf.get_variable(
            "biases", [out_dim], initializer=tf.constant_initializer())
        return tf.nn.xw_plus_b(x, w, b)
1104917
def build_network(self,
                      images,
                      phase_train=True,
                      nclass=1001,
                      image_depth=3,
                      data_type=tf.float32,
                      data_format="NCHW",
                      use_tf_layers=True,
                      fp16_vars=False):
        """"""
        if data_format == "NCHW":
            images = tf.transpose(images, [0, 3, 1, 2])
        var_type = tf.float32
        if data_type == tf.float16 and fp16_vars:
            var_type = tf.float16
        network = convnet_builder.ConvNetBuilder(
            images, image_depth, phase_train, use_tf_layers, data_format,
            data_type, var_type)
        with tf.variable_scope(
                "cg", custom_getter=network.get_custom_getter()):
            self.add_inference(network)
            # Add the final fully-connected class layer
            logits = (network.affine(nclass, activation="linear")
                      if not self.skip_final_affine_layer() else
                      network.top_layer)
            aux_logits = None
            if network.aux_top_layer is not None:
                with network.switch_to_aux_top_layer():
                    aux_logits = network.affine(
                        nclass, activation="linear", stddev=0.001)
        if data_type == tf.float16:
            # TODO(reedwm): Determine if we should do this cast here.
            logits = tf.cast(logits, tf.float32)
            if aux_logits is not None:
                aux_logits = tf.cast(aux_logits, tf.float32)
        return logits, aux_logits
310250
def to_dnf(self):
        """"""
        node = self.node.to_dnf()
        if node is self.node:
            return self
        else:
            return _expr(node)
145605
def prepare_everything(self):
        """"""
        self.prepare_network()
        self.init_models()
        self.load_conditions()
        with hydpy.pub.options.warnmissingobsfile(False):
            self.prepare_nodeseries()
        self.prepare_modelseries()
        self.load_inputseries()
924707
def _get_all_attributes(network):
    
    attrs = network.attributes
    for n in network.nodes:
        attrs.extend(n.attributes)
    for l in network.links:
        attrs.extend(l.attributes)
    for g in network.resourcegroups:
        attrs.extend(g.attributes)

    return attrs
657441
def as_graph(self, depth=0):
        
        if depth in self._graph_cache:
            return self._graph_cache[depth]
        self._graph_cache[depth] = graph = Graph(self, depth=depth)
        return graph
716458
def get_nx_graph(ea):
    """"""
    nx_graph = networkx.DiGraph()
    func = idaapi.get_func(ea)
    flowchart = FlowChart(func)
    for block in flowchart:
        # Make sure all nodes are added (including edge-less nodes)
        nx_graph.add_node(block.startEA)

        for pred in block.preds():
            nx_graph.add_edge(pred.startEA, block.startEA)
        for succ in block.succs():
            nx_graph.add_edge(block.startEA, succ.startEA)

    return nx_graph
65415
def make_model(self):
        """"""
        # Assemble in two stages.
        # First, create the nodes of the graph
        for stmt in self.statements:
            # Skip SelfModification (self loops) -- has one node
            if isinstance(stmt, SelfModification) or \
               isinstance(stmt, Translocation) or \
               isinstance(stmt, ActiveForm):
                continue
            # Special handling for Associations -- more than 1 node and members
            # are Events
            elif isinstance(stmt, Association):
                for m in stmt.members:
                    self._add_node(m.concept)
            # Special handling for Complexes -- more than 1 node
            elif isinstance(stmt, Complex):
                for m in stmt.members:
                    self._add_node(m)
            # All else should have exactly 2 nodes
            elif all([ag is not None for ag in stmt.agent_list()]):
                if not len(stmt.agent_list()) == 2:
                    logger.warning(
                        '%s has less/more than the expected 2 agents.' % stmt)
                    continue
                for ag in stmt.agent_list():
                    self._add_node(ag)
        # Second, create the edges of the graph
        for stmt in self.statements:
            # Skip SelfModification (self loops) -- has one node
            if isinstance(stmt, SelfModification) or \
               isinstance(stmt, Translocation) or \
               isinstance(stmt, ActiveForm):
                continue
            elif isinstance(stmt, Association):
                self._add_complex(stmt.members, is_association=True)
            elif isinstance(stmt, Complex):
                self._add_complex(stmt.members)
            elif all([ag is not None for ag in stmt.agent_list()]):
                self._add_stmt_edge(stmt)