def fig10(template_dir, build_dir, bound_radius=0.6,  selectivity_norm=0.07138,
          size_factor=1.0, show_raster=False):
    name = 'fig10'
    if show_raster: return Display(snapshot=name, template_dir=template_dir)
    times=[2000*i for i in range(6)]
    template_path, output_dir = setup(name, template_dir, build_dir)
    pattern = 'jn13_figures/output/Fig10_12/*/*/*.npz'
    files = lancet.FilePattern('npz_file', pattern)
    file_info = lancet.FileInfo(files, 'npz_file', lancet.NumpyFile())

    filter_times = file_info.dframe['time'].map(lambda x: x in times)
    selection = file_info.load(file_info.dframe[filter_times])

    savefig_opts = dict(transparent=True, format='svg', bbox_inches='tight', pad_inches=0)
    development_info = []
    for (index, row) in selection.iterrows():
        time =row['time']
        fname = os.path.join(output_dir, '%%s_%.1f.png' % int(time))
        bounds = imagen.boundingregion.BoundingBox(radius=0.75)
        sheetcoords = imagen.SheetCoordinateSystem(bounds, xdensity=98)
        roi = slice(*sheetcoords.sheet2matrixidx(bound_radius, bound_radius))
        # Not applying ROI as new bounds will be used
        pref = get_pref(row, roi=roi)
        sel = get_sel(row, roi=roi)
        (cfs, coords) = row['afferent_CFs']

        roi = slice(*sheetcoords.sheet2matrixidx(bound_radius, bound_radius))
        # Create the combined preference/selectivity map
        or_map = rasterplots.OR_map(pref,sel)
        or_black = rasterplots.black_selectivity(or_map)
        (dim1,dim2) = pref.shape
        or_black_resized = rasterplots.resize(or_black, (dim1*4,dim2*4))
        # Save the orientation map
        or_black_resized.save(fname % 'OR')
        # Save the row of CF images
        cf_block  = rasterplots.cf_image(cfs, coords, border=5, width=8, height=1,
                                         pos=(1,4),  bg=(255,255,255))
        cf_block.save(fname % 'CF')
        # Save the FFT of the last map
        if time == times[-1]:
            normalized_spectrum = analysis.power_spectrum(pref[roi,roi])
            fft_im = rasterplots.greyscale(normalized_spectrum)
            fft_im.save(fname % 'FFT')

        # Note: ROI not applied and the values of 3 are due to historical reasons
        development_info.append((time,pref[3:-3, 3:-3], np.mean(sel[3:-3,3:-3])))

    ts, prefs, mean_sels = zip(*sorted(development_info))
    # We only need the stabilities up till 10000
    fname = os.path.join(output_dir, 'model_development.svg')
    development_fig = vectorplots.map_development_plot(analysis.stability_index(prefs),
                                                          mean_sels, selectivity_norm)
    development_fig.savefig(fname, **savefig_opts)
    vectorplots.close([development_fig])
    svg_path = os.path.join(output_dir, '%s.svg' % name)
    return Display(compose.apply_template(template_path, svg_path,
                                             size_factor=size_factor))
