Esempio n. 1
0
def show_matches_gt_npy(filepath, name):
    global viewer
    global res
    with viewer.txn() as s:
        npf = np.load(filepath)
        keys = npf.item().keys()
        for key in keys:
            l = np.asarray(npf.item().get(key))

            s.layers.append(name='start_' + name,
                            layer=neuroglancer.AnnotationLayer(voxelSize=res))
            start = s.layers[-1].annotations

            s.layers.append(name='end_' + name,
                            layer=neuroglancer.AnnotationLayer(voxelSize=res))
            end = s.layers[-1].annotations
            id = -1
            for data in l:
                id += 1
                start.append(
                    neuroglancer.LineAnnotation(id=id,
                                                point_a=data[2][::-1],
                                                point_b=data[3][::-1]))
                end.append(
                    neuroglancer.PointAnnotation(id=id, point=data[2][::-1]))
Esempio n. 2
0
def add_trees(s, trees, node_id, name, visible=False):
    if trees is None:
        return None
    # print(f"Drawing {name} with {len(trees.nodes)} nodes")
    for i, cc_nodes in enumerate(nx.weakly_connected_components(trees)):
        # print(f"drawing cc {i} with {len(cc_nodes)} nodes")
        cc = trees.subgraph(cc_nodes)
        mst = []
        for u, v in cc.edges():
            pos_u = np.array(cc.nodes[u]["pos"]) + 0.5
            pos_v = np.array(cc.nodes[v]["pos"]) + 0.5
            mst.append(
                neuroglancer.LineAnnotation(point_a=pos_u[::-1],
                                            point_b=pos_v[::-1],
                                            id=next(node_id)))
        # print(f"adding {len(mst)} edge annotations")

        s.layers.append(
            name="{}_{}".format(name, i),
            layer=neuroglancer.AnnotationLayer(annotations=mst),
            annotationColor="#{:02X}{:02X}{:02X}".format(
                random.randint(0, 255), random.randint(0, 255),
                random.randint(0, 255)),
            visible=visible,
        )
Esempio n. 3
0
def show_grad(file_path, name, vec_lec=1, downsample_fac=1):
    global viewer
    global res
    h5file = h5py.File(file_path, 'r')
    for key in h5file.keys():
        line_id = 0
        data = h5file[key]
        with viewer.txn() as s:
            s.layers.append(name=name + '_' + key + '_end',
                            layer=neuroglancer.AnnotationLayer(voxelSize=res))
            s.layers.append(name=name + '_' + key + '_start',
                            layer=neuroglancer.AnnotationLayer(voxelSize=res))
            line = s.layers[-2].annotations
            point = s.layers[-1].annotations
            for i in range(data.shape[0]):
                line.append(
                    neuroglancer.LineAnnotation(
                        id=line_id,
                        point_a=downsample_fac * data[i, 0:3],
                        point_b=downsample_fac * data[i, 0:3] +
                        vec_lec * data[i, 3:6]))
                point.append(
                    neuroglancer.PointAnnotation(id=line_id + 500000,
                                                 point=downsample_fac *
                                                 data[i, 0:3]))

                line_id += 1
