Beispiel #1
0
    def setup_labels(self, size=None, color=None, shadow=None):
        """Sets up coordinates for labels wrt SVG file (2D flatmap)"""
        # 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()):
                labelpos.append(pos)
                candidates.append((roi, i))

        w, h = self.svgshape
        nolabels = set(candidates)
        txtstyle = "font-family:sans;font-size:%s;font-weight:bold;font-style:italic;fill:%s;fill-opacity:%f;text-anchor:middle;"%(size, color, alpha)
        for text in layer.findall(".//{%s}text"%svgns):
            x = float(text.get('x'))
            y = float(text.get('y'))
            text.attrib['style'] = txtstyle
            text.attrib['data-ptidx'] = str(self.kdt.query((x / w, 1-(y / h)))[1])
            pts, cand = [], []
            for p, c in zip(labelpos, candidates):
                if c[0].name == text.text:
                    pts.append((p[0]*w, (1-p[1])*h))
                    cand.append(c)
            d, idx = cKDTree(pts).query((x,y))
            nolabels.remove(cand[idx])

        for roi, i in nolabels:
            x, y = roi.get_labelpos()[i]
            text = etree.SubElement(layer, "{%s}text"%svgns)
            text.text = roi.name
            text.attrib["x"] = str(x*w)
            text.attrib["y"] = str((1-y)*h)
            if self.shadow > 0:
                text.attrib['filter'] = "url(#dropshadow)"
            text.attrib['style'] = txtstyle
            text.attrib['data-ptidx'] = str(self.kdt.query((x, y))[1])

        self.labels = layer
        return layer
Beispiel #2
0
    def __init__(self, tcoords, svgfile, callback=None, linewidth=None,
                 linecolor=None, roifill=None, shadow=None, labelsize=None,
                 labelcolor=None, dashtype='fromsvg', dashoffset='fromsvg',
                 layer='rois'):
        """Contains ROI data in SVG form

        Stores [[display elements]] from one layer of an svg file.
        Most commonly, these are ROIs. Each ROI (or other display element)
        can contain multiple paths.
        If those paths are closed (i.e., if these are all ROIs), then
        you can use the method ROIpack.get_roi() to get an index of the
        vertices associated with each roi.

        Parameters
        ----------

        Notes
        -----
        The name and the function of this class have begun to diverge. This class
        almost entirely has to do with parsing and storing elements of svg files,
        *SOME* of which are related to ROIs, and some of which are not. In the future,
        this class may be renamed to something like DispPack, display_pack, disp_elements,
        etc

        """
        if isinstance(layer,(list,tuple)):
            # More elegant would be to have ROIpack be a fundamentally multi-layer
            # object, but for backward compatibility and for not breaking other
            # other parts of the code (e.g. finding roi indices, etc) I have kept
            # it this way ML 2014.08.12
            self.svgfile = svgfile
            self.callback = callback
            self.kdt = cKDTree(tcoords)
            self.layer = 'multi_layer'
            self.layers = {}
            self.rois = {}
            self.layer_names = layer
            layer1 = layer[0]
            # Recursive call to create multiple layers
            for iL,L in enumerate(layer):
                self.layers[L] = ROIpack(tcoords, svgfile, callback, linewidth, linecolor,
                    roifill, shadow, labelsize, labelcolor, dashtype, dashoffset,
                    layer=L)
                # Necessary?
                self.rois.update(self.layers[L].rois)
                # # Create combined svg out of individual layer svgs
                if iL == 0:
                    self.tcoords = self.layers[layer1].tcoords
                    svg_fin = copy.copy(self.layers[layer1].svg)
                elif iL>0:
                    to_add = _find_layer(self.layers[L].svg, L)
                    svg_fin.getroot().insert(0, to_add)
            # linewidth, etc not set - set in individual layers
            self.svg = svg_fin
        else:
            # Normalize coordinates 0-1
            if np.any(tcoords.max(0) > 1) or np.any(tcoords.min(0) < 0):
                tcoords -= tcoords.min(0)
                tcoords /= tcoords.max(0)
            self.tcoords = tcoords
            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)