def OR_analysis(row, template_dir, build_dir, name='OR_analysis',
                selectivity=False, contours=False,
                cfs=True, scalebox = False, size_factor=1.0,):
    """
    Builds a pinwheel analysis of a single orientation map from a
    template. Used in Figures 3 and 6-9.  Displays an annotated map
    with pinwheels next to the FFT spectrum and corresponding fit.
    The selectivity channel of the map can be enabled as can pinwheel
    contours and a column of central connection fields. The map can
    have either a normal scalebar or a box showing the hypercolumn
    area.
    """
    template_path, output_dir = setup('OR_analysis', template_dir, build_dir, subdir=name)
    savefig_opts = dict(transparent=True, format='svg', bbox_inches='tight', pad_inches=0)
    pref = get_pref(row)
    sel = get_sel(row) if selectivity else None
    fname = os.path.join(output_dir, '%%s_%s.%%s' % name)
    # Save the OR preference and selectivity raster
    or_map = rasterplots.OR_map(pref, sel)
    rasterplots.black_selectivity(or_map).save(fname % ('OR','png'))
    # Save the FFT raster
    rasterplots.greyscale(analysis.power_spectrum(pref)).save(fname % ('FFT','png'))

    # Save the histogram SVG overlay
    hist = vectorplots.FFT_histogram_overlay(row['amplitudes'], row['fit'])
    hist.savefig(fname % ('HIST', 'svg'), **savefig_opts)
    # Save the pinwheel contour SVG overlay
    contours = (row['re_contours'], row['im_contours']) if contours else None
    contour_fig = vectorplots.pinwheel_overlay(row['pinwheels'], contours=contours)
    contour_fig.savefig(fname % ('OVERLAY','svg'), **savefig_opts)

    # Save the CFs (if enabled)
    if cfs and row['afferent_CFs'] is np.nan:
        print "No afferent connection fields found in the given row"
    elif cfs:
        cf_block = rasterplots.cf_image(*row['afferent_CFs'],
                                         border=5, width=1, height=8, pos=(4,1))
        cf_block.save(fname % ('CFs', 'png'))

    # Save the scale bar or scale box SVG overlay
    scale_overlay = (vectorplots.scale_box_overlay if scalebox
                     else vectorplots.scale_bar_overlay)
    scale = scale_overlay(row['units_per_hypercolumn']/float(pref.shape[0]))
    scale.savefig(fname % ('SBOX' if scalebox else 'SBAR', 'svg'), **savefig_opts)
    vectorplots.close([hist, contour_fig, scale])

    layers = {'-scalebox':(not scalebox), '+scalebox':scalebox,
              '-CFs':(not cfs), '+CFs':cfs}

    svg_path = os.path.join(output_dir, '%s.svg' % name)
    return compose.apply_template(template_path, svg_path,
                                  mapping={'[LABEL]':name},
                                  layers=layers,
                                  size_factor=size_factor)
def OR_analysis(
    row,
    template_dir,
    build_dir,
    name='OR_analysis',
    selectivity=False,
    contours=False,
    cfs=True,
    scalebox=False,
    size_factor=1.0,
):
    """
    Builds a pinwheel analysis of a single orientation map from a
    template. Used in Figures 3 and 6-9.  Displays an annotated map
    with pinwheels next to the FFT spectrum and corresponding fit.
    The selectivity channel of the map can be enabled as can pinwheel
    contours and a column of central connection fields. The map can
    have either a normal scalebar or a box showing the hypercolumn
    area.
    """
    template_path, output_dir = setup('OR_analysis',
                                      template_dir,
                                      build_dir,
                                      subdir=name)
    savefig_opts = dict(transparent=True,
                        format='svg',
                        bbox_inches='tight',
                        pad_inches=0)
    pref = get_pref(row)
    sel = get_sel(row) if selectivity else None
    fname = os.path.join(output_dir, '%%s_%s.%%s' % name)
    # Save the OR preference and selectivity raster
    or_map = rasterplots.OR_map(pref, sel)
    rasterplots.black_selectivity(or_map).save(fname % ('OR', 'png'))
    # Save the FFT raster
    rasterplots.greyscale(analysis.power_spectrum(pref)).save(fname %
                                                              ('FFT', 'png'))

    # Save the histogram SVG overlay
    hist = vectorplots.FFT_histogram_overlay(row['amplitudes'], row['fit'])
    hist.savefig(fname % ('HIST', 'svg'), **savefig_opts)
    # Save the pinwheel contour SVG overlay
    contours = (row['re_contours'], row['im_contours']) if contours else None
    contour_fig = vectorplots.pinwheel_overlay(row['pinwheels'],
                                               contours=contours)
    contour_fig.savefig(fname % ('OVERLAY', 'svg'), **savefig_opts)

    # Save the CFs (if enabled)
    if cfs and row['afferent_CFs'] is np.nan:
        print "No afferent connection fields found in the given row"
    elif cfs:
        cf_block = rasterplots.cf_image(*row['afferent_CFs'],
                                        border=5,
                                        width=1,
                                        height=8,
                                        pos=(4, 1))
        cf_block.save(fname % ('CFs', 'png'))

    # Save the scale bar or scale box SVG overlay
    scale_overlay = (vectorplots.scale_box_overlay
                     if scalebox else vectorplots.scale_bar_overlay)
    scale = scale_overlay(row['units_per_hypercolumn'] / float(pref.shape[0]))
    scale.savefig(fname % ('SBOX' if scalebox else 'SBAR', 'svg'),
                  **savefig_opts)
    vectorplots.close([hist, contour_fig, scale])

    layers = {
        '-scalebox': (not scalebox),
        '+scalebox': scalebox,
        '-CFs': (not cfs),
        '+CFs': cfs
    }

    svg_path = os.path.join(output_dir, '%s.svg' % name)
    return compose.apply_template(template_path,
                                  svg_path,
                                  mapping={'[LABEL]': name},
                                  layers=layers,
                                  size_factor=size_factor)
