This function creates a graph of vertices and edges from segments returned by SLIC.
    :param array grid: A grid of segments as returned by the slic function defined in skimage library
    :return: A graph as [vertices, edges]
163003
def create_graph(grid):
    
    try:
        import numpy as np
    except ImportError:
        print(
            "NumPY is not installed. segraph needs NumPY to function. Please use 'pip install numpy' to install numpy.")
        exit(0)
    print("Creating a graph using segmented grid..")
    # get an array of unique labels
    try:
        vertices = np.unique(grid)

        # get number of vertices
        num_vertices = len(vertices)

        # map these unique labels to [1,...,N], where N is the number of labels (vertices)
        mapping = dict(zip(vertices, np.arange(num_vertices)))
        mapped_grid = np.array([mapping[x] for x in grid.flat]).reshape(grid.shape)

        # create edges, going left to right and top to bottom
        l2r = np.c_[mapped_grid[:, :-1].ravel(), mapped_grid[:, 1:].ravel()]
        t2b = np.c_[mapped_grid[:-1, :].ravel(), mapped_grid[1:, :].ravel()]

        # stack for entire graph
        edges = np.vstack([l2r, t2b])
        edges = edges[edges[:, 0] != edges[:, 1], :]
        edges = np.sort(edges, axis=1)

        # create a edge map, a hashmap
        edge_map = edges[:, 0] + num_vertices * edges[:, 1]

        # filter unique connections as edges
        edges = np.unique(edge_map)

        # reverse map and form edges as pairs
        edges = [[vertices[edge % num_vertices],
                  vertices[edge // num_vertices]] for edge in edges]
    except:
        print("Invalid argument supplied !")
        return None

    return vertices, edges
246617
def create_rectangular_prism(origin, size):
    '''
    

    '''
    from lace.topology import quads_to_tris

    lower_base_plane = np.array([
        # Lower base plane
        origin,
        origin + np.array([size[0], 0, 0]),
        origin + np.array([size[0], 0, size[2]]),
        origin + np.array([0, 0, size[2]]),
    ])
    upper_base_plane = lower_base_plane + np.array([0, size[1], 0])

    vertices = np.vstack([lower_base_plane, upper_base_plane])

    faces = quads_to_tris(np.array([
        [0, 1, 2, 3],  # lower base (-y)
        [7, 6, 5, 4],  # upper base (+y)
        [4, 5, 1, 0],  # +z face
        [5, 6, 2, 1],  # +x face
        [6, 7, 3, 2],  # -z face
        [3, 7, 4, 0],  # -x face
    ]))

    return Mesh(v=vertices, f=faces)
750908
def coord_grid(self):
        """"""

        ra2 = math.pi * 2
        ra1 = 0
        dec1 = -1 * math.pi / 2.0
        dec2 = math.pi / 2.0

        dra = math.fabs((self.x2 - self.x1) / 4.0)
        ddec = math.fabs((self.y2 - self.y1) / 4.0)
        logging.debug("Drawing the grid.")
        label = True
        ra = ra1
        while ra <= ra2:
            # create a line that goes from dec1 to dec2 at this ra
            (cx1, cy1) = self.p2c((ra, dec1))
            # ly is the y location mid-way between the top and bottom of the plot
            (cx2, cy2) = self.p2c((ra, dec2))
            # create a dashed line for un-labeled lines
            self.create_line(cx1, cy1, cx2, cy2, dash=(20, 20), fill="grey")
            dec = dec1
            while dec <= dec2:
                if label:
                    # lx is the the x screen coordinate location of the ra
                    (lx, ly) = self.p2c((ra, dec + ddec / 2.0))
                    self.create_text(lx + 5, ly, justify=LEFT,
                                     font=('Times', '-20'),
                                     text="\n".join(str(ephem.hours(ra))[:-3]), fill='grey')
                label = not label
                dec += ddec
            ra += dra

        # plot dec grid lines bewtween South (dec1) and North (dec2) limits of plot
        dec = dec1
        # should we label the current grid line?
        label = True
        while dec <= dec2:
            # create a line the goes from ra1 to ra2 at this dec
            (cx1, cy1) = self.p2c((ra1, dec))
            (cx2, cy2) = self.p2c((ra2, dec))
            self.create_line(cx1, cy1, cx2, cy2, dash=(20, 20), fill='grey')
            ra = ra1
            while ra <= ra2:
                if label:
                    # lx/ly are the screen coordinates of the label
                    (lx, ly) = self.p2c((ra + dra / 2.0, dec))
                    self.create_text(lx, ly - 5, font=('Times', '-20'),
                                     text=str(ephem.degrees(dec)), fill='grey')
                ra += dra
            dec += ddec
            label = not label
1235288
def _build_vertex_data(self):
        
        grid = self._grid
        w = 1.0 / grid[1]
        h = 1.0 / grid[0]

        quad = np.array([[0, 0, 0], [w, 0, 0], [w, h, 0],
                         [0, 0, 0], [w, h, 0], [0, h, 0]],
                        dtype=np.float32)
        quads = np.empty((grid[1], grid[0], 6, 3), dtype=np.float32)
        quads[:] = quad

        mgrid = np.mgrid[0.:grid[1], 0.:grid[0]].transpose(1, 2, 0)
        mgrid = mgrid[:, :, np.newaxis, :]
        mgrid[..., 0] *= w
        mgrid[..., 1] *= h

        quads[..., :2] += mgrid
        tex_coords = quads.reshape(grid[1]*grid[0]*6, 3)
        tex_coords = np.ascontiguousarray(tex_coords[:, :2])
        vertices = tex_coords * self.size

        self._subdiv_position.set_data(vertices.astype('float32'))
        self._subdiv_texcoord.set_data(tex_coords.astype('float32'))
1213389
def edges_to_dict_of_dataframes(grid, edges):
    
    omega = 2 * pi * 50
    srid = int(cfg_ding0.get('geo', 'srid'))

    lines = {'line_id': [], 'bus0': [], 'bus1': [], 'x': [], 'r': [],
             's_nom': [], 'length': [], 'cables': [], 'geom': [],
             'grid_id': []}

    # iterate over edges and add them one by one
    for edge in edges:

        line_name = '_'.join(['MV',
                              str(grid.id_db),
                              'lin',
                              str(edge['branch'].id_db)])

        # TODO: find the real cause for being L, C, I_th_max type of Series
        if (isinstance(edge['branch'].type['L'], Series) or
                isinstance(edge['branch'].type['C'], Series)):
            x = omega * edge['branch'].type['L'].values[0] * 1e-3
        else:

            x = omega * edge['branch'].type['L'] * 1e-3

        if isinstance(edge['branch'].type['R'], Series):
            r = edge['branch'].type['R'].values[0]
        else:
            r = edge['branch'].type['R']

        if (isinstance(edge['branch'].type['I_max_th'], Series) or
                isinstance(edge['branch'].type['U_n'], Series)):
            s_nom = sqrt(3) * edge['branch'].type['I_max_th'].values[0] * \
                    edge['branch'].type['U_n'].values[0]
        else:
            s_nom = sqrt(3) * edge['branch'].type['I_max_th'] * \
                    edge['branch'].type['U_n']

        # get lengths of line
        l = edge['branch'].length / 1e3

        lines['line_id'].append(line_name)
        lines['bus0'].append(edge['adj_nodes'][0].pypsa_id)
        lines['bus1'].append(edge['adj_nodes'][1].pypsa_id)
        lines['x'].append(x * l)
        lines['r'].append(r * l)
        lines['s_nom'].append(s_nom)
        lines['length'].append(l)
        lines['cables'].append(3)
        lines['geom'].append(from_shape(
            LineString([edge['adj_nodes'][0].geo_data,
                        edge['adj_nodes'][1].geo_data]),
            srid=srid))
        lines['grid_id'].append(grid.id_db)

    return {'Line': DataFrame(lines).set_index('line_id')}
190481
def grid(self, z_x_y):
        
        # sources.py -> MapnikRenderer -> grid
        (z, x, y) = z_x_y
        content = self.reader.grid(z, x, y, self.grid_fields, self.grid_layer)
        return content
338035
def grid(metadata, layout, params):
  
  x = layout["x"]
  y = layout["y"]
  x_min = np.min(x)
  x_max = np.max(x)
  y_min = np.min(y)
  y_max = np.max(y)

  # this creates the grid
  bins = np.linspace(x_min, x_max, params["n_layer"] - 1)
  xd = np.digitize(x, bins)
  bins = np.linspace(y_min, y_max, params["n_layer"] - 1)
  yd = np.digitize(y, bins)

  # the number of tiles is the number of cells divided by the number of cells in each tile
  num_tiles = int(params["n_layer"]/params["n_tile"])
  print("num tiles", num_tiles)
  # we will save the tiles in an array indexed by the tile coordinates
  tiles = {}
  for ti in range(num_tiles):
    for tj in range(num_tiles):
      tiles[(ti,tj)] = {
        "x": [],
        "y": [],
        "ci": [], # cell-space x coordinate
        "cj": [], # cell-space y coordinate
        "gi": [], # global index
      }

  for i,xi in enumerate(x):
    if(i % 1000 == 0 or i+1 == len(x)):
      print("point", i+1, "/", len(x), end="\r")
    # layout-space coordinates
    yi = y[i]
    # grid-space cell coordinates
    ci = xd[i]
    cj = yd[i]
    # tile coordinate
    ti = math.floor(ci / params["n_tile"])
    tj = math.floor(cj / params["n_tile"])

    # TODO: don't append a point if it doesn't match a filter function provided in params
    filter = params.get("filter", lambda i,metadata: True)
    if(filter(i, metadata=metadata)):
      tiles[(ti,tj)]["x"].append(xi)
      tiles[(ti,tj)]["y"].append(yi)
      tiles[(ti,tj)]["ci"].append(ci)
      tiles[(ti,tj)]["cj"].append(cj)
      tiles[(ti,tj)]["gi"].append(i)
    
  return tiles
1367078
def grid_edges(shape, inds=None, return_directions=True):
    
    if inds is None:
        inds = np.arange(np.prod(shape)).reshape(shape)
    # if not self.segparams['use_boundary_penalties'] and \
    #         boundary_penalties_fcn is None :
    if len(shape) == 2:
        edgx = np.c_[inds[:, :-1].ravel(), inds[:, 1:].ravel()]
        edgy = np.c_[inds[:-1, :].ravel(), inds[1:, :].ravel()]

        edges = [edgx, edgy]

        directions = [
            np.ones([edgx.shape[0]], dtype=np.int8) * 0,
            np.ones([edgy.shape[0]], dtype=np.int8) * 1,
        ]

    elif len(shape) == 3:
        # This is faster for some specific format
        edgx = np.c_[inds[:, :, :-1].ravel(), inds[:, :, 1:].ravel()]
        edgy = np.c_[inds[:, :-1, :].ravel(), inds[:, 1:, :].ravel()]
        edgz = np.c_[inds[:-1, :, :].ravel(), inds[1:, :, :].ravel()]
        edges = [edgx, edgy, edgz]
    else:
        logger.error("Expected 2D or 3D data")

    # for all edges along first direction put 0, for second direction put 1, for third direction put 3
    if return_directions:
        directions = []
        for idirection in range(len(shape)):
            directions.append(
                np.ones([edges[idirection].shape[0]], dtype=np.int8) * idirection
            )
    edges = np.concatenate(edges)
    if return_directions:
        edge_dir = np.concatenate(directions)
        return edges, edge_dir
    else:
        return edges
730628
def grid_list(data):
    '''
    
    '''
    a = []
    b = []
    M = []
    for i in data:
        a.append(i[0])  # np.array([i[1] for i in data], dtype=np.float64)
        b.append(i[1])  # np.array([i[0] for i in data], dtype=np.float64)
        M.append(i[2])  # np.array([i[2] for i in data], dtype=np.float64)
    a = np.array(a, dtype=np.float64).tolist()
    b = np.array(b, dtype=np.float64).tolist()
    M = np.array(M, dtype=np.float64).tolist()
    a = list(set(a))
    b = list(set(b))
    return a, b, M
17136
def graph_from_adjacency_matrix(matrix, node_prefix='', directed=False):
    

    node_orig = 1

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

    for row in matrix:
        if not directed:
            skip = matrix.index(row)
            r = row[skip:]
        else:
            skip = 0
            r = row
        node_dest = skip + 1

        for e in r:
            if e:
                graph.add_edge(
                    Edge(
                        node_prefix + node_orig,
                        node_prefix + node_dest))
            node_dest += 1
        node_orig += 1

    return graph
636020
def surface_nodes(self):
        
        line = []
        for point in self.mesh:
            line.append(point.longitude)
            line.append(point.latitude)
            line.append(point.depth)
        return [Node('griddedSurface', nodes=[Node('gml:posList', {}, line)])]
1180185
def grid(self, z, x, y, fields, layer):
        
        logger.debug(_("Render grid %s") % ((z, x, y),))
        proj = GoogleProjection(self.tilesize, [z])
        return self.render_grid(proj.tile_bbox((z, x, y)), fields, layer)
959463
def kdtree(self):
        

        kdtree = KDTree(self.vertices.view(np.ndarray))
        return kdtree
1261728
def inc_edges(self, node):
        
        try:
            return list(self.nodes[node][0])
        except KeyError:
            raise GraphError('Invalid node %s' % node)

        return None
1156894
def grid(box, draw)
      x, y, w, h = box.x, box.y, box.width, box.height
      use_cairo do |cc|
        (x..@width + w).step(w)  { |ix| line_xy(ix, y - @height, ix, @height + y, draw) }
        (y..@height + h).step(h) { |iy| line_xy(x - @width, iy, @width + x, iy, draw) }
      end
    end
120595
def _SGraphFromJsonTree(json_str):
    
    g = json.loads(json_str)
    vertices = [_Vertex(x['id'],
                dict([(str(k), v) for k, v in _six.iteritems(x) if k != 'id']))
                                                      for x in g['vertices']]
    edges = [_Edge(x['src'], x['dst'],
             dict([(str(k), v) for k, v in _six.iteritems(x) if k != 'src' and k != 'dst']))
                                                      for x in g['edges']]
    sg = _SGraph().add_vertices(vertices)
    if len(edges) > 0:
        sg = sg.add_edges(edges)
    return sg
58669
def connect_edges(graph):
    
    paths = []
    for start, end in graph.array(graph.kdims):
        start_ds = graph.nodes[:, :, start]
        end_ds = graph.nodes[:, :, end]
        if not len(start_ds) or not len(end_ds):
            raise ValueError('Could not find node positions for all edges')
        start = start_ds.array(start_ds.kdims[:2])
        end = end_ds.array(end_ds.kdims[:2])
        paths.append(np.array([start[0], end[0]]))
    return paths