Esempio n. 4
0
def show_grad_field(file_path,
                    name,
                    seg_file=None,
                    seg_id=None,
                    vec_lec=1,
                    upsample_fac=1,
                    sparsity=15,
                    bloat=0):
    global viewer
    global res
    h5file = h5py.File(file_path, 'r')

    if seg_file is not None:
        h5file_seg = h5py.File(seg_file, 'r')
        segs = np.asarray(h5file_seg['main'])
        h5file_seg.close()
        mask = (segs == seg_id)
    else:
        mask = None

    for key in h5file.keys():
        line_id = 0
        data = h5file[key]

        if mask is None:
            locations = np.transpose(
                np.nonzero((data[0] != 0) | (data[1] != 0) | (data[2] != 0)))
        else:
            if bloat > 0:
                mask = ndimage.binary_dilation(mask,
                                               structure=np.ones((3, 3, 3)),
                                               iterations=int(bloat))
            locations = np.transpose(np.nonzero((mask)))

        locations = locations[::sparsity]
        with viewer.txn() as s:
            s.layers.append(name=name + '_' + key + '_end',
                            layer=neuroglancer.AnnotationLayer(voxelSize=res))
            s.layers.append(name=name + '_' + key + '_start',
                            layer=neuroglancer.AnnotationLayer(voxelSize=res))
            line = s.layers[-2].annotations
            point = s.layers[-1].annotations
            for i in range(locations.shape[0]):
                loc = tuple(locations[i])
                line.append(
                    neuroglancer.LineAnnotation(
                        id=line_id,
                        point_a=upsample_fac * locations[i, ::-1],
                        point_b=upsample_fac * locations[i, ::-1] +
                        vec_lec * np.array([
                            data[(2, ) + loc], data[(1, ) + loc], data[
                                (0, ) + loc]
                        ])))
                point.append(
                    neuroglancer.PointAnnotation(id=line_id + 500000,
                                                 point=upsample_fac *
                                                 locations[i, ::-1]))

                line_id += 1
Esempio n. 5
0
def add_trees(s, trees, node_id, name, visible=False):
    if trees is None:
        return None
    trees = nx.to_directed(trees)
    ccs = list(nx.weakly_connected_components(trees))
    if len(ccs) < 10:
        for i, cc_nodes in enumerate(nx.weakly_connected_components(trees)):
            cc = trees.subgraph(cc_nodes)
            mst = []
            for u, v in cc.edges():
                pos_u = np.array(cc.nodes[u]["location"]) + 0.5
                pos_v = np.array(cc.nodes[v]["location"]) + 0.5
                mst.append(
                    neuroglancer.LineAnnotation(point_a=pos_u[::-1],
                                                point_b=pos_v[::-1],
                                                id=next(node_id)))

            s.layers.append(
                name="{}_{}".format(name, i),
                layer=neuroglancer.AnnotationLayer(annotations=mst),
                annotationColor="#{:02X}{:02X}{:02X}".format(
                    random.randint(0, 255),
                    random.randint(0, 255),
                    random.randint(0, 255),
                ),
                visible=visible,
            )
    else:
        mst = []
        for u, v in trees.edges():
            pos_u = np.array(trees.nodes[u]["location"]) + 0.5
            pos_v = np.array(trees.nodes[v]["location"]) + 0.5
            mst.append(
                neuroglancer.LineAnnotation(point_a=pos_u[::-1],
                                            point_b=pos_v[::-1],
                                            id=next(node_id)))

        s.layers.append(
            name="{}".format(name),
            layer=neuroglancer.AnnotationLayer(annotations=mst),
            annotationColor="#{:02X}{:02X}{:02X}".format(
                random.randint(0, 255), random.randint(0, 255),
                random.randint(0, 255)),
            visible=visible,
        )
