Creates a basic graph out of an incidence matrix.

    The matrix has to be a list of rows of values
    representing an incidence matrix.
    The values can be anything: bool, int, float, as long
    as they can evaluate to True or False.
546464
def graph_from_incidence_matrix(matrix, node_prefix='', directed=False):
    

    if directed:
        graph = Dot(graph_type='digraph')
    else:
        graph = Dot(graph_type='graph')

    for row in matrix:
        nodes = []
        c = 1

        for node in row:
            if node:
                nodes.append(c * node)
            c += 1

        nodes.sort()

        if len(nodes) == 2:
            graph.add_edge(
                Edge(
                    node_prefix + abs(nodes[0]),
                    node_prefix + nodes[1]))

    if not directed:
        graph.set_simplify(True)

    return graph
874865
def build_plane_arrays(x, y, qlist):
    
    if type(qlist) is not list:
        return_list = False
        qlist = [qlist]
    else:
        return_list = True
    xv = x[np.where(y==y[0])[0]]
    yv = y[np.where(x==x[0])[0]]
    qlistp = []
    for n in range(len(qlist)):
        qlistp.append(np.zeros((len(yv), len(xv))))
    for j in range(len(qlist)):
        for n in range(len(yv)):
            i = np.where(y==yv[n])[0]
            qlistp[j][n,:] = qlist[j][i]
    if not return_list:
        qlistp = qlistp[0]
    return xv, yv, qlistp
1176163
def _interp(self):
        
        if np.all(self.hrow_indices == self.row_indices):
            return self._interp1d()

        xpoints, ypoints = np.meshgrid(self.hrow_indices,
                                       self.hcol_indices)

        for num, data in enumerate(self.tie_data):
            spl = RectBivariateSpline(self.row_indices,
                                      self.col_indices,
                                      data,
                                      s=0,
                                      kx=self.kx_,
                                      ky=self.ky_)

            new_data_ = spl.ev(xpoints.ravel(), ypoints.ravel())
            self.new_data[num] = new_data_.reshape(xpoints.shape).T.copy(order='C')
1181603
void constructLinearSystem(List<DMatrixRMaj> homographies,
							   List<List<PointIndex2D_F64>> observations) {
		// parameters are encoded points first then the
		int startView = totalFeatures*3;

		A.reshape(numEquations,numUnknown);

		DMatrixRMaj H = new DMatrixRMaj(3,3);
		Point2D_F64 p = new Point2D_F64();

		int row = 0;
		for (int viewIdx = 0; viewIdx < homographies.size(); viewIdx++) {
			N.apply(homographies.get(viewIdx),H);

			int colView = startView + viewIdx*3;

			List<PointIndex2D_F64> obs = observations.get(viewIdx);
			for (int i = 0; i < obs.size(); i++) {
				PointIndex2D_F64 p_pixel = obs.get(i);

				N.apply(p_pixel,p);

				// column this feature is at
				int col = p_pixel.index*3;

				// x component of pixel
				// A(row,colView) =  ...
				A.data[row*A.numCols + col    ] = p.x*H.get(2,0) - H.get(0,0);
				A.data[row*A.numCols + col + 1] = p.x*H.get(2,1) - H.get(0,1);
				A.data[row*A.numCols + col + 2] = p.x*H.get(2,2) - H.get(0,2);

				A.data[row*A.numCols + colView     ] = -1;
				A.data[row*A.numCols + colView + 1 ] = 0;
				A.data[row*A.numCols + colView + 2 ] = p.x;

				// y component of pixel
				row += 1;
				A.data[row*A.numCols + col    ] = p.y*H.get(2,0) - H.get(1,0);
				A.data[row*A.numCols + col + 1] = p.y*H.get(2,1) - H.get(1,1);
				A.data[row*A.numCols + col + 2] = p.y*H.get(2,2) - H.get(1,2);

				A.data[row*A.numCols + colView     ] = 0;
				A.data[row*A.numCols + colView + 1 ] = -1;
				A.data[row*A.numCols + colView + 2 ] = p.y;

				row += 1;
			}
		}
	}
