How to use the cortex.options.config.get 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 / svgroi.py View on Github external
self.svgfile = svgfile
            self.callback = callback
            self.kdt = cKDTree(tcoords)
            self.layer = layer
            # Display parameters
            if layer in config.sections():
                dlayer = layer
            else:
                # Unknown display layer; default to values for ROIs
                import warnings
                warnings.warn('No defaults set for display layer %s; Using defaults for ROIs in options.cfg file'%layer)
                dlayer = 'rois'
            self.linewidth = float(config.get(dlayer, "line_width")) if linewidth is None else linewidth
            self.linecolor = tuple(map(float, config.get(dlayer, "line_color").split(','))) if linecolor is None else linecolor
            self.roifill = tuple(map(float, config.get(dlayer, "fill_color").split(','))) if roifill is None else roifill
            self.shadow = float(config.get(dlayer, "shadow")) if shadow is None else shadow

            # For dashed lines, default to WYSIWYG from rois.svg
            self.dashtype = dashtype
            self.dashoffset = dashoffset

            self.reload(size=labelsize, color=labelcolor)
github gallantlab / pycortex / cortex / blender / __init__.py View on Github external
import os
import six
import shlex
import xdrlib
import tempfile
import subprocess as sp

import numpy as np

from .. import options
from .. import freesurfer
from .. import dataset
from .. import utils 

default_blender = options.config.get('dependency_paths', 'blender')

_base_imports = """import sys
sys.path.insert(0, '{path}')
import xdrlib
import blendlib
import bpy.ops
from bpy import context as C
from bpy import data as D
""".format(path=os.path.split(os.path.abspath(__file__))[0])

def _call_blender(filename, code, blender_path=default_blender):
    """Call blender, while running the given code. If the filename doesn't exist, save a new file in that location.
    New files will be initially cleared by deleting all objects.
    """
    with tempfile.NamedTemporaryFile() as tf:
        print("In new named temp file: %s"%tf.name)
github gallantlab / pycortex / cortex / svgroi.py View on Github external
# Recursive call for multiple layers
        if self.layer == 'multi_layer':
            label_layers = []
            for L in self.layer_names:
                label_layers.append(self.layers[L].setup_labels())
                self.svg.getroot().insert(0, label_layers[-1])
            return label_layers
        if self.layer in config.sections():
            dlayer = self.layer
        else:
            # Unknown display layer; default to values for ROIs
            import warnings
            warnings.warn('No defaults set for display layer %s; Using defaults for ROIs in options.cfg file'%self.layer)
            dlayer = 'rois'
        if size is None:
            size = config.get(dlayer, "labelsize")
        if color is None:
            color = tuple(map(float, config.get(dlayer, "labelcolor").split(",")))
        if shadow is None:
            shadow = self.shadow

        alpha = color[3]
        color = "rgb(%d, %d, %d)"%(color[0]*255, color[1]*255, color[2]*255)

        try:
            layer = _find_layer(self.svg, "%s_labels"%self.layer)
        except ValueError: # Changed in _find_layer below... AssertionError: # Why assertion error?
            layer = _make_layer(self.svg.getroot(), "%s_labels"%self.layer)

        labelpos, candidates = [], []
        for roi in list(self.rois.values()):
            for i, pos in enumerate(roi.get_labelpos()):
github gallantlab / pycortex / cortex / mayavi_aligner.py View on Github external
except:
    outline_reps = tuple(outline_reps)

class Align(HasTraits):
    # The position of the view
    position = Array(shape=(3,))

    brightness = Range(-2., 2., value=0.)
    contrast = Range(0., 3., value=1.)
    opacity = Range(0., 1., value=.1)
    colormap = Enum(*lut_manager.lut_mode_list())
    fliplut = Bool

    outlines_visible = Bool(default_value=True)
    outline_rep = Enum(outline_reps)
    outline_color = Color(default=options.config.get("mayavi_aligner", "outline_color"))
    line_width = Range(0.5, 10., value=float(options.config.get("mayavi_aligner", "line_width")))
    point_size = Range(0.5, 10., value=float(options.config.get("mayavi_aligner", "point_size")))

    epi_filter = Enum(None, "median", "gradient")
    filter_strength = Range(1, 20, value=3)

    scene_3d = Instance(MlabSceneModel, ())
    scene_x = Instance(MlabSceneModel, ())
    scene_y = Instance(MlabSceneModel, ())
    scene_z = Instance(MlabSceneModel, ())

    # The data source
    epi_src = Instance(Source)
    surf_src = Instance(Source)
    xfm = Instance(Filter)
    surf = Instance(Module)
