<commit_before>import io
import os
import glob
import binascii
import numpy as np

from . import utils
from . import dataset
from .database import db
from .options import config

def make_figure(braindata, recache=False, pixelwise=True, thick=32, sampler='nearest',
                height=1024, dpi=100, depth=0.5, with_rois=True, with_sulci=False,
                with_labels=True, with_colorbar=True, with_borders=False, 
                with_dropout=False, with_curvature=False, extra_disp=None, 
                linewidth=None, linecolor=None, roifill=None, shadow=None,
                labelsize=None, labelcolor=None, cutout=None, cvmin=None,
                cvmax=None, cvthr=None, fig=None, extra_hatch=None,
                colorbar_ticks=None, **kwargs):
    """Show a Volume or Vertex on a flatmap with matplotlib. Additional kwargs are passed on to
    matplotlib's imshow command.

    Parameters
    ----------
    braindata : Dataview
        the data you would like to plot on a flatmap
    recache : bool
        If True, recache the flatmap cache. Useful if you've made changes to the alignment
    pixelwise : bool
        Use pixel-wise mapping
    thick : int
        Number of layers through the cortical sheet to sample. Only applies for pixelwise = True
    sampler : str
        Name of sampling function used to sample underlying volume data. Options include 
        'trilinear','nearest','lanczos'; see functions in cortex.mapper.samplers.py for all options
    height : int
        Height of the image to render. Automatically scales the width for the aspect
        of the subject's flatmap
    with_rois, with_labels, with_colorbar, with_borders, with_dropout, with_curvature : bool, optional
        Display the rois, labels, colorbar, annotated flatmap borders, or cross-hatch dropout?
    cutout : str
        Name of flatmap cutout with which to clip the full flatmap. Should be the name
        of a sub-layer of the 'cutouts' layer in <filestore>/<subject>/rois.svg

    Other Parameters
    ----------------
    dpi : int
        DPI of the generated image. Only applies to the scaling of matplotlib elements,
        specifically the colormap
    linewidth : int, optional
        Width of ROI lines. Defaults to roi options in your local `options.cfg`
    linecolor : tuple of float, optional
        (R, G, B, A) specification of line color
    roifill : tuple of float, optional
        (R, G, B, A) sepcification for the fill of each ROI region
    shadow : int, optional
        Standard deviation of the gaussian shadow. Set to 0 if you want no shadow
    labelsize : str, optional
        Font size for the label, e.g. "16pt"
    labelcolor : tuple of float, optional
        (R, G, B, A) specification for the label color
    cvmin : float,optional
        Minimum value for curvature colormap. Defaults to config file value.
    cvmax : float, optional
        Maximum value for background curvature colormap. Defaults to config file value.
    cvthr : bool,optional
        Apply threshold to background curvature
    extra_disp : tuple, optional
        Optional extra display layer from external .svg file. Tuple specifies (filename,layer)
        filename should be a full path. External svg file should be structured exactly as 
        rois.svg for the subject. (Best to just copy rois.svg somewhere else and add layers to it)
        Default value is None.
    extra_hatch : tuple, optional
        Optional extra crosshatch-textured layer, given as (DataView, [r, g, b]) tuple. 

    """
    from matplotlib import colors,cm, pyplot as plt
    from matplotlib.collections import LineCollection

    dataview = dataset.normalize(braindata)
    if not isinstance(dataview, dataset.Dataview):
        raise TypeError('Please provide a Dataview, not a Dataset')
    
    if fig is None:
        fig_resize = True
        fig = plt.figure()
    else:
        fig_resize = False
        fig = plt.figure(fig.number)

    im, extents = make(dataview, recache=recache, pixelwise=pixelwise, sampler=sampler,
                       height=height, thick=thick, depth=depth)

    if cutout:
        roi = db.get_overlay(dataview.subject,
                             otype='cutouts',
                             roifill=(0.,0.,0.,0.),
                             linecolor=(0.,0.,0.,0.),
                             linewidth=0.)

        # Set ONLY desired cutout to be white
        roi.rois[cutout].set(roifill=(1.,1.,1.,1.),
                             linewidth=2.,
                             linecolor=(1.,1.,1.,1.))
        roitex = roi.get_texture(height, labels=False)
        roitex.seek(0)
        co = plt.imread(roitex)[:,:,0] # Cutout image
        if not np.any(co):
            raise Exception('No pixels in cutout region %s!'%cutout)

        # STUPID BUT NECESSARY 1-PIXEL CHECK:
        if any([np.abs(aa-bb)>0 and np.abs(aa-bb)<2 for aa,bb in zip(im.shape,co.shape)]):
            from scipy.misc import imresize
            co = imresize(co,im.shape[:2]).astype(np.float32)/255.

        # Alpha
        if im.dtype == np.uint8:
            im = np.cast['float32'](im)/255.
            im[:,:,3]*=co
            h,w,cdim = [float(v) for v in im.shape]
        else:
            im[co==0] = np.nan
            h,w = [float(v) for v in im.shape]

        # set extents
        y,x = np.nonzero(co)
        l,r,t,b = extents
        extents = [x.min()/w * (l-r)+l,
                    x.max()/w * (l-r)+l,
                    y.min()/h * (t-b)+b,
                    y.max()/h * (t-b)+b]

        # bounding box indices
        iy,ix = ((y.min(),y.max()),(x.min(),x.max()))
    else:
        iy,ix = ((0,-1),(0,-1))
    
    if with_curvature:
        curv,ee = make(db.get_surfinfo(dataview.subject),recache=recache)
        if cutout: curv[co==0] = np.nan
        axcv = fig.add_axes((0,0,1,1))
        # Option to use thresholded curvature
        use_threshold_curvature = config.get('curvature','threshold').lower() in ('true','t','1','y','yes') if cvthr is None else cvthr
        if use_threshold_curvature:
            curvT = (curv>0).astype(np.float32)
            curvT[np.isnan(curv)] = np.nan
            curv = curvT
        cvimg = axcv.imshow(curv[iy[1]:iy[0]:-1,ix[0]:ix[1]], 
                aspect='equal', 
                extent=extents, 
                cmap=plt.cm.gray,
                vmin=float(config.get('curvature','min')) if cvmin is None else cvmin,
                vmax=float(config.get('curvature','max')) if cvmax is None else cvmax,
                origin='lower')
        axcv.axis('off')
        axcv.set_xlim(extents[0], extents[1])
        axcv.set_ylim(extents[2], extents[3])

    kwargs = dict(aspect='equal', 
        extent=extents, 
        origin='lower')
    if not isinstance(dataview, (dataset.VolumeRGB, dataset.VertexRGB)):
        # Get colormap from matplotlib or pycortex colormaps
        ## -- redundant code, here and in cortex/dataset/views.py -- ##
        if isinstance(dataview.cmap,(str,unicode)):
            if not dataview.cmap in cm.__dict__:
                # unknown colormap, test whether it's in pycortex colormaps
                cmapdir = config.get('webgl', 'colormaps')
                colormaps = glob.glob(os.path.join(cmapdir, "*.png"))<commit_msg>Fix of a bug in quickflat (height of figure is now correctly propagated)<commit_after>import io
