コード例 #1
0
ファイル: __init__.py プロジェクト: AnthonyAlers/topographica
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))
コード例 #2
0
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))
コード例 #3
0
ファイル: __init__.py プロジェクト: AnthonyAlers/topographica
def fig06_09(template_dir, build_dir, fig, contrasts=(10,25,100),
             selectivity_norm = 1.0, input_seed=102, size_factor=1.0,
             kernel=analysis.gamma_metric, show_raster=False):

    name = 'fig0%d' % fig
    if show_raster: return Display(snapshot=name, template_dir=template_dir)
    template_path, output_dir = setup('fig06_09', template_dir,
                                      build_dir, subdir=name)
    # Get the files containing the relevant data
    output_name = ('Fig0%d' % fig) if fig != 6 else 'Fig05_06'
    pattern = 'jn13_figures/output/%s/*%s_*/*/*.npz' % (output_name, output_name)
    files = lancet.FilePattern('npz_file', pattern)
    info = lancet.FileInfo(files, 'npz_file', lancet.NumpyFile())
    dframe = info.dframe
    # Some basic constants
    max_time = max(dframe['time']); input_seeds = set(dframe['input_seed'])
    all_contrasts = set(dframe['contrast']); all_times = set(dframe['time'])

    savefig_opts = dict(transparent=True, format='svg', bbox_inches='tight', pad_inches=0)
    # Saving all the png/svg components for the three chosen contrasts (subplot D-F)
    boolarr = np.array(dframe['time'] == max_time) & np.array(dframe['input_seed'] == input_seed)
    for contrast in contrasts:
        fname = os.path.join(output_dir, '%%s_%d_%d.%%s' % (contrast, max_time))
        contrast_slice = np.array(dframe['contrast']==contrast)
        row = info.load(dframe[boolarr & contrast_slice]).iloc[0]

        OR_analysis(row, template_dir, output_dir,
                    name='OR_c%s' % contrast, selectivity=True)

        # Collecting preferences/selectivities across time/seeds for map_development plots
        selectivities, stabilities = [],[]
        for seed in input_seeds:
            seed_slice = np.array(dframe['input_seed'] == seed)
            df = info.load(dframe[contrast_slice & seed_slice])
            # Ensuring the data is sorted by simulation time
            sorted_rows = [df[df['time'] == time].iloc[0] for time in sorted(df['time'])]
            prefs = [get_pref(row) for row in sorted_rows]
            # Each selectivity is a whole map, these selectivities are averages across the map
            mean_sels = [get_sel(row).mean() for row in sorted_rows]
            selectivities.append(mean_sels)
            stabilities.append(analysis.stability_index(prefs))

        # Save the stability/selectivity plots
        map_dev = vectorplots.map_development_streams(np.array(stabilities),
                                                      np.array(selectivities),
                                                      selectivity_norm = selectivity_norm)
        fname = os.path.join(output_dir, 'SI_%s.svg' % contrast)
        map_dev.savefig(fname,**savefig_opts)
        vectorplots.close([map_dev])

    # Collect the selectivity, stability and map metric across contrasts and seeds
    selectivities, stabilities, metrics = [],[],[]
    time_slice = np.array(dframe['time'] == max_time)
    for seed in input_seeds:
        seed_slice = np.array(dframe['input_seed'] == seed)
        df = info.load(dframe[time_slice & seed_slice])
        # Ensuring contrasts are sorted
        sorted_rows = [df[df['contrast'] == contrast].iloc[0] for contrast in sorted(df['contrast'])]

        missing_contrasts = set(df['contrast']) ^set(all_contrasts)
        if missing_contrasts != set():
            missing = ', '.join(str(el) for el in missing_contrasts)
            print "Warning: Contrast values %s are missing for seed %d" % (missing, seed)
        # Each selectivity is a whole map, these selectivities are averages across the map
        mean_sels = [get_sel(row).mean() for row in sorted_rows]
        # Computing map quality based on the pinwheel density
        pinwheel_counts = [row['pinwheels'].shape[0] for row in sorted_rows]
        # Pinwheel density is pinwheel count / (kmax**2)
        pinwheel_densities = [(pwcount/row['kmax']**2) for (pwcount,row)
                                      in zip(pinwheel_counts, sorted_rows)]
        metrics.append([kernel(pwd) for pwd in pinwheel_densities])
        selectivities.append(mean_sels)
        # Obtaining the mean stability per contrast, sorted by contrast then by time
        df = info.load(dframe[seed_slice])
        contrast_stabilities = []
        for contrast in sorted(all_contrasts):
            rows = [df[(df['time']==time) & (df['contrast']==contrast)].iloc[0] for time in sorted(all_times)]
            prefs = [get_pref(row) for row in rows]
            mean_stability = np.mean(analysis.stability_index(prefs))
            contrast_stabilities.append(mean_stability)
        stabilities.append(contrast_stabilities)

    # Save the contrast plot
    fname = os.path.join(output_dir, 'contrast.svg')
    args = (sorted(all_contrasts), np.array(selectivities), np.array(stabilities), np.array(metrics))
    contrast_plot = vectorplots.contrast_streams(*args, vlines=contrasts)
    contrast_plot.savefig(fname, **savefig_opts)
    vectorplots.close([contrast_plot])
    # Composing the whole figure together
    svg_path = os.path.join(output_dir, '%s.svg' % name)
    model_list = ['L','AL','GCL','GCAL']
    current_model = model_list[[6,7,8,9].index(fig)]
    mapping = dict([('[CONTRAST%d]' % i,c) for (i,c) in enumerate(contrasts)]
                   + [('[TIME]', int(max_time)),
                      ('[Model-Name]', current_model + " Model")])

    layers = dict((name,name==current_model) for name in model_list)
    return Display(compose.apply_template(template_path, svg_path,
                                             mapping=mapping,
                                             layers=layers,
                                             size_factor=size_factor))