810831
private void createVertexNumber()
    {
    	c = graph.vertexSet().size();
        vertexToVertexNumber = new HashMap<>(c);

        for (V vertex : graph.vertexSet()) {
            vertexToVertexNumber.put(vertex, new VertexNumber<V>(vertex, 0));            
        }
        
        stack = new ArrayDeque<>(c);
        B = new ArrayDeque<>(c);
    }
930996
def get_igraph_from_adjacency(adjacency, directed=None):
    """"""
    import igraph as ig
    sources, targets = adjacency.nonzero()
    weights = adjacency[sources, targets]
    if isinstance(weights, np.matrix):
        weights = weights.A1
    g = ig.Graph(directed=directed)
    g.add_vertices(adjacency.shape[0])  # this adds adjacency.shap[0] vertices
    g.add_edges(list(zip(sources, targets)))
    try:
        g.es['weight'] = weights
    except:
        pass
    if g.vcount() != adjacency.shape[0]:
        logg.warn('The constructed graph has only {} nodes. '
                  'Your adjacency matrix contained redundant nodes.'
                  .format(g.vcount()))
    return g
558826
def _make_graph(bsname, version=None, data_dir=None):
    '''
    
    '''

    if not graphviz_avail:
        raise RuntimeError("graphviz package is not installed")

    data_dir = api.fix_data_dir(data_dir)

    md = api._get_basis_metadata(bsname, data_dir)

    if version is None:
        version = md['latest_version']
    else:
        version = str(version)

    if not version in md['versions']:
        raise RuntimeError("Version {} of {} doesn't exist".format(version, bsname))

    gr = graphviz.Digraph(comment='Basis Set Graph: ' + bsname)

    # Read the table file
    table_path = os.path.join(data_dir, md['versions'][version]['file_relpath'])
    table_data = fileio.read_json_basis(table_path)

    table_edges = {}
    for el, entry in table_data['elements'].items():
        if entry not in table_edges:
            table_edges[entry] = []
        table_edges[entry].append(el)

    for k, v in table_edges.items():
        gr.edge(bsname, k, label=compact_elements(v))

    # Element file
    for elfile in table_edges.keys():
        element_path = os.path.join(data_dir, elfile)
        element_data = fileio.read_json_basis(element_path)

        element_edges = {}

        for el, components in element_data['elements'].items():
            components = components['components']
            components_str = '\n'.join(components)

            # skip if this element for the table basis doesn't come from this file
            if el not in table_data['elements']:
                continue
            if table_data['elements'][el] != elfile:
                continue

            if components_str not in element_edges:
                element_edges[components_str] = []
            element_edges[components_str].append(el)

        for k, v in element_edges.items():
            if len(v):
                gr.edge(elfile, k, label=compact_elements(v))

    return gr
266065
def make_node(cls, id_, arglist, lineno):
        
        assert isinstance(arglist, SymbolARGLIST)
        variable = gl.SYMBOL_TABLE.access_array(id_, lineno)
        if variable is None:
            return None

        if len(variable.bounds) != len(arglist):
            syntax_error(lineno, "Array '%s' has %i dimensions, not %i" %
                         (variable.name, len(variable.bounds), len(arglist)))
            return None

        # Checks for array subscript range if the subscript is constant
        # e.g. A(1) is a constant subscript access
        for i, b in zip(arglist, variable.bounds):
            btype = gl.SYMBOL_TABLE.basic_types[gl.BOUND_TYPE]
            lower_bound = NUMBER(b.lower, type_=btype, lineno=lineno)
            i.value = BINARY.make_node('MINUS',
                                       TYPECAST.make_node(btype, i.value, lineno),
                                       lower_bound, lineno, func=lambda x, y: x - y,
                                       type_=btype)
            if is_number(i.value) or is_const(i.value):
                val = i.value.value
                if val < 0 or val > b.count:
                    warning(lineno, "Array '%s' subscript out of range" % id_)

        # Returns the variable entry and the node
        return cls(variable, arglist, lineno)
