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

from .. import utils
from .. import dataset
from .utils import make_flatmap_image
from . import composite

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,
                with_connected_vertices=False,
                linewidth=None, linecolor=None, roifill=None, shadow=None,
                labelsize=None, labelcolor=None, cutout=None, curvature_brightness=None,
                curvature_contrast=None, curvature_threshold=None, fig=None, extra_hatch=None,
                colorbar_ticks=None, colorbar_location=(.4, .07, .2, .04), **kwargs):
    """Show a Volume or Vertex on a flatmap with matplotlib.

    Note that **kwargs are ONLY present now for backward compatibility / warnings. No kwargs
    should be used.

    Parameters
    ----------
    braindata : Dataview (e.g. instance of cortex.Volume, cortex.Vertex,...)
        the data you would like to plot on a flatmap
    recache : boolean
        Whether or not to recache intermediate files. Takes longer to plot this way, potentially
        resolves some errors. 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
    depth : float
        Value between 0 and 1 for how deep to sample the surface for the flatmap (0 = gray/white matter
        boundary, 1 = pial surface)
    with_rois, with_labels, with_colorbar, with_borders, with_dropout, with_curvature, etc : bool, optional
        Display the rois, labels, colorbar, annotated flatmap borders, etc
    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>/overlays.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
    curvature_brightness : float, optional
        Mean* brightness of background. 0 = black, 1 = white, intermediate values are corresponding
        grayscale values. If None, Defaults to config file value. (*this does not precisely specify
        the mean; the actual mean luminance of the curvature depends on the value for
        `curvature_contrast`. It's easiest to think about it as the mean brightness, though.)
    curvature_contrast : float, optional
        Contrast of curvature. 1 = maximal contrast (black/white), 0 = no contrast (solid color for
        curvature equal to `curvature_brightness`).
    cvmax : float, optional [DEPRECATED! use `curvature_brightness` and `curvature_contrast` instead]
        Maximum value for background curvature colormap. Defaults to config file value.
    cvthr : bool, optional [DEPRECATED! use `curvature_threshold` instead]
        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
        overlays.svg for the subject. (Best to just copy overlays.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.
    colorbar_location : tuple, optional
        Location of the colorbar! Not sure of what the numbers actually mean. Left, bottom, width, height, maybe?
    fig : figure or ax
        figure into which to plot flatmap
    """
    from matplotlib import pyplot as plt

    dataview = dataset.normalize(braindata)
    if not isinstance(dataview, dataset.Dataview):
        raise TypeError('Please provide a Dataview (e.g. an instance of cortex.Volume, cortex.Vertex, etc), not a Dataset')
    if fig is None:
        fig_resize = True
        fig = plt.figure()
        ax = fig.add_axes((0, 0, 1, 1))
    elif isinstance(fig, plt.Figure):
        fig_resize = False
        fig = plt.figure(fig.number)
        ax = fig.add_axes((0, 0, 1, 1))
    elif isinstance(fig, plt.Axes):
        fig_resize = False
        ax = fig
        fig = ax.figure

    # Add data
    data_im, extents = composite.add_data(ax, dataview, pixelwise=pixelwise, thick=thick, sampler=sampler,
                                          height=height, depth=depth, recache=recache)

    layers = dict(data=data_im)
    # Add curvature
    if with_curvature:
        # backward compatibility
        if any([x in kwargs for x in ['cvmin', 'cvmax', 'cvthr']]):
            import warnings
            warnings.warn(("Use of `cvmin`, `cvmax`, and `cvthr` is deprecated! Please use \n"
                           "`curvature_brightness`, `curvature_contrast`, and `curvature_threshold`\n"
                           "to set appearance of background curvature."))
            legacy_mode = True
            if ('cvmin' in kwargs) and ('cvmax' in kwargs):
                # Assumes that if one is specified, both are; weird case where only one is
                # specified will still break.
                curvature_lims = (kwargs.pop('cvmin'), kwargs.pop('cvmax'))
            else:
                curvature_lims = 0.5
            if 'cvthr' in kwargs:
                curvature_threshold = kwargs.pop('cvthr')
        else:
            curvature_lims = 0.5
            legacy_mode = False
        curv_im = composite.add_curvature(ax, dataview, extents,
                                          brightness=curvature_brightness,
                                          contrast=curvature_contrast,
                                          threshold=curvature_threshold,
                                          curvature_lims=curvature_lims,
                                          legacy_mode=legacy_mode)
        layers['curvature'] = curv_im
    # Add dropout
    if with_dropout is not False:
        # Support old api:
        if isinstance(with_dropout, dataset.Dataview):
            hatch_data = with_dropout
        else:
            hatch_data = None
            dropout_power = 20 if with_dropout is True else with_dropout
        if hatch_data is None:
            hatch_data = utils.get_dropout(dataview.subject, dataview.xfmname,
                                           power=dropout_power)

        drop_im = composite.add_hatch(ax, hatch_data, extents=extents, height=height,
                                      sampler=sampler)
        layers['dropout'] = drop_im
    # Add extra hatching
    if extra_hatch is not None:
        hatch_data2, hatch_color = extra_hatch
        hatch_im = composite.add_hatch(ax, hatch_data2, extents=extents, height=height,
                                       sampler=sampler)
        layers['hatch'] = hatch_im
    # Add rois
    if with_rois:
        roi_im = composite.add_rois(ax, dataview, extents=extents, height=height, linewidth=linewidth, linecolor=linecolor,
                                    roifill=roifill, shadow=shadow, labelsize=labelsize, labelcolor=labelcolor,
                                    with_labels=with_labels)
        layers['rois'] = roi_im
    # Add sulci
    if with_sulci:
        sulc_im = composite.add_sulci(ax, dataview, extents=extents, height=height, linewidth=linewidth, linecolor=linecolor,
                                      shadow=shadow, labelsize=labelsize, labelcolor=labelcolor, with_labels=with_labels)
        layers['sulci'] = sulc_im
    # Add custom
    if extra_disp is not None:
        svgfile, layer = extra_disp
        custom_im = composite.add_custom(ax, dataview, svgfile, layer, height=height, extents=extents,
                                         linewidth=linewidth, linecolor=linecolor, shadow=shadow, labelsize=labelsize,
                                         labelcolor=labelcolor, with_labels=with_labels)
        layers['custom'] = custom_im
    # Add connector lines btw connected vertices
    if with_connected_vertices:
        vertex_lines = composite.add_connected_vertices(ax, dataview)

    ax.axis('off')
    ax.set_xlim(extents[0], extents[1])
    ax.set_ylim(extents[2], extents[3])

    if fig_resize:
        imsize = fig.get_axes()[0].get_images()[0].get_size()
        fig.set_size_inches(np.array(imsize)[::-1] / float(dpi))

    # Add (apply) cutout of flatmap<commit_msg>pass recache parameter to composite functions<commit_after>import io