コード例 #4
0
def fig06_09(template_dir,
             build_dir,
             fig,
             contrasts=(10, 25, 100),
             selectivity_norm=1.0,
             input_seed=102,
             size_factor=1.0,
             kernel=analysis.gamma_metric,
             show_raster=False):

    name = 'fig0%d' % fig
    if show_raster: return Display(snapshot=name, template_dir=template_dir)
    template_path, output_dir = setup('fig06_09',
                                      template_dir,
                                      build_dir,
                                      subdir=name)
    # Get the files containing the relevant data
    output_name = ('Fig0%d' % fig) if fig != 6 else 'Fig05_06'
    pattern = 'jn13_figures/output/%s/*%s_*/*/*.npz' % (output_name,
                                                        output_name)
    files = lancet.FilePattern('npz_file', pattern)
    info = lancet.FileInfo(files, 'npz_file', lancet.NumpyFile())
    dframe = info.dframe
    # Some basic constants
    max_time = max(dframe['time'])
    input_seeds = set(dframe['input_seed'])
    all_contrasts = set(dframe['contrast'])
    all_times = set(dframe['time'])

    savefig_opts = dict(transparent=True,
                        format='svg',
                        bbox_inches='tight',
                        pad_inches=0)
    # Saving all the png/svg components for the three chosen contrasts (subplot D-F)
    boolarr = np.array(dframe['time'] == max_time) & np.array(
        dframe['input_seed'] == input_seed)
    for contrast in contrasts:
        fname = os.path.join(output_dir,
                             '%%s_%d_%d.%%s' % (contrast, max_time))
        contrast_slice = np.array(dframe['contrast'] == contrast)
        row = info.load(dframe[boolarr & contrast_slice]).iloc[0]

        OR_analysis(row,
                    template_dir,
                    output_dir,
                    name='OR_c%s' % contrast,
                    selectivity=True)

        # Collecting preferences/selectivities across time/seeds for map_development plots
        selectivities, stabilities = [], []
        for seed in input_seeds:
            seed_slice = np.array(dframe['input_seed'] == seed)
            df = info.load(dframe[contrast_slice & seed_slice])
            # Ensuring the data is sorted by simulation time
            sorted_rows = [
                df[df['time'] == time].iloc[0] for time in sorted(df['time'])
            ]
            prefs = [get_pref(row) for row in sorted_rows]
            # Each selectivity is a whole map, these selectivities are averages across the map
            mean_sels = [get_sel(row).mean() for row in sorted_rows]
            selectivities.append(mean_sels)
            stabilities.append(analysis.stability_index(prefs))

        # Save the stability/selectivity plots
        map_dev = vectorplots.map_development_streams(
            np.array(stabilities),
            np.array(selectivities),
            selectivity_norm=selectivity_norm)
        fname = os.path.join(output_dir, 'SI_%s.svg' % contrast)
        map_dev.savefig(fname, **savefig_opts)
        vectorplots.close([map_dev])

    # Collect the selectivity, stability and map metric across contrasts and seeds
    selectivities, stabilities, metrics = [], [], []
    time_slice = np.array(dframe['time'] == max_time)
    for seed in input_seeds:
        seed_slice = np.array(dframe['input_seed'] == seed)
        df = info.load(dframe[time_slice & seed_slice])
        # Ensuring contrasts are sorted
        sorted_rows = [
            df[df['contrast'] == contrast].iloc[0]
            for contrast in sorted(df['contrast'])
        ]

        missing_contrasts = set(df['contrast']) ^ set(all_contrasts)
        if missing_contrasts != set():
            missing = ', '.join(str(el) for el in missing_contrasts)
            print "Warning: Contrast values %s are missing for seed %d" % (
                missing, seed)
        # Each selectivity is a whole map, these selectivities are averages across the map
        mean_sels = [get_sel(row).mean() for row in sorted_rows]
        # Computing map quality based on the pinwheel density
        pinwheel_counts = [row['pinwheels'].shape[0] for row in sorted_rows]
        # Pinwheel density is pinwheel count / (kmax**2)
        pinwheel_densities = [(pwcount / row['kmax']**2)
                              for (pwcount,
                                   row) in zip(pinwheel_counts, sorted_rows)]
        metrics.append([kernel(pwd) for pwd in pinwheel_densities])
        selectivities.append(mean_sels)
        # Obtaining the mean stability per contrast, sorted by contrast then by time
        df = info.load(dframe[seed_slice])
        contrast_stabilities = []
        for contrast in sorted(all_contrasts):
            rows = [
                df[(df['time'] == time) & (df['contrast'] == contrast)].iloc[0]
                for time in sorted(all_times)
            ]
            prefs = [get_pref(row) for row in rows]
            mean_stability = np.mean(analysis.stability_index(prefs))
            contrast_stabilities.append(mean_stability)
        stabilities.append(contrast_stabilities)

    # Save the contrast plot
    fname = os.path.join(output_dir, 'contrast.svg')
    args = (sorted(all_contrasts), np.array(selectivities),
            np.array(stabilities), np.array(metrics))
    contrast_plot = vectorplots.contrast_streams(*args, vlines=contrasts)
    contrast_plot.savefig(fname, **savefig_opts)
    vectorplots.close([contrast_plot])
    # Composing the whole figure together
    svg_path = os.path.join(output_dir, '%s.svg' % name)
    model_list = ['L', 'AL', 'GCL', 'GCAL']
    current_model = model_list[[6, 7, 8, 9].index(fig)]
    mapping = dict([('[CONTRAST%d]' % i, c)
                    for (i, c) in enumerate(contrasts)] +
                   [('[TIME]', int(max_time)),
                    ('[Model-Name]', current_model + " Model")])

    layers = dict((name, name == current_model) for name in model_list)
    return Display(
        compose.apply_template(template_path,
                               svg_path,
                               mapping=mapping,
                               layers=layers,
                               size_factor=size_factor))