def add_neuron(s, df, neuron_ids=[], show_ellipsoid_annotation=False):
    if len(neuron_ids) == 0:
        neuron_ids = list(np.unique(df.neuron_id))
    for ii, neuron_id in enumerate(neuron_ids):
        color = "#%06x" % random.randint(0, 0xFFFFFF)
        pos_dic = {}
        df_neuron = df[df.neuron_id == neuron_id]
        edges = []
        for index, row in df_neuron.iterrows():
            node_id = row.id
            pos = np.array(row.position)
            pos_dic[node_id] = np.flip(pos)
            if row.parent_id:
                edges.append((node_id, row.parent_id))

        v_nodes, u_nodes, connectors = [], [], []
        print(f'Loaded {len(pos_dic)} nodes for neuron id {neuron_id}')
        for u, v in edges:
            if u in pos_dic and v in pos_dic:
                u_site = pos_dic[u]
                v_site = pos_dic[v]

                u_nodes.append(
                    neuroglancer.EllipsoidAnnotation(center=u_site,
                                                     radii=(30, 30, 30),
                                                     id=next(ngid)))
                v_nodes.append(
                    neuroglancer.EllipsoidAnnotation(center=v_site,
                                                     radii=(30, 30, 30),
                                                     id=next(ngid)))
                connectors.append(
                    neuroglancer.LineAnnotation(point_a=u_site,
                                                point_b=v_site,
                                                id=next(ngid)))

        s.layers['neuronskeleton_{}'.format(
            neuron_id)] = neuroglancer.AnnotationLayer(
                voxel_size=(1, 1, 1),
                filter_by_segmentation=False,
                annotation_color=color,
                annotations=connectors,
            )
        if show_ellipsoid_annotation:
            s.layers['node_u_{}'.format(
                neuron_id)] = neuroglancer.AnnotationLayer(
                    voxel_size=(1, 1, 1),
                    filter_by_segmentation=False,
                    annotation_color=color,
                    annotations=u_nodes,
                )
            s.layers['node_v_{}'.format(
                neuron_id)] = neuroglancer.AnnotationLayer(
                    voxel_size=(1, 1, 1),
                    filter_by_segmentation=False,
                    annotation_color=color,
                    annotations=v_nodes,
                )
Esempio n. 7
0
    def _append_synapse_annotation_layer(
            self, viewer_state: ng.viewer_state.ViewerState, name: str,
            synapses: Synapses):
        annotations = []

        pre_synapses = synapses.pre_with_physical_coordinate
        self._append_point_annotation_layer(viewer_state, name + '_pre',
                                            pre_synapses)

        post_synapses = synapses.post_with_physical_coordinate
        if post_synapses is not None:
            for post_idx in range(post_synapses.shape[0]):
                pre_idx = post_synapses[post_idx, 0]
                pre_coordinate = pre_synapses[pre_idx, :]
                post_coordinate = post_synapses[post_idx, 1:]
                post_annotation = ng.LineAnnotation(
                    id=str(post_idx),
                    # note that the synapse coordinate is already in xyz order
                    # so we do not need to reverse it!
                    pointA=pre_coordinate,
                    pointB=post_coordinate,
                    props=['#0ff', 5])
                annotations.append(post_annotation)

        viewer_state.layers.append(
            name=name,
            layer=ng.LocalAnnotationLayer(
                dimensions=ng.CoordinateSpace(names=['z', 'y', 'x'],
                                              units="nm",
                                              scales=(1, 1, 1)),
                annotation_properties=[
                    ng.AnnotationPropertySpec(
                        id='color',
                        type='rgb',
                        default='red',
                    ),
                    ng.AnnotationPropertySpec(id='size',
                                              type='float32',
                                              default=5)
                ],
                annotations=annotations,
                shader='''
void main() {
  setColor(prop_color());
  setPointMarkerSize(prop_size());
}
''',
            ),
        )
Esempio n. 8
0
def add_trees_no_skeletonization(
    s, trees, node_id, name, dimensions, visible=False, color=None
):
    mst = []
    for u, v in trees.edges():
        pos_u = np.array(trees.nodes[u]["location"]) + 0.5
        pos_v = np.array(trees.nodes[v]["location"]) + 0.5
        mst.append(
            neuroglancer.LineAnnotation(
                point_a=pos_u[::-1], point_b=pos_v[::-1], id=next(node_id)
            )
        )

    s.layers.append(
        name="{}".format(name),
        layer=neuroglancer.AnnotationLayer(annotations=mst),
        annotationColor="#{:02X}{:02X}{:02X}".format(255, 125, 125),
        visible=visible,
    )