import os
import tempfile
import binascii
import numpy as np

from .. import utils
from .. import dataset
from .utils import make_flatmap_image
from . import composite

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,
                with_connected_vertices=False,
                linewidth=None, linecolor=None, roifill=None, shadow=None,
                labelsize=None, labelcolor=None, cutout=None, curvature_brightness=None,
                curvature_contrast=None, curvature_threshold=None, fig=None, extra_hatch=None,
                colorbar_ticks=None, colorbar_location=(.4, .07, .2, .04), **kwargs):
    """Show a Volume or Vertex on a flatmap with matplotlib.

    Note that **kwargs are ONLY present now for backward compatibility / warnings. No kwargs
    should be used.

    Parameters
    ----------
    braindata : Dataview (e.g. instance of cortex.Volume, cortex.Vertex,...)
        the data you would like to plot on a flatmap
    recache : boolean
        Whether or not to recache intermediate files. Takes longer to plot this way, potentially
        resolves some errors. 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
    depth : float
        Value between 0 and 1 for how deep to sample the surface for the flatmap (0 = gray/white matter
        boundary, 1 = pial surface)
    with_rois, with_labels, with_colorbar, with_borders, with_dropout, with_curvature, etc : bool, optional
        Display the rois, labels, colorbar, annotated flatmap borders, etc
    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>/overlays.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
    curvature_brightness : float, optional
        Mean* brightness of background. 0 = black, 1 = white, intermediate values are corresponding
        grayscale values. If None, Defaults to config file value. (*this does not precisely specify
        the mean; the actual mean luminance of the curvature depends on the value for
        `curvature_contrast`. It's easiest to think about it as the mean brightness, though.)
    curvature_contrast : float, optional
        Contrast of curvature. 1 = maximal contrast (black/white), 0 = no contrast (solid color for
        curvature equal to `curvature_brightness`).
    cvmax : float, optional [DEPRECATED! use `curvature_brightness` and `curvature_contrast` instead]
        Maximum value for background curvature colormap. Defaults to config file value.
    cvthr : bool, optional [DEPRECATED! use `curvature_threshold` instead]
        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
        overlays.svg for the subject. (Best to just copy overlays.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.
    colorbar_location : tuple, optional
        Location of the colorbar! Not sure of what the numbers actually mean. Left, bottom, width, height, maybe?
    fig : figure or ax
        figure into which to plot flatmap
    """
    from matplotlib import pyplot as plt

    dataview = dataset.normalize(braindata)
    if not isinstance(dataview, dataset.Dataview):
        raise TypeError('Please provide a Dataview (e.g. an instance of cortex.Volume, cortex.Vertex, etc), not a Dataset')
    if fig is None:
        fig_resize = True
        fig = plt.figure()
        ax = fig.add_axes((0, 0, 1, 1))
    elif isinstance(fig, plt.Figure):
        fig_resize = False
        fig = plt.figure(fig.number)
        ax = fig.add_axes((0, 0, 1, 1))
    elif isinstance(fig, plt.Axes):
        fig_resize = False
        ax = fig
        fig = ax.figure

    # Add data
    data_im, extents = composite.add_data(ax, dataview, pixelwise=pixelwise, thick=thick, sampler=sampler,
                                          height=height, depth=depth, recache=recache)

    layers = dict(data=data_im)
    # Add curvature
    if with_curvature:
        # backward compatibility
        if any([x in kwargs for x in ['cvmin', 'cvmax', 'cvthr']]):
            import warnings
            warnings.warn(("Use of `cvmin`, `cvmax`, and `cvthr` is deprecated! Please use \n"
                           "`curvature_brightness`, `curvature_contrast`, and `curvature_threshold`\n"
                           "to set appearance of background curvature."))
            legacy_mode = True
            if ('cvmin' in kwargs) and ('cvmax' in kwargs):
                # Assumes that if one is specified, both are; weird case where only one is
                # specified will still break.
                curvature_lims = (kwargs.pop('cvmin'), kwargs.pop('cvmax'))
            else:
                curvature_lims = 0.5
            if 'cvthr' in kwargs:
                curvature_threshold = kwargs.pop('cvthr')
        else:
            curvature_lims = 0.5
            legacy_mode = False
        curv_im = composite.add_curvature(ax, dataview, extents,
                                          brightness=curvature_brightness,
                                          contrast=curvature_contrast,
                                          threshold=curvature_threshold,
                                          curvature_lims=curvature_lims,
                                          legacy_mode=legacy_mode,
                                          recache=recache)
        layers['curvature'] = curv_im
    # Add dropout
    if with_dropout is not False:
        # Support old api:
        if isinstance(with_dropout, dataset.Dataview):
            hatch_data = with_dropout
        else:
            hatch_data = None
            dropout_power = 20 if with_dropout is True else with_dropout
        if hatch_data is None:
            hatch_data = utils.get_dropout(dataview.subject, dataview.xfmname,
                                           power=dropout_power)

        drop_im = composite.add_hatch(ax, hatch_data, extents=extents, height=height,
                                      sampler=sampler, recache=recache)
        layers['dropout'] = drop_im
    # Add extra hatching
    if extra_hatch is not None:
        hatch_data2, hatch_color = extra_hatch
        hatch_im = composite.add_hatch(ax, hatch_data2, extents=extents, height=height,
                                       sampler=sampler, recache=recache)
        layers['hatch'] = hatch_im
    # Add rois
    if with_rois:
        roi_im = composite.add_rois(ax, dataview, extents=extents, height=height, linewidth=linewidth, linecolor=linecolor,
                                    roifill=roifill, shadow=shadow, labelsize=labelsize, labelcolor=labelcolor,
                                    with_labels=with_labels)
        layers['rois'] = roi_im
    # Add sulci
    if with_sulci:
        sulc_im = composite.add_sulci(ax, dataview, extents=extents, height=height, linewidth=linewidth, linecolor=linecolor,
                                      shadow=shadow, labelsize=labelsize, labelcolor=labelcolor, with_labels=with_labels)
        layers['sulci'] = sulc_im
    # Add custom
    if extra_disp is not None:
        svgfile, layer = extra_disp
        custom_im = composite.add_custom(ax, dataview, svgfile, layer, height=height, extents=extents,
                                         linewidth=linewidth, linecolor=linecolor, shadow=shadow, labelsize=labelsize,
                                         labelcolor=labelcolor, with_labels=with_labels)
        layers['custom'] = custom_im
    # Add connector lines btw connected vertices
    if with_connected_vertices:
        vertex_lines = composite.add_connected_vertices(ax, dataview, recache=recache)

    ax.axis('off')
    ax.set_xlim(extents[0], extents[1])
    ax.set_ylim(extents[2], extents[3])

    if fig_resize:
        imsize = fig.get_axes()[0].get_images()[0].get_size()
        fig.set_size_inches(np.array(imsize)[::-1] / float(dpi))

    # Add (apply) cutout of flatmap
{'fraction_non_alphanumeric': 0.07627467105263158, 'fraction_numerical': 0.005242598684210526, 'mean_word_length': 2.3214407647661317, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 50, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1844048', 'n_tokens_mistral': 5496, 'n_tokens_neox': 5303, 'n_words': 1784}