325179
function makeMatrix(n, m, x) {
  var matrix = [];
  for (var i = 0; i < n; i++) {
    matrix[i] = new Array(m);
    for (var j = 0; j < m; j++) {
      matrix[i][j] = x;
    }
  }

  return matrix;
}
1289575
def create(atoms_list,N, L, cutoff = 0, all_atomtypes=[]):
    
    myAlphas, myBetas = genBasis.getBasisFunc(cutoff, N)
    # get information about feature length
    n_datapoints = len(atoms_list)
    atoms = atoms_list[0]
    x = get_lastatom_soap(atoms, cutoff, myAlphas, myBetas,N,L, all_atomtypes=all_atomtypes)
    n_features = x.shape[1]
    print("soap first", x.shape)
    print(n_datapoints, n_features)
    soapmatrix = np.zeros((n_datapoints, n_features))

    i = -1
    for atoms in atoms_list:
        i +=1
        #atoms
        print("Processing " + str(atoms.info)," Run time: " + str(time.time()-t0_total), end="\r")
        soapmatrix[i,:] = get_lastatom_soap(atoms, cutoff, myAlphas, myBetas, N, L, all_atomtypes=all_atomtypes)
    print("")

    # infos
    print("shape", soapmatrix.shape)
    return soapmatrix
618588
public static DMatrix4 extractRow( DMatrix4x4 a , int row , DMatrix4 out ) {
        if( out == null) out = new DMatrix4();
        switch( row ) {
            case 0:
                out.a1 = a.a11;
                out.a2 = a.a12;
                out.a3 = a.a13;
                out.a4 = a.a14;
            break;
            case 1:
                out.a1 = a.a21;
                out.a2 = a.a22;
                out.a3 = a.a23;
                out.a4 = a.a24;
            break;
            case 2:
                out.a1 = a.a31;
                out.a2 = a.a32;
                out.a3 = a.a33;
                out.a4 = a.a34;
            break;
            case 3:
                out.a1 = a.a41;
                out.a2 = a.a42;
                out.a3 = a.a43;
                out.a4 = a.a44;
            break;
            default:
                throw new IllegalArgumentException("Out of bounds row.  row = "+row);
        }
        return out;
    }
242622
def _make_graph(self):
        """"""
        self.nodes['graph'] = self.svg.node(
            class_='graph %s-graph %s' % (
                self.__class__.__name__.lower(),
                'horizontal' if self.horizontal else 'vertical'
            )
        )
        self.svg.node(
            self.nodes['graph'],
            'rect',
            class_='background',
            x=0,
            y=0,
            width=self.width,
            height=self.height
        )
        self.nodes['plot'] = self.svg.node(
            self.nodes['graph'],
            class_="plot",
            transform="translate(%d, %d)" %
            (self.margin_box.left, self.margin_box.top)
        )
        self.svg.node(
            self.nodes['plot'],
            'rect',
            class_='background',
            x=0,
            y=0,
            width=self.view.width,
            height=self.view.height
        )
        self.nodes['title'] = self.svg.node(
            self.nodes['graph'], class_="titles"
        )
        self.nodes['overlay'] = self.svg.node(
            self.nodes['graph'],
            class_="plot overlay",
            transform="translate(%d, %d)" %
            (self.margin_box.left, self.margin_box.top)
        )
        self.nodes['text_overlay'] = self.svg.node(
            self.nodes['graph'],
            class_="plot text-overlay",
            transform="translate(%d, %d)" %
            (self.margin_box.left, self.margin_box.top)
        )
        self.nodes['tooltip_overlay'] = self.svg.node(
            self.nodes['graph'],
            class_="plot tooltip-overlay",
            transform="translate(%d, %d)" %
            (self.margin_box.left, self.margin_box.top)
        )
        self.nodes['tooltip'] = self.svg.node(
            self.nodes['tooltip_overlay'],
            transform='translate(0 0)',
            style="opacity: 0",
            **{'class': 'tooltip'}
        )

        self.svg.node(
            self.nodes['tooltip'],
            'rect',
            rx=self.tooltip_border_radius,
            ry=self.tooltip_border_radius,
            width=0,
            height=0,
            **{'class': 'tooltip-box'}
        )
        self.svg.node(self.nodes['tooltip'], 'g', class_='text')