Esempio n. 9
0
def add_line_annotations(viewer, xyz0, xyz1, layer_name, color=(1, 1, 1)):
    '''
    Add a collection of points to a point annotation layer. This function will create the layer if need be.
    Each point has a unique id. 
    '''
    extant_layers = [l.name for l in viewer.state.layers]
    if layer_name not in extant_layers:
        add_annotation_layer(viewer, layer_name)
        print("Adding layer {}".format(layer_name))

    with viewer.txn() as s:
        s.layers[layer_name].annotationColor = cl.to_hex(color)
        for ind, xyz0_row in enumerate(xyz0):
            s.layers[layer_name].annotations.append(
                neuroglancer.LineAnnotation(
                    pointA=np.array(xyz0_row, dtype=np.int),
                    pointB=np.array(xyz1[ind, :], dtype=np.int),
                    id=neuroglancer.random_token.make_random_token()))
    set_annotation_color(viewer, layer_name=layer_name, color=color)
    return viewer
Esempio n. 10
0
def show_lines(filepath, name):
    global viewer
    global res
    h5file = h5py.File(filepath, 'r')
    with viewer.txn() as s:
        s.layers.append(name='start_' + name,
                        layer=neuroglancer.AnnotationLayer(voxelSize=res))
        start = s.layers[-1].annotations

        s.layers.append(name='end_' + name,
                        layer=neuroglancer.AnnotationLayer(voxelSize=res))
        end = s.layers[-1].annotations
        line_id = 0
        for key in h5file.keys():
            data = np.asarray(h5file[key])
            start.append(
                neuroglancer.LineAnnotation(id=line_id,
                                            point_a=data[2::-1],
                                            point_b=data[5:2:-1]))
            end.append(
                neuroglancer.PointAnnotation(id=line_id, point=data[0:3]))
            line_id += 1
Esempio n. 11
0
def show_vec_2(direction_vecs_path, vec_lec, name):
    global viewer
    global res
    h5file = h5py.File(direction_vecs_path, 'r')
    for key in h5file.keys():
        line_id = 0
        data = h5file[key]
        with viewer.txn() as s:
            s.layers.append(name='dir_' + key,
                            layer=neuroglancer.AnnotationLayer(voxelSize=res))
            annotations = s.layers[-1].annotations
            for i in range(data.shape[0]):
                annotations.append(
                    neuroglancer.LineAnnotation(id=line_id,
                                                point_a=data[i][2::-1],
                                                point_b=data[i][2::-1] +
                                                vec_lec * data[i][5:2:-1]))
                annotations.append(
                    neuroglancer.PointAnnotation(id=line_id + 500000,
                                                 point=data[i][2::-1] +
                                                 vec_lec * data[i][5:2:-1]))
                line_id += 1
Esempio n. 12
0
def show_matches_pred_npy(filepath, name, weight_th=0.80):
    global viewer
    global res
    with viewer.txn() as s:
        results = np.load(filepath)

        s.layers.append(name='start_' + name,
                        layer=neuroglancer.AnnotationLayer(voxelSize=res))
        start = s.layers[-1].annotations

        s.layers.append(name='end_' + name,
                        layer=neuroglancer.AnnotationLayer(voxelSize=res))
        end = s.layers[-1].annotations
        id = -1
        for data in results:
            if float(data[5]) > weight_th:
                id += 1
                start.append(
                    neuroglancer.LineAnnotation(id=id,
                                                point_a=data[2][::-1],
                                                point_b=data[3][::-1]))
                end.append(
                    neuroglancer.PointAnnotation(id=id, point=data[2][::-1]))