def fig10(template_dir,
          build_dir,
          bound_radius=0.6,
          selectivity_norm=0.07138,
          size_factor=1.0,
          show_raster=False):
    name = 'fig10'
    if show_raster: return Display(snapshot=name, template_dir=template_dir)
    times = [2000 * i for i in range(6)]
    template_path, output_dir = setup(name, template_dir, build_dir)
    pattern = 'jn13_figures/output/Fig10_12/*/*/*.npz'
    files = lancet.FilePattern('npz_file', pattern)
    file_info = lancet.FileInfo(files, 'npz_file', lancet.NumpyFile())

    filter_times = file_info.dframe['time'].map(lambda x: x in times)
    selection = file_info.load(file_info.dframe[filter_times])

    savefig_opts = dict(transparent=True,
                        format='svg',
                        bbox_inches='tight',
                        pad_inches=0)
    development_info = []
    for (index, row) in selection.iterrows():
        time = row['time']
        fname = os.path.join(output_dir, '%%s_%.1f.png' % int(time))
        bounds = imagen.boundingregion.BoundingBox(radius=0.75)
        sheetcoords = imagen.SheetCoordinateSystem(bounds, xdensity=98)
        roi = slice(*sheetcoords.sheet2matrixidx(bound_radius, bound_radius))
        # Not applying ROI as new bounds will be used
        pref = get_pref(row, roi=roi)
        sel = get_sel(row, roi=roi)
        (cfs, coords) = row['afferent_CFs']

        roi = slice(*sheetcoords.sheet2matrixidx(bound_radius, bound_radius))
        # Create the combined preference/selectivity map
        or_map = rasterplots.OR_map(pref, sel)
        or_black = rasterplots.black_selectivity(or_map)
        (dim1, dim2) = pref.shape
        or_black_resized = rasterplots.resize(or_black, (dim1 * 4, dim2 * 4))
        # Save the orientation map
        or_black_resized.save(fname % 'OR')
        # Save the row of CF images
        cf_block = rasterplots.cf_image(cfs,
                                        coords,
                                        border=5,
                                        width=8,
                                        height=1,
                                        pos=(1, 4),
                                        bg=(255, 255, 255))
        cf_block.save(fname % 'CF')
        # Save the FFT of the last map
        if time == times[-1]:
            normalized_spectrum = analysis.power_spectrum(pref[roi, roi])
            fft_im = rasterplots.greyscale(normalized_spectrum)
            fft_im.save(fname % 'FFT')

        # Note: ROI not applied and the values of 3 are due to historical reasons
        development_info.append((time, pref[3:-3,
                                            3:-3], np.mean(sel[3:-3, 3:-3])))

    ts, prefs, mean_sels = zip(*sorted(development_info))
    # We only need the stabilities up till 10000
    fname = os.path.join(output_dir, 'model_development.svg')
    development_fig = vectorplots.map_development_plot(
        analysis.stability_index(prefs), mean_sels, selectivity_norm)
    development_fig.savefig(fname, **savefig_opts)
    vectorplots.close([development_fig])
    svg_path = os.path.join(output_dir, '%s.svg' % name)
    return Display(
        compose.apply_template(template_path,
                               svg_path,
                               size_factor=size_factor))