def main():
    from sys import argv
    if len(argv) < 4:
        print "Insufficient arguments!"
        print "Proper Usage: %s [db_path] [experiment_path] [offset_file]"
        return

    db_path = path.expanduser(argv[1])
    db_man = io.ImageDbManager(db_path, readonly=False)

    experiment_path = path.expanduser(argv[2])
    meta_man = io.MetadataManager(experiment_path)

    offset_path = path.expanduser(argv[3])
    offsets = json.load(open(offset_path))

    for i, offset in enumerate(offsets):
        print "Updating image %d/%d" % (i, len(offsets))
        key = offset['vsi_path'][2:]

        try:
            image = db_man.get_image(key)
            image.region_map_offset = offset['pad_size']

            metadata = meta_man.get_entry_by_attribute('vsiPath', key)
            region_map = io.load_mhd(path.join(experiment_path, metadata['registeredAtlasLabelsPath']))[0]
            hemisphere_map = io.load_mhd(path.join(experiment_path, metadata['registeredHemisphereLabelsPath']))[0]

            image.region_map = numpy.rot90(region_map, k=2)
            image.hemisphere_map = numpy.rot90(hemisphere_map, k=2)

            db_man.add_image(image)

        except:
            print "Failed to update image with key: %s" % key
def main():
    from sys import argv
    if len(argv) < 4:
        print "Insufficient Arguments!"
        print "Proper Usage: %s [structure_data_path] [structure_data_mhd] [output_path]" % argv[0]
        return

    structure_data_path, structure_mhd_path, output_path = map(path.expanduser, argv[1:4])
    
    struct_finder = allen_atlas.StructureFinder(structure_data_path)
    struct_image = io.load_mhd(structure_mhd_path)[0]
   
    # The second argment to numpy.split indictes the indicies to split at, so we exclude 0
    area_maps = [StructureAreaMapper(image, struct_finder.structureData).area_map 
        for image in numpy.split(struct_image, range(1, struct_image.shape[0]))]

    structure_size_table = pandas.DataFrame()

    for depth, area_map in enumerate(area_maps):
        regions, region_areas = zip(*area_map.iteritems())
        depths = [depth] * len(regions)
        slice_df = pandas.DataFrame({
            'depth': depths,
            'region': regions,
            'area': region_areas
        })

        structure_size_table = pandas.concat((structure_size_table, slice_df))

    structure_size_table.to_csv(output_path)
def main():
    from sys import argv
    if len(argv) < 4:
        print "Insufficient Arguments!"
        print "Proper Usage: %s [db_path] [csv_path] [experiment_path] [output_dir]"
        return

    db_path = path.expanduser(argv[1])
    csv_path = path.expanduser(argv[2])
    experiment_path = path.expanduser(argv[3])

    if len(argv) < 5:
        output_dir = path.join(experiment_path, 'detected_cell_overlays')
        print "Output dir not specified!"
        print "Saving output images to %s" % output_dir
    else:
        output_dir = path.expanduser(argv[4])

    if not path.exists(output_dir):
        mkdir(output_dir)

    db_man = io.ImageDbManager(db_path)
    metadata_man = io.MetadataManager(experiment_path)
    df = pandas.read_csv(csv_path)
    df = df[numpy.logical_not(df.disqualified)]
    df = df[df.region > 0]
    df = df[(df.number_of_pixels > 350) & (df.number_of_pixels < 7000)]
    df = df[df['95th percentile'] > 2**-8.5]

    for image in db_man.get_image_iter():
        # Get corresponding metadata
        entry = metadata_man.get_entry_by_attribute('vsiPath', image.source_path)
        rows = df[df['image'] == path.basename(image.source_path)]

        # Load downsampled image
        ds_im_path = path.join(experiment_path, entry['downsampledImagePath'])
        ds_im = io.load_mhd(ds_im_path)[0]

        figure()
        imshow(ds_im, cmap=cm.Greys)

        if not rows.empty:
            # Plot cells
            centroids = [centroid_to_index(centroid, image.region_map_scale, image.region_map_offset) 
                for centroid in imap(numpy.asarray, izip(rows['centroid_row'], rows['centroid_col']))]
            rows, cols = zip(*centroids)

            scatter(cols, rows, color='b', s=2, alpha=.3)

        # Save image
        output_path = generate_output_path(output_dir, entry)
        savefig(output_path)
        close()
def main():
    from sys import argv
    if len(argv) < 4:
        print "Insufficient Arguments!"
        print "Proper Usage: %s [experiment_path] [structure_data_path] [output_path]" % argv[0]
        return

    experiment_path, structure_data_path, output_path = map(path.expanduser, argv[1:4])

    struct_finder = allen_atlas.StructureFinder(structure_data_path)
    meta_man = io.MetadataManager(experiment_path)
    
    image_stats_table = pandas.DataFrame()

    for entry in meta_man.metadata:
        print "Importing data from %s ..." % entry['vsiPath']
        try:
            region_map = io.load_mhd(path.join(experiment_path, entry['registeredAtlasLabelsPath']))[0]
            hemisphere_map = io.load_mhd(path.join(experiment_path, entry['registeredHemisphereLabelsPath']))[0]
        except:
            print "Could not load registration results for %s.  Registration probably failed" % entry['vsiPath']
            # It is nice to know which images have been excluded from registration.
            # This is as much information as we can extract from the metadata entry
            image_stats_table = pandas.concat(
                (
                    image_stats_table,
                    pandas.DataFrame({
                        'image': [path.basename(entry['vsiPath'])],
                        'animal': [dataframes.get_animal(entry['vsiPath'])],
                        'slide': [dataframes.get_slide(entry['vsiPath'])],
                        'condition': [dataframes.get_class(entry['vsiPath'])],
                        'excluded_from_registration': [entry.get('exclude', True)]
                    })
                )
            )

            continue

        for hemisphere in (1, 2):
            lateral_region_map = region_map * (hemisphere_map == hemisphere)
            lateral_area_map = StructureAreaMapper(lateral_region_map, struct_finder.structureData).area_map
            regions, region_areas = zip(*lateral_area_map.iteritems())

            image_names = [path.basename(entry['vsiPath'])] * len(regions)
            animals = [dataframes.get_animal(entry['vsiPath'])] * len(regions)
            slides = [dataframes.get_slide(entry['vsiPath'])] * len(regions)
            conditions = [dataframes.get_class(entry['vsiPath'])] * len(regions)
            hemispheres = [hemisphere] * len(regions)
            exclusions = [entry.get('exclude', False)] * len(regions)

            depths = [entry.get('atlasIndex', None)] * len(regions)
            usabilities = [entry.get('sliceUsable', None)] * len(regions)

            disqualifications = [[region, hemisphere] in entry.get('regionIdsToExclude', []) 
                                    for region in regions]

            update_df = pandas.DataFrame({
                'image': image_names,
                'animal': animals,
                'slide': slides,
                'condition': conditions,
                'depth': depths,
                'slice_usable': usabilities,
                'disqualified': disqualifications,
                'region': regions,
                'hemisphere': hemispheres,
                'area': region_areas,
                'excluded_from_registration': exclusions
            })

            image_stats_table = pandas.concat((image_stats_table, update_df))

    
    image_stats_table.to_csv(output_path)