def add_synapses(s,
                 df,
                 pre_neuron_id=None,
                 post_neuron_id=None,
                 color=None,
                 name='',
                 radius=30):
    if pre_neuron_id is not None:
        df = df[df.id_skel_pre == pre_neuron_id]
    if post_neuron_id is not None:
        df = df[df.id_skel_post == post_neuron_id]

    pre_sites, post_sites, connectors = [], [], []
    print('Displaying {} of synapses'.format(len(df)))
    for index, syn in df.iterrows():
        pre_site = np.flip(syn.location_pre)
        post_site = np.flip(syn.location_post)

        pre_sites.append(
            neuroglancer.EllipsoidAnnotation(center=pre_site,
                                             radii=(radius, radius, radius),
                                             id=next(ngid)))
        post_sites.append(
            neuroglancer.EllipsoidAnnotation(center=post_site,
                                             radii=(radius, radius, radius),
                                             id=next(ngid)))
        connectors.append(
            neuroglancer.LineAnnotation(point_a=pre_site,
                                        point_b=post_site,
                                        id=next(ngid)))

    s.layers['synlinks_{}'.format(name)] = neuroglancer.AnnotationLayer(
        voxel_size=(1, 1, 1),
        filter_by_segmentation=False,
        annotation_color=color,
        annotations=connectors,
    )
Esempio n. 14
0
    def _update_synapses(self):
        synapses = {}
        partner_counts = None
        for segment_id in self.selected_segments:
            for synapse in self.synapses_by_id.get(segment_id, []):
                synapses[id(synapse)] = synapse

        for segment_id in self.selected_segments:
            cur_counts = self.synapse_partner_counts.get(
                segment_id, collections.Counter())
            if partner_counts is None:
                partner_counts = cur_counts
                continue
            if self.top_method == 'sum':
                partner_counts = partner_counts + cur_counts
            elif self.top_method == 'min':
                partner_counts = partner_counts & cur_counts
        if partner_counts is None:
            partner_counts = collections.Counter()
        top_partners = sorted((x for x in partner_counts.keys()
                               if x not in self.selected_segments),
                              key=lambda x: -partner_counts[x])
        top_partners = top_partners[:self.num_top_partners]
        with self.viewer.txn() as s:
            s.layers['partners'].segments = top_partners
            annotations = s.layers['synapses'].annotations
            del annotations[:]
            for synapse in six.itervalues(synapses):
                tbar = synapse['T-bar']
                for partner in synapse['partners']:
                    annotations.append(
                        neuroglancer.LineAnnotation(
                            id='%d' % id(partner),
                            point_a=tbar['location'],
                            point_b=partner['location'],
                            segments=[tbar['body ID'], partner['body ID']],
                        ))
Esempio n. 15
0
                             "solved_{}".format(solve_number),
                             edge_collection="edges_g{}".format(graph_number))
    nodes_in_edges = []
    if edges:
        k = 0
        edge_connectors = []
        for u, v, selected, solved in edges:
            try:
                pos_u = (nodes[u][2], nodes[u][1], nodes[u][0])
                pos_v = (nodes[v][2], nodes[v][1], nodes[v][0])
                nodes_in_edges.append(u)
                nodes_in_edges.append(v)

                edge_connectors.append(
                    neuroglancer.LineAnnotation(point_a=pos_u,
                                                point_b=pos_v,
                                                id=k,
                                                segments=None))
                k += 1
            except KeyError:
                pass
        data_k["edge_connectors"] = edge_connectors

    if nodes:
        maxima = []
        maxima_dict = {}
        if not selected_only:
            for node_id, node_data in nodes.items():
                x = node_data[2]
                y = node_data[1]
                z = node_data[0]
                maxima_dict[node_id] = (x, y, z)
Esempio n. 16
0
    add(s, gradient_embedding, "grad_embedding", shader="rgb", visible=False)
    add(s, gradient_fg, "grad_fg", shader="rgb", visible=False)

    mst = []
    node_id = itertools.count(start=1)
    for edge, u, v in zip(emst.to_ndarray(), edges_u.to_ndarray(),
                          edges_v.to_ndarray()):
        if edge[2] > 1.0:
            continue
        pos_u = daisy.Coordinate(u[-3:] * 100) + (
            (0, ) + labels.roi.get_offset())
        pos_v = daisy.Coordinate(v[-3:] * 100) + (
            (0, ) + labels.roi.get_offset())
        mst.append(
            neuroglancer.LineAnnotation(point_a=pos_u[::-1],
                                        point_b=pos_v[::-1],
                                        id=next(node_id)))

    s.layers.append(name="mst",
                    layer=neuroglancer.AnnotationLayer(annotations=mst))

    pb = []
    pbs = {
        int(node_id): node_location
        for node_id, node_location in zip(tuple(trees[:,
                                                      0]), tuple(trees[:,
                                                                       1:-1]))
    }
    for row in trees:
        u = int(row[0])
        v = int(row[-1])
