How to use the cortex.database.db function in cortex

To help you get started, we’ve selected a few cortex examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github gallantlab / pycortex / cortex / brainctm.py View on Github external
def addSurf(self, typename, addtype=True, **kwargs):
        left, right = db.get_surf(self.subject, typename, nudge=False, merge=False)
        self.left.addSurf(left[0], typename, **kwargs)
        self.right.addSurf(right[0], typename, **kwargs)
        if addtype:
            self.types.append(typename)
github gallantlab / pycortex / cortex / quickflat / utils.py View on Github external
def _make_pixel_cache(subject, xfmname, height=1024, thick=32, depth=0.5, sampler='nearest'):
    from scipy import sparse
    from scipy.spatial import Delaunay
    flat, polys = db.get_surf(subject, "flat", merge=True, nudge=True)
    valid = np.unique(polys)
    fmax, fmin = flat.max(0), flat.min(0)
    size = fmax - fmin
    aspect = size[0] / size[1]
    width = int(aspect * height)
    grid = np.mgrid[fmin[0]:fmax[0]:width*1j, fmin[1]:fmax[1]:height*1j].reshape(2,-1)
    
    mask, extents = get_flatmask(subject, height=height)
    assert mask.shape[0] == width and mask.shape[1] == height
    
    ## Get barycentric coordinates
    dl = Delaunay(flat[valid,:2])
    simps = dl.find_simplex(grid.T[mask.ravel()])
    missing = simps == -1
    tfms = dl.transform[simps]
    l1, l2 = (tfms[:,:2].transpose(1,2,0) * (grid.T[mask.ravel()] - tfms[:,2]).T).sum(1)
github gallantlab / pycortex / cortex / utils.py View on Github external
if False, return a list of indices for the ROI

    Returns
    -------
    roidict : dict
        Dictionary of {roi name : roi verts}. ROI verts are for both
        hemispheres, with right hemisphere vertex numbers sequential
        after left hemisphere vertex numbers.
    """
    # Get overlays
    svg = db.get_overlay(subject)

    # Get flat surface so we can figure out which verts are in medial wall
    # or in cuts
    # This assumes subject has flat surface, which they must to have ROIs.
    pts, polys = db.get_surf(subject, "flat", merge=True)
    goodpts = np.unique(polys)

    if roi is None:
        roi = svg.rois.shapes.keys()

    roidict = dict()
    if isinstance(roi, string_types):
        roi = [roi]

    for name in roi:
        roi_idx = np.intersect1d(svg.rois.get_mask(name), goodpts)
        if mask:
            roidict[name] = np.zeros(pts.shape[:1]) > 1
            if np.any(roi_idx):
                roidict[name][roi_idx] = True
            else:
github gallantlab / pycortex / cortex / dataset / __init__.py View on Github external
def _pack_subjs(h5, subjects):
    for subject in subjects:
        rois = db.get_overlay(subject, type='rois')
        rnode = h5.require_dataset("/subjects/%s/rois"%subject, (1,),
            dtype=h5py.special_dtype(vlen=str))
        rnode[0] = rois.toxml(pretty=False)

        surfaces = db.get_paths(subject)['surfs']
        for surf in surfaces.keys():
            for hemi in ("lh", "rh"):
                pts, polys = db.get_surf(subject, surf, hemi)
                group = "/subjects/%s/surfaces/%s/%s"%(subject, surf, hemi)
                _hdf_write(h5, pts, "pts", group)
                _hdf_write(h5, polys, "polys", group)
github gallantlab / pycortex / cortex / webgl / view.py View on Github external
Retrieves named view from pycortex database and sets current
            viewer parameters to retrieved values.

            Parameters
            ----------
            subject : string
                pycortex subject ID
            name : string
                name of saved view to re-load

            Notes
            -----
            Equivalent to call to cortex.db.get_view(subject, vw, name)
            For a list of the view parameters set, see viewer._capture_view
            """
            view = db.get_view(self, subject, name)
github gallantlab / pycortex / cortex / dataset / dataset.py View on Github external
def _pack_subjs(h5, subjects):
    for subject in subjects:
        rois = db.get_overlay(subject)
        rnode = h5.require_dataset("/subjects/%s/rois"%subject, (1,),
                                   dtype=h5py.special_dtype(vlen=str))
        rnode[0] = rois.toxml(pretty=False)

        surfaces = db.get_paths(subject)['surfs']
        for surf in surfaces.keys():
            for hemi in ("lh", "rh"):
                pts, polys = db.get_surf(subject, surf, hemi)
                group = "/subjects/%s/surfaces/%s/%s"%(subject, surf, hemi)
                _hdf_write(h5, pts, "pts", group)
                _hdf_write(h5, polys, "polys", group)