Beispiel #3
0
    def __init__(self, tcoords, svgfile, callback=None, linewidth=None,
                 linecolor=None, roifill=None, shadow=None, labelsize=None,
                 labelcolor=None, dashtype='fromsvg', dashoffset='fromsvg',
                 layer='rois'):
        """Contains ROI data in SVG form 

        Stores [[display elements]] from one layer of an svg file. 
        Most commonly, these are ROIs. Each ROI (or other display element)
        can contain multiple paths. 
        If those paths are closed (i.e., if these are all ROIs), then 
        you can use the method ROIpack.get_roi() to get an index of the
        vertices associated with each roi.

        Parameters
        ----------

        Notes
        -----
        The name and the function of this class have begun to diverge. This class
        almost entirely has to do with parsing and storing elements of svg files, 
        *SOME* of which are related to ROIs, and some of which are not. In the future,
        this class may be renamed to something like DispPack, display_pack, disp_elements,
        etc

        """
        if isinstance(layer,(list,tuple)):
            # More elegant would be to have ROIpack be a fundamentally multi-layer
            # object, but for backward compatibility and for not breaking other
            # other parts of the code (e.g. finding roi indices, etc) I have kept 
            # it this way ML 2014.08.12
            self.svgfile = svgfile
            self.callback = callback
            self.kdt = cKDTree(tcoords)
            self.layer = 'multi_layer'
            self.layers = {}
            self.rois = {}
            self.layer_names = layer
            layer1 = layer[0]
            # Recursive call to create multiple layers
            for iL,L in enumerate(layer):
                self.layers[L] = ROIpack(tcoords, svgfile, callback, linewidth, linecolor, 
                    roifill, shadow, labelsize, labelcolor, dashtype, dashoffset,
                    layer=L)
                # Necessary?
                self.rois.update(self.layers[L].rois)
                # # Create combined svg out of individual layer svgs
                if iL == 0:
                    self.tcoords = self.layers[layer1].tcoords
                    svg_fin = copy.copy(self.layers[layer1].svg)
                elif iL>0:
                    to_add = _find_layer(self.layers[L].svg, L)
                    svg_fin.getroot().insert(0, to_add)
            # linewidth, etc not set - set in individual layers
            self.svg = svg_fin
        else:
            # Normalize coordinates 0-1
            if np.any(tcoords.max(0) > 1) or np.any(tcoords.min(0) < 0):
                tcoords -= tcoords.min(0)
                tcoords /= tcoords.max(0)
            self.tcoords = tcoords
            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)
Beispiel #4
0
    def setup_labels(self, size=None, color=None, shadow=None):
        """Sets up coordinates for labels wrt SVG file (2D flatmap)"""
        # 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()):
                labelpos.append(pos)
                candidates.append((roi, i))

        w, h = self.svgshape
        nolabels = set(candidates)
        txtstyle = "font-family:sans;font-size:%s;font-weight:bold;font-style:italic;fill:%s;fill-opacity:%f;text-anchor:middle;"%(size, color, alpha)
        for text in layer.findall(".//{%s}text"%svgns):
            x = float(text.get('x'))
            y = float(text.get('y'))
            text.attrib['style'] = txtstyle
            text.attrib['data-ptidx'] = str(self.kdt.query((x / w, 1-(y / h)))[1])
            pts, cand = [], []
            for p, c in zip(labelpos, candidates):
                if c[0].name == text.text:
                    pts.append((p[0]*w, (1-p[1])*h))
                    cand.append(c)
            d, idx = cKDTree(pts).query((x,y))
            nolabels.remove(cand[idx])

        for roi, i in nolabels:
            x, y = roi.get_labelpos()[i]
            text = etree.SubElement(layer, "{%s}text"%svgns)
            text.text = roi.name
            text.attrib["x"] = str(x*w)
            text.attrib["y"] = str((1-y)*h)
            if self.shadow > 0:
                text.attrib['filter'] = "url(#dropshadow)"
            text.attrib['style'] = txtstyle
            text.attrib['data-ptidx'] = str(self.kdt.query((x, y))[1])

        self.labels = layer
        return layer
Beispiel #5
0
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')
print(basic_config)