Esempio n. 17
0
def find_post_syn(synapse_df, seg_chunk, sj_labels, offset, 
  rad=(50, 50, 10), max_angle=90.0, border_thickness=(3, 3, 2)):
  input_bb = Bbox((0, 0, 0), seg_chunk.shape)
  synapse_entries = []
  pre_seg_ids = synapse_df.index
  for ind, row in tqdm(synapse_df.iterrows(), total=len(synapse_df), disable=True):
    pos = (row.sj_pos - offset).astype(np.int32)
    inter_bb = Bbox.intersection(input_bb, Bbox(pos - rad, pos + rad))
    if np.product(inter_bb.size3()) == 0: 
      continue
    local_slc = inter_bb.to_slices()
    local_offset = offset + inter_bb.minpt
    
    local_sj_labels = sj_labels[local_slc]
    local_sj_mask = local_sj_labels == row.sj_id
    local_seg_chunk = seg_chunk[local_slc]
    
    post_seg_entries = get_neighbors(local_sj_mask, local_seg_chunk, 
      border_thickness=border_thickness, min_size=5)
    pre_seg_entry = [ps for ps in post_seg_entries if ps['id'] == row.pre_seg_id]
    if len(pre_seg_entry) < 1:
      # if cannot find pre_seg_id in neighbor, which is rare, use vc_pos as pre pos
      pre_pos = np.array(row.vc_pos)
    else:
      # if can find pre_seg_id in neighbor, use the median as pre seg pos
      pre_pos = pre_seg_entry[0]['pos'] + local_offset
    post_seg_entries = [ps for ps in post_seg_entries if ps['id'] != row.pre_seg_id and ps['id'] not in pre_seg_ids]

    
    # chose the largest one that forms obtuse angle vc - sj - post
    for ps in post_seg_entries:
      ps['angle'] = get_angle(pre_pos, row.sj_pos, ps['pos'] +local_offset) 
      # logging.warning('pos %s', ps['pos'])
      # if np.isnan(ps['angle']):
        # logging.warning('failed at %s, %s, %s', pre_pos, ps['pos'])
        # logging.warning('failed at %s, %s, %s', pre_pos, row.sj_pos, ps['pos'] + local_offset)
        # return
    post_seg_entries = [ps for ps in post_seg_entries if ps['angle'] > max_angle]
    if not post_seg_entries: continue
    # each sj can only have one post syn seg partner
    max_ps = max(post_seg_entries, key=lambda ps: ps['size'])
    post_pos = max_ps['pos'] + local_offset 

    synapse_entries.append({
      'pre_seg_id': row.pre_seg_id,
      'post_seg_id': max_ps['id'],
      'vc_id': row.vc_id,
      'vc_pos': row.vc_pos,
      'vc_size': row.vc_size,
      'sj_id': row.sj_id,
      'sj_pos': row.sj_pos.tolist(),
      'sj_size': row.sj_size,
      'sj_norm_size': row.sj_norm_size,
      'sj_value': row.sj_value,
      'pre_seg_pos': pre_pos.tolist(),
      'post_seg_pos': post_pos.tolist()
    })
  new_synapse_df = pd.DataFrame(synapse_entries)
  line_annos = [neuroglancer.LineAnnotation(
    point_a=row.vc_pos,
    point_b=row.post_seg_pos,
    id=ind) for ind, row in new_synapse_df.iterrows()]
  return new_synapse_df, line_annos