github gallantlab / pycortex / examples / quickstart / show_config.py View on Github external
Easily locating your config file and filestore locations.
This comes in useful when things don't work because the config file is not set correctly.
"""
from __future__ import print_function
import cortex
from cortex.options import config

##########################################################
# Finding where your config file is.
print(cortex.options.usercfg)

##########################################################
# Finding where the current filestore is.
# Useful for when your subjects don't show up in cortex.db, and all you have is S1.
print(config.get('basic', 'filestore'))

##########################################################
# Finding where pycortex is looking for colormaps.
# Useful for when you get color map not found messages.
print(config.get('webgl', 'colormaps'))

##########################################################
# To look at your config file, it is recommended that you open it with a text editor.
# However, you *can* still look at options from within pycortex.

# sections gets the upper-level sections in the config file
sections = config.sections()
print(sections)

# items gets the option items within a section as a list of key-value pairs.
basic_config = config.items('paths_default')
github gallantlab / pycortex / cortex / utils.py View on Github external
Parameters
    ----------
    cmap : matplotlib colormap
        Color map to be saved
    name : 
        Name for colormap, e.g. 'jet', 'blue_to_yellow', etc. This will be a file name,
        so no weird characters. This name will also be used to specify this colormap in 
        future calls to cortex.quickflat.make_figure() or cortex.webgl.show()
    """
    import matplotlib.pyplot as plt
    from matplotlib import colors
    x = np.linspace(0, 1, 256)
    cmap_im = cmap(x).reshape((1,256,4))
    if cmapdir is None:
        # Probably won't work due to permissions...
        cmapdir = config.get('webgl', 'colormaps')
    plt.imsave(os.path.join(cmapdir, name), cmap_im)
github gallantlab / pycortex / cortex / dataset / view2D.py View on Github external
import os
import json
import numpy as np

from .. import options
from .views import Dataview, Volume, Vertex, VolumeRGB, VertexRGB
from .braindata import VolumeData, VertexData

default_cmap2D = options.config.get("basic", "default_cmap2D")

class Dataview2D(Dataview):
    """Abstract base class for 2-dimensional data views.
    """
    def __init__(self, description="", cmap=None, vmin=None, vmax=None, vmin2=None, vmax2=None, state=None, **kwargs):
        self.cmap = cmap or default_cmap2D
        self.vmin = vmin
        self.vmax = vmax
        self.vmin2 = vmin if vmin2 is None else vmin2
        self.vmax2 = vmax if vmax2 is None else vmax2

        self.state = state
        self.attrs = kwargs
        if 'priority' not in self.attrs:
            self.attrs['priority'] = 1
        self.description = description
github gallantlab / pycortex / cortex / quickflat / composite.py View on Github external
name for colormap of curvature
    recache : boolean
        Whether or not to recache intermediate files. Takes longer to plot this way, potentially
        resolves some errors.

    Returns
    -------
    img : matplotlib.image.AxesImage
        matplotlib axes image object for plotted data

    """
    from matplotlib.colors import Normalize
    if height is None:
        height = _get_height(fig)
    # Get curvature map as image
    default_smoothing = config.get('curvature', 'smooth')
    if default_smoothing.lower()=='none':
        default_smoothing = None
    else:
        default_smoothing = np.float(default_smoothing)
    if smooth is None:
        # (Might still be None!)
        smooth = default_smoothing
    if smooth is None:
        # If no value for 'smooth' is given in kwargs, db.get_surfinfo returns
        # the default curvature value, whatever that may be. This is the behavior
        # that we want a None in the code to invoke. This is silly and complicated
        # due to backward compatibility issues with some old subjects.
        curv_vertices = db.get_surfinfo(dataview.subject)
    else:
        curv_vertices = db.get_surfinfo(dataview.subject, smooth=smooth)
    curv, _ = make_flatmap_image(curv_vertices, recache=recache, height=height)
github gallantlab / pycortex / cortex / polyutils / exact_geodesic.py View on Github external
- uses external authors' implementation of [Qin el al 2016]
        - https://github.com/YipengQin/VTP_source_code
        - vtp code must be compiled separately to produce VTP executable
        - once compiled, place path to VTP executable in pycortex config
        - i.e. in config put:
            [geodesic]
            vtp_path = /path/to/compiled/VTP

        Parameters
        ----------
        - vertex : int
            index of vertex to compute geodesic distance from
        """

        if config.has_option('geodesic', 'vtp_path'):
            vtp_path = config.get('geodesic', 'vtp_path')
        else:
            raise ExactGeodesicException('must set config["geodesic"]["vtp_path"]')

        if not os.path.exists(vtp_path):
            raise ExactGeodesicException('vtp_path does not exist: ' + str(vtp_path))

        # initialize temporary files
        f_obj, tmp_obj_path = tempfile.mkstemp()
        f_output, tmp_output_path = tempfile.mkstemp()

        # create object file
        formats.write_obj(tmp_obj_path, self.pts, self.polys)

        # run algorithm
        cmd = [vtp_path, '-m', tmp_obj_path, '-s', str(vertex), '-o', tmp_output_path]
        subprocess.call(cmd)
github gallantlab / pycortex / cortex / database.py View on Github external
"""
import os
import re
import copy
import glob
import json
import shutil
import warnings
import tempfile
import functools
import numpy as np
from hashlib import sha1

from . import options

default_filestore = options.config.get('basic', 'filestore')


def _memo(fn):
    @functools.wraps(fn)
    def memofn(self, *args, **kwargs):
        if not hasattr(self, "_memocache"):
            setattr(self, "_memocache", dict())
        #h = sha1(str((id(fn), args, kwargs))).hexdigest()
        h = str((id(fn), args, kwargs))
        if h not in self._memocache:
            self._memocache[h] = fn(self, *args, **kwargs)
        return copy.deepcopy(self._memocache[h])

    return memofn

class SubjectDB(object):