270641
function(fn) {
    var els = [], ni = this.elements.length, ki = ni, i, nj, kj = this.elements[0].length, j;
    do { i = ki - ni;
      nj = kj;
      els[i] = [];
      do { j = kj - nj;
        els[i][j] = fn(this.elements[i][j], i + 1, j + 1);
      } while (--nj);
    } while (--ni);
    return Matrix.create(els);
  }
916924
def build_diagonals(self):
    

    ##########################################################
    # INCORPORATE BOUNDARY CONDITIONS INTO COEFFICIENT ARRAY #
    ##########################################################

    # Roll to keep the proper coefficients at the proper places in the
    # arrays: Python will naturally just do vertical shifts instead of 
    # diagonal shifts, so this takes into account the horizontal compoent 
    # to ensure that boundary values are at the right place.
    self.l2 = np.roll(self.l2, -2)
    self.l1 = np.roll(self.l1, -1)
    self.r1 = np.roll(self.r1, 1)
    self.r2 = np.roll(self.r2, 2)

    # Then assemble these rows: this is where the periodic boundary condition 
    # can matter.
    if self.coeff_matrix is not None:
      pass
    elif self.BC_E == 'Periodic' and self.BC_W == 'Periodic':
      # In this case, the boundary-condition-related stacking has already 
      # happened inside b.c.-handling function. This is because periodic
      # boundary conditions require extra diagonals to exist on the edges of 
      # the solution array
      pass
    else:
      self.diags = np.vstack((self.l2,self.l1,self.c0,self.r1,self.r2))
      self.offsets = np.array([-2,-1,0,1,2])

    # Everybody now (including periodic b.c. cases)
    self.coeff_matrix = spdiags(self.diags, self.offsets, self.nx, self.nx, format='csr')
778870
function() {
    var rows = this.elements.length, cols = this.elements[0].length;
    var elements = [], ni = cols, i, nj, j;
    do { i = cols - ni;
      elements[i] = [];
      nj = rows;
      do { j = rows - nj;
        elements[i][j] = this.elements[j][i];
      } while (--nj);
    } while (--ni);
    return Matrix.create(elements);
  }
1098899
def make_graph(node, inputs):
        
        initializer = []
        tensor_input_info = []
        tensor_output_info = []

        # Adding input tensor info.
        for index in range(len(node.input)):
            tensor_input_info.append(
                helper.make_tensor_value_info(str(node.input[index]), TensorProto.FLOAT, [1]))

            # Creating an initializer for Weight params.
            # Assumes that weight params is named as 'W'.
            # TODO: Handle multiple weight params.
            # TODO: Add for "bias" if needed
            if node.input[index] == 'W':
                dim = inputs[index].shape
                param_tensor = helper.make_tensor(
                    name=node.input[index],
                    data_type=TensorProto.FLOAT,
                    dims=dim,
                    vals=inputs[index].flatten())

                initializer.append(param_tensor)

        # Adding output tensor info.
        for index in range(len(node.output)):
            tensor_output_info.append(
                helper.make_tensor_value_info(str(node.output[index]), TensorProto.FLOAT, [1]))

        # creating graph proto object.
        graph_proto = helper.make_graph(
            [node],
            "test",
            tensor_input_info,
            tensor_output_info,
            initializer=initializer)

        return graph_proto
1353488
public Graph<Attribute>[] createDS(Graph<Attribute>[] ids, List<Attribute>[][] a) {
        int i;
        Graph<Attribute>[] ds;

        ds = new Graph[ids.length];
        for (i = 0; i < ds.length; i++) {
            ds[i] = createDSx(ids[i], a[i]);
        }
        return ds;
    }