import os
import glob
import binascii
import numpy as np

from . import utils
from . import dataset
from .database import db
from .options import config

def make_figure(braindata, recache=False, pixelwise=True, thick=32, sampler='nearest',
                height=1024, dpi=100, depth=0.5, with_rois=True, with_sulci=False,
                with_labels=True, with_colorbar=True, with_borders=False, 
                with_dropout=False, with_curvature=False, extra_disp=None, 
                linewidth=None, linecolor=None, roifill=None, shadow=None,
                labelsize=None, labelcolor=None, cutout=None, cvmin=None,
                cvmax=None, cvthr=None, fig=None, extra_hatch=None,
                colorbar_ticks=None, **kwargs):
    """Show a Volume or Vertex on a flatmap with matplotlib. Additional kwargs are passed on to
    matplotlib's imshow command.

    Parameters
    ----------
    braindata : Dataview
        the data you would like to plot on a flatmap
    recache : bool
        If True, recache the flatmap cache. Useful if you've made changes to the alignment
    pixelwise : bool
        Use pixel-wise mapping
    thick : int
        Number of layers through the cortical sheet to sample. Only applies for pixelwise = True
    sampler : str
        Name of sampling function used to sample underlying volume data. Options include 
        'trilinear','nearest','lanczos'; see functions in cortex.mapper.samplers.py for all options
    height : int
        Height of the image to render. Automatically scales the width for the aspect
        of the subject's flatmap
    with_rois, with_labels, with_colorbar, with_borders, with_dropout, with_curvature : bool, optional
        Display the rois, labels, colorbar, annotated flatmap borders, or cross-hatch dropout?
    cutout : str
        Name of flatmap cutout with which to clip the full flatmap. Should be the name
        of a sub-layer of the 'cutouts' layer in <filestore>/<subject>/rois.svg

    Other Parameters
    ----------------
    dpi : int
        DPI of the generated image. Only applies to the scaling of matplotlib elements,
        specifically the colormap
    linewidth : int, optional
        Width of ROI lines. Defaults to roi options in your local `options.cfg`
    linecolor : tuple of float, optional
        (R, G, B, A) specification of line color
    roifill : tuple of float, optional
        (R, G, B, A) sepcification for the fill of each ROI region
    shadow : int, optional
        Standard deviation of the gaussian shadow. Set to 0 if you want no shadow
    labelsize : str, optional
        Font size for the label, e.g. "16pt"
    labelcolor : tuple of float, optional
        (R, G, B, A) specification for the label color
    cvmin : float,optional
        Minimum value for curvature colormap. Defaults to config file value.
    cvmax : float, optional
        Maximum value for background curvature colormap. Defaults to config file value.
    cvthr : bool,optional
        Apply threshold to background curvature
    extra_disp : tuple, optional
        Optional extra display layer from external .svg file. Tuple specifies (filename,layer)
        filename should be a full path. External svg file should be structured exactly as 
        rois.svg for the subject. (Best to just copy rois.svg somewhere else and add layers to it)
        Default value is None.
    extra_hatch : tuple, optional
        Optional extra crosshatch-textured layer, given as (DataView, [r, g, b]) tuple. 

    """
    from matplotlib import colors,cm, pyplot as plt
    from matplotlib.collections import LineCollection

    dataview = dataset.normalize(braindata)
    if not isinstance(dataview, dataset.Dataview):
        raise TypeError('Please provide a Dataview, not a Dataset')
    
    if fig is None:
        fig_resize = True
        fig = plt.figure()
    else:
        fig_resize = False
        fig = plt.figure(fig.number)

    im, extents = make(dataview, recache=recache, pixelwise=pixelwise, sampler=sampler,
                       height=height, thick=thick, depth=depth)

    if cutout:
        roi = db.get_overlay(dataview.subject,
                             otype='cutouts',
                             roifill=(0.,0.,0.,0.),
                             linecolor=(0.,0.,0.,0.),
                             linewidth=0.)

        # Set ONLY desired cutout to be white
        roi.rois[cutout].set(roifill=(1.,1.,1.,1.),
                             linewidth=2.,
                             linecolor=(1.,1.,1.,1.))
        roitex = roi.get_texture(height, labels=False)
        roitex.seek(0)
        co = plt.imread(roitex)[:,:,0] # Cutout image
        if not np.any(co):
            raise Exception('No pixels in cutout region %s!'%cutout)

        # STUPID BUT NECESSARY 1-PIXEL CHECK:
        if any([np.abs(aa-bb)>0 and np.abs(aa-bb)<2 for aa,bb in zip(im.shape,co.shape)]):
            from scipy.misc import imresize
            co = imresize(co,im.shape[:2]).astype(np.float32)/255.

        # Alpha
        if im.dtype == np.uint8:
            im = np.cast['float32'](im)/255.
            im[:,:,3]*=co
            h,w,cdim = [float(v) for v in im.shape]
        else:
            im[co==0] = np.nan
            h,w = [float(v) for v in im.shape]

        # set extents
        y,x = np.nonzero(co)
        l,r,t,b = extents
        extents = [x.min()/w * (l-r)+l,
                    x.max()/w * (l-r)+l,
                    y.min()/h * (t-b)+b,
                    y.max()/h * (t-b)+b]

        # bounding box indices
        iy,ix = ((y.min(),y.max()),(x.min(),x.max()))
    else:
        iy,ix = ((0,-1),(0,-1))
    
    if with_curvature:
        curv,ee = make(db.get_surfinfo(dataview.subject),recache=recache,height=height)
        if cutout: curv[co==0] = np.nan
        axcv = fig.add_axes((0,0,1,1))
        # Option to use thresholded curvature
        use_threshold_curvature = config.get('curvature','threshold').lower() in ('true','t','1','y','yes') if cvthr is None else cvthr
        if use_threshold_curvature:
            curvT = (curv>0).astype(np.float32)
            curvT[np.isnan(curv)] = np.nan
            curv = curvT
        cvimg = axcv.imshow(curv[iy[1]:iy[0]:-1,ix[0]:ix[1]], 
                aspect='equal', 
                extent=extents, 
                cmap=plt.cm.gray,
                vmin=float(config.get('curvature','min')) if cvmin is None else cvmin,
                vmax=float(config.get('curvature','max')) if cvmax is None else cvmax,
                origin='lower')
        axcv.axis('off')
        axcv.set_xlim(extents[0], extents[1])
        axcv.set_ylim(extents[2], extents[3])

    kwargs = dict(aspect='equal', 
        extent=extents, 
        origin='lower')
    if not isinstance(dataview, (dataset.VolumeRGB, dataset.VertexRGB)):
        # Get colormap from matplotlib or pycortex colormaps
        ## -- redundant code, here and in cortex/dataset/views.py -- ##
        if isinstance(dataview.cmap,(str,unicode)):
            if not dataview.cmap in cm.__dict__:
                # unknown colormap, test whether it's in pycortex colormaps
                cmapdir = config.get('webgl', 'colormaps')
                colormaps = glob.glob(os.path.join(cmapdir, "*.png"))
{'fraction_non_alphanumeric': 0.105873524797053, 'fraction_numerical': 0.009959751688382564, 'mean_word_length': 2.2015723957195896, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6112057', 'n_tokens_mistral': 4575, 'n_tokens_neox': 4400, 'n_words': 1333}