github gallantlab / pycortex / cortex / quickflat / composite.py View on Github external
with_labels : bool
        Whether to display text labels on ROIs
    roi_list : 

    kwargs : 

    Returns
    -------
    img : matplotlib.image.AxesImage
        matplotlib axes image object for plotted data
    """
    if extents is None:
        extents = _get_extents(fig)
    if height is None:
        height = _get_height(fig)        
    svgobject = db.get_overlay(dataview.subject)
    svg_kws = _convert_svg_kwargs(kwargs)
    layer_kws = _parse_defaults('rois_paths')
    layer_kws.update(svg_kws)
    im = svgobject.get_texture('rois', height, labels=with_labels, shape_list=roi_list, **layer_kws)
    _, ax = _get_fig_and_ax(fig)
    img = ax.imshow(im,
                    aspect='equal',
                    interpolation='bicubic',
                    extent=extents,
                    label='rois',
                    zorder=4)
    return img
github gallantlab / pycortex / cortex / svgoverlay.py View on Github external
# I think this should be an entirely separate function, and it should
        # be made clear when this file is created - opening a git issue on 
        # this soon...ML
        with open(svgfile, "wb") as fp:
            fp.write(make_svg(pts.copy(), polys).encode())

        svg = SVGOverlay(svgfile, coords=cullpts, **kwargs)

        ## Add default layers
        from .database import db
        import io
        from . import quickflat
        import binascii

        # Curvature
        curv = db.get_surfinfo(subject, 'curvature')
        curv.cmap = 'gray'
        fp = io.BytesIO()
        quickflat.make_png(fp, curv, height=1024, with_rois=False, with_labels=False)
        fp.seek(0)
        svg.rois.add_shape('curvature', binascii.b2a_base64(fp.read()).decode('utf-8'), False)

    else:
        svg = SVGOverlay(svgfile, 
                         coords=cullpts, 
                         overlays_available=overlays_available,
                         **kwargs)
    
    
    if overlays_available is None:
        # Assure all layers are present
        # (only if some set of overlays is not specified)
github gallantlab / pycortex / cortex / dataset / __init__.py View on Github external
def _pack_subjs(h5, subjects):
    for subject in subjects:
        rois = db.get_overlay(subject, type='rois')
        rnode = h5.require_dataset("/subjects/%s/rois"%subject, (1,),
            dtype=h5py.special_dtype(vlen=str))
        rnode[0] = rois.toxml(pretty=False)

        surfaces = db.get_paths(subject)['surfs']
        for surf in surfaces.keys():
            for hemi in ("lh", "rh"):
                pts, polys = db.get_surf(subject, surf, hemi)
                group = "/subjects/%s/surfaces/%s/%s"%(subject, surf, hemi)
                _hdf_write(h5, pts, "pts", group)
                _hdf_write(h5, polys, "polys", group)
github gallantlab / pycortex / cortex / blender / __init__.py View on Github external
def gii_cut(fname, subject, hemi):
    '''
    Add gifti surface to blender
    '''
    from ..database import db
    hemis = dict(lh='left',
                 rh='right')
    
    wpts, polys = db.get_surf(subject, 'wm', hemi)
    ipts, _ = db.get_surf(subject, 'very_inflated', hemi)
    curvature = db.getSurfInfo(subject, 'curvature')
    rcurv = curvature.__getattribute__(hemis[hemi])

    p = xdrlib.Packer()
    p.pack_array(wpts.ravel(), p.pack_double)
    p.pack_array(ipts.ravel(), p.pack_double)
    p.pack_array(polys.ravel(), p.pack_uint)
    p.pack_array(rcurv.ravel(), p.pack_double)
    with tempfile.NamedTemporaryFile() as tf:
        tf.write(p.get_buffer())
        tf.flush()
        code = """with open('{tfname}', 'rb') as fp:
            u = xdrlib.Unpacker(fp.read())
            wpts = u.unpack_array(u.unpack_double)
            ipts = u.unpack_array(u.unpack_double)
            polys = u.unpack_array(u.unpack_uint)
            curv = u.unpack_array(u.unpack_double)