Esempio n. 18
0
    for z, y, x, node_id in
    zip(nodes_attrs["center_z"], nodes_attrs["center_y"],
        nodes_attrs["center_x"], nodes_attrs['id'])
}

edges = {(u, v): score
         for u, v, score in zip(edges_attrs["u"], edges_attrs["v"],
                                edges_attrs[config.new_edge_attr_trinary])}
logger.info(f'write nodes and edges to dicts in {time.time() - start}s')

start = time.time()
lines = {}
for i, ((u, v), score) in tqdm(enumerate(edges.items())):
    try:
        l = neuroglancer.LineAnnotation(point_a=np.array(nodes[u])[::-1],
                                        point_b=np.array(nodes[v])[::-1],
                                        id=i)
        lines.setdefault(score, []).append(l)
    except KeyError:
        pass
logger.info(f'create LineAnnotations in {time.time() - start}s')
for k, v in lines.items():
    logger.info(f'layer {k} with {len(v)} edges')

lines = {0: lines[0]}
start = time.time()
# colors_list = list(colors.CSS4_COLORS.values())
colors_list = ['#ffff00', '#00ff00', '#ff00ff']
with viewer.txn() as s:
    for i, (k, v) in tqdm(enumerate(lines.items())):
        # TODO adapt parameters
Esempio n. 19
0
edges = []
print(len(neuron_graph.nodes))
for node_a, node_b in neuron_graph.edges:
    a = swc_to_voxel_coords(neuron_graph.nodes[node_a]["location"], origin, spacing)
    b = swc_to_voxel_coords(neuron_graph.nodes[node_b]["location"], origin, spacing)

    pos_u = a
    pos_v = b

    nodes.append(
        neuroglancer.EllipsoidAnnotation(
            center=pos_u, radii=(3, 3, 3) / voxel_size, id=next(ngid)
        )
    )
    edges.append(
        neuroglancer.LineAnnotation(point_a=pos_u, point_b=pos_v, id=next(ngid))
    )
    if len(nodes) > 10000:
        break
nodes.append(
    neuroglancer.EllipsoidAnnotation(
        center=pos_v, radii=(1, 1, 1) / voxel_size, id=next(ngid)
    )
)


a = daisy.open_ds(str(n5_path.absolute()), "volume")

with viewer.txn() as s:
    add_layer(s, a, "volume", shader="rgb", c=[0, 0, 0])
Esempio n. 20
0
def vis_points_with_array(raw: np.ndarray, points: nx.DiGraph,
                          voxel_size: np.ndarray):
    ngid = itertools.count(start=1)

    neuroglancer.set_server_bind_address("0.0.0.0")
    viewer = neuroglancer.Viewer()

    nodes = []
    edges = []

    for node_a, node_b in points.edges:
        a = points.nodes[node_a]["location"][::-1]
        b = points.nodes[node_b]["location"][::-1]

        pos_u = a
        pos_v = b

        nodes.append(
            neuroglancer.EllipsoidAnnotation(center=pos_u,
                                             radii=(3, 3, 3) / voxel_size,
                                             id=next(ngid)))
        edges.append(
            neuroglancer.LineAnnotation(point_a=pos_u,
                                        point_b=pos_v,
                                        id=next(ngid)))
    nodes.append(
        neuroglancer.EllipsoidAnnotation(center=pos_v,
                                         radii=(1, 1, 1) / voxel_size,
                                         id=next(ngid)))

    print(raw.shape)

    max_raw = np.max(raw)
    min_raw = np.min(raw)
    diff_raw = max_raw - min_raw

    try:
        raw = ((raw - min_raw) / float(diff_raw) * 255).astype("uint8")
    except Exception as e:
        print(min_raw, max_raw)
        raise e

    with viewer.txn() as s:
        s.layers["raw"] = neuroglancer.ImageLayer(
            source=neuroglancer.LocalVolume(data=raw.transpose([2, 1, 0]),
                                            voxel_size=voxel_size))
        s.layers["edges"] = neuroglancer.AnnotationLayer(
            voxel_size=voxel_size,
            filter_by_segmentation=False,
            annotation_color="#add8e6",
            annotations=edges,
        )
        s.layers["nodes"] = neuroglancer.AnnotationLayer(
            voxel_size=voxel_size,
            filter_by_segmentation=False,
            annotation_color="#ff00ff",
            annotations=nodes,
        )
        position = np.array(raw.shape) // 2
        s.navigation.position.voxelCoordinates = tuple(position)
    print(viewer)

    input("done?")
Esempio n. 21
0
def visualize_synapses_in_neuroglancer(s,
                                       synapses,
                                       score_thr=-1,
                                       radius=30,
                                       show_ellipsoid_annotation=False,
                                       name='',
                                       color='#00ff00'):
    pre_sites = []
    post_sites = []
    connectors = []
    below_score = 0
    neuro_id = 0
    for syn in synapses:
        if syn.score is None:
            add_synapse = True
        else:
            add_synapse = syn.score > score_thr
        if not add_synapse:
            below_score += 1
        else:
            pre_site = np.flip(syn.location_pre)
            post_site = np.flip(syn.location_post)
            description = f"id: {syn.id}, pre_seg: {syn.id_segm_pre}, post_seg: {syn.id_segm_post}, score: {syn.score}"
            pre_sites.append(
                neuroglancer.EllipsoidAnnotation(center=pre_site,
                                                 radii=(radius, radius,
                                                        radius),
                                                 id=neuro_id + 1))
            post_sites.append(
                neuroglancer.EllipsoidAnnotation(center=post_site,
                                                 radii=(radius, radius,
                                                        radius),
                                                 id=neuro_id + 2))
            connectors.append(
                neuroglancer.LineAnnotation(point_a=pre_site,
                                            point_b=post_site,
                                            id=neuro_id + 3,
                                            description=description))
            neuro_id += 3

    s.layers['connectors_{}'.format(name)] = neuroglancer.AnnotationLayer(
        voxel_size=(1, 1, 1),
        filter_by_segmentation=False,
        annotation_color=color,
        annotations=connectors,
    )
    if show_ellipsoid_annotation:
        s.layers['pre_sites'] = neuroglancer.AnnotationLayer(
            voxel_size=(1, 1, 1),
            filter_by_segmentation=False,
            annotation_color='#00ff00',
            annotations=pre_sites,
        )
        s.layers['post_sites'] = neuroglancer.AnnotationLayer(
            voxel_size=(1, 1, 1),
            filter_by_segmentation=False,
            annotation_color='#ff00ff',
            annotations=post_sites,
        )
    print('filtered out {}/{} of synapses'.format(below_score, len(synapses)))
    print('displaying {} synapses'.format(len(post_sites)))
    return synapses
Esempio n. 22
0
with viewer.txn() as s:
    s.layers.append(name="den", layer=ngLayer(seg, res))
    s.layers['den'].segments.update(range(1, 30))
    s.layers['den'].visible = True

    s.layers.append(name="nodes", layer=ngLayer(reduced_nodes, res))
    s.layers['nodes'].segments.update(range(1, 3))
    s.layers['nodes'].visible = True

    s.layers.append(name='edges',
                    layer=neuroglancer.AnnotationLayer(voxelSize=res))
    annotations = s.layers[-1].annotations
    line_id = 1
    for edge in edge_list:
        annotations.append(
            neuroglancer.LineAnnotation(id=line_id,
                                        point_a=[
                                            all_nodes[edge[0]][2],
                                            all_nodes[edge[0]][1],
                                            all_nodes[edge[0]][0]
                                        ],
                                        point_b=[
                                            all_nodes[edge[1]][2],
                                            all_nodes[edge[1]][1],
                                            all_nodes[edge[1]][0]
                                        ]))

        line_id += 1

print(viewer)