def make_heatmaps(pth, subdir=False):
    """ 
    makes clearmap style heatmaps 
    NOTE: do not need to do this if you have already succesfully run your images using ClearMap
    """
    #make heatmaps
    vox_params = {"method": "Spherical", "size": (15, 15, 15), "weights": None}
    #if cells detected separateful from clearmap
    if subdir:
        if subdir in os.listdir(pth):
            points = np.load(os.path.join(pth, subdir+"/posttransformed_zyx_voxels.npy"))
            
            #run clearmap style blurring
            vox = voxelize(np.asarray(points), dataSize = (456, 528, 320), **vox_params)
            dst = os.path.join(pth, subdir+"/cells_heatmap.tif")
        else:
            print("no transformed cells")         
    else:
        points = np.load(os.path.join(pth, "clearmap_cluster_output/cells_transformed_to_Atlas.npy"))
        #reorder to ZYX
        points = np.array([[pnt[2], pnt[1], pnt[0]] for pnt in points])
        #run clearmap style blurring
        vox = voxelize(np.asarray(points), dataSize = (456, 528, 320), **vox_params)
        dst = os.path.join(pth, "cells_heatmap.tif")
    tifffile.imsave(dst, vox.astype("float32"))
    
    return dst
def make_heatmaps(pth, subdir):
    """ makes clearmap style heatmaps """

    #make heatmaps
    vox_params = {"method": "Spherical", "size": (15, 15, 15), "weights": None}

    if subdir in os.listdir(pth):
        points = np.load(
            os.path.join(pth, subdir + "/posttransformed_zyx_voxels.npy"))

        #run clearmap style blurring
        vox = voxelize(np.asarray(points),
                       dataSize=(456, 528, 320),
                       **vox_params)
        dst = os.path.join(pth, subdir + "/cells_heatmap.tif")
        tifffile.imsave(dst, vox.astype("int32"))
    else:
        print("no transformed cells")
    return dst
Exemplo n.º 3
0
def output_analysis(
        threshold=(20, 900), row=(3, 3), check_cell_detection=False, **params):
    """Wrapper for analysis:

    Inputs
    -------------------
    Thresholding: the threshold parameter is either intensity or size in voxel, depending on the chosen "row"
    Row:
        row = (0,0) : peak intensity from the raw data
        row = (1,1) : peak intensity from the DoG filtered data
        row = (2,2) : peak intensity from the background subtracted data
        row = (3,3) : voxel size from the watershed

    Check Cell detection: (For the testing phase only, remove when running on the full size dataset)
    """
    dct = pth_update(set_parameters_for_clearmap(**params))

    points, intensities = io.readPoints(
        dct["ImageProcessingParameter"]["sink"])

    #Thresholding: the threshold parameter is either intensity or size in voxel, depending on the chosen "row"
    #row = (0,0) : peak intensity from the raw data
    #row = (1,1) : peak intensity from the DoG filtered data
    #row = (2,2) : peak intensity from the background subtracted data
    #row = (3,3) : voxel size from the watershed
    points, intensities = thresholdPoints(points,
                                          intensities,
                                          threshold=threshold,
                                          row=row)
    #points, intensities = thresholdPoints(points, intensities, threshold = (20, 900), row = (2,2));
    io.writePoints(dct["FilteredCellsFile"], (points, intensities))

    ## Check Cell detection (For the testing phase only, remove when running on the full size dataset)
    #######################
    #    if check_cell_detection:
    #        import ClearMap.Visualization.Plot as plt
    #        pointSource= os.path.join(BaseDirectory, FilteredCellsFile[0]);
    #        data = plt.overlayPoints(cFosFile, pointSource, pointColor = None, **cFosFileRange);
    #        io.writeData(os.path.join(BaseDirectory, "cells_check.tif"), data);

    # Transform point coordinates
    #############################
    points = io.readPoints(
        dct["CorrectionResamplingPointsParameter"]["pointSource"])
    points = resamplePoints(**dct["CorrectionResamplingPointsParameter"])
    points = transformPoints(
        points,
        transformDirectory=dct["CorrectionAlignmentParameter"]
        ["resultDirectory"],
        indices=False,
        resultDirectory=None)
    dct["CorrectionResamplingPointsInverseParameter"]["pointSource"] = points
    points = resamplePointsInverse(
        **dct["CorrectionResamplingPointsInverseParameter"])
    dct["RegistrationResamplingPointParameter"]["pointSource"] = points
    points = resamplePoints(**dct["RegistrationResamplingPointParameter"])
    points = transformPoints(
        points,
        transformDirectory=dct["RegistrationAlignmentParameter"]
        ["resultDirectory"],
        indices=False,
        resultDirectory=None)
    io.writePoints(dct["TransformedCellsFile"], points)

    # Heat map generation
    #####################
    points = io.readPoints(dct["TransformedCellsFile"])
    intensities = io.readPoints(dct["FilteredCellsFile"][1])

    #Without weigths:
    vox = voxelize(points, dct["AtlasFile"], **dct["voxelizeParameter"])
    if not isinstance(vox, str):
        io.writeData(os.path.join(dct["OutputDirectory"], "cells_heatmap.tif"),
                     vox.astype("int32"))

    #With weigths from the intensity file (here raw intensity):
    dct["voxelizeParameter"]["weights"] = intensities[:, 0].astype(float)
    vox = voxelize(points, dct["AtlasFile"], **dct["voxelizeParameter"])
    if not isinstance(vox, str):
        io.writeData(
            os.path.join(dct["OutputDirectory"], "cells_heatmap_weighted.tif"),
            vox.astype("int32"))

    #Table generation:
    ##################
    #With integrated weigths from the intensity file (here raw intensity):
    try:
        ids, counts = countPointsInRegions(points,
                                           labeledImage=dct["AnnotationFile"],
                                           intensities=intensities,
                                           intensityRow=0)
        table = numpy.zeros(ids.shape,
                            dtype=[("id", "int64"), ("counts", "f8"),
                                   ("name", "a256")])
        table["id"] = ids
        table["counts"] = counts
        table["name"] = labelToName(ids)
        io.writeTable(
            os.path.join(dct["OutputDirectory"],
                         "Annotated_counts_intensities.csv"), table)

        #Without weigths (pure cell number):
        ids, counts = countPointsInRegions(points,
                                           labeledImage=dct["AnnotationFile"],
                                           intensities=None)
        table = numpy.zeros(ids.shape,
                            dtype=[("id", "int64"), ("counts", "f8"),
                                   ("name", "a256")])
        table["id"] = ids
        table["counts"] = counts
        table["name"] = labelToName(ids)
        io.writeTable(
            os.path.join(dct["OutputDirectory"], "Annotated_counts.csv"),
            table)
    except:
        print("Table not generated.\n")

    print("Analysis Completed")

    return
def output_analysis_helper(threshold=(20, 900), row=(3, 3), **params):
    '''
    Function to change elastix result directory before running 'step 6' i.e. point transformix to atlas.
    '''
    dct = pth_update(set_parameters_for_clearmap(**params))

    dct['RegistrationAlignmentParameter']["resultDirectory"] = os.path.join(
        params["outputdirectory"],
        'clearmap_cluster_output/elastix_auto_to_sim_atlas')

    points, intensities = io.readPoints(
        dct['ImageProcessingParameter']["sink"])

    #Thresholding: the threshold parameter is either intensity or size in voxel, depending on the chosen "row"
    #row = (0,0) : peak intensity from the raw data
    #row = (1,1) : peak intensity from the DoG filtered data
    #row = (2,2) : peak intensity from the background subtracted data
    #row = (3,3) : voxel size from the watershed
    points, intensities = thresholdPoints(points,
                                          intensities,
                                          threshold=threshold,
                                          row=row)
    #points, intensities = thresholdPoints(points, intensities, threshold = (20, 900), row = (2,2));
    io.writePoints(dct['FilteredCellsFile'], (points, intensities))

    # Transform point coordinates
    #############################
    points = io.readPoints(
        dct['CorrectionResamplingPointsParameter']["pointSource"])
    points = resamplePoints(**dct['CorrectionResamplingPointsParameter'])
    points = transformPoints(
        points,
        transformDirectory=dct['CorrectionAlignmentParameter']
        ["resultDirectory"],
        indices=False,
        resultDirectory=None)
    dct['CorrectionResamplingPointsInverseParameter']["pointSource"] = points
    points = resamplePointsInverse(
        **dct['CorrectionResamplingPointsInverseParameter'])
    dct['RegistrationResamplingPointParameter']["pointSource"] = points
    points = resamplePoints(**dct['RegistrationResamplingPointParameter'])
    points = transformPoints(
        points,
        transformDirectory=dct['RegistrationAlignmentParameter']
        ["resultDirectory"],
        indices=False,
        resultDirectory=None)
    io.writePoints(dct['TransformedCellsFile'], points)

    # Heat map generation
    #####################
    points = io.readPoints(dct['TransformedCellsFile'])
    intensities = io.readPoints(dct['FilteredCellsFile'][1])

    #Without weigths:
    vox = voxelize(points, dct['AtlasFile'], **dct['voxelizeParameter'])
    if not isinstance(vox, basestring):
        io.writeData(os.path.join(dct['OutputDirectory'], 'cells_heatmap.tif'),
                     vox.astype('int32'))

    #With weigths from the intensity file (here raw intensity):
    dct['voxelizeParameter']["weights"] = intensities[:, 0].astype(float)
    vox = voxelize(points, dct['AtlasFile'], **dct['voxelizeParameter'])
    if not isinstance(vox, basestring):
        io.writeData(
            os.path.join(dct['OutputDirectory'], 'cells_heatmap_weighted.tif'),
            vox.astype('int32'))

    #Table generation:
    ##################
    #With integrated weigths from the intensity file (here raw intensity):
    ids, counts = countPointsInRegions(points,
                                       labeledImage=dct['AnnotationFile'],
                                       intensities=intensities,
                                       intensityRow=0)
    table = np.zeros(ids.shape,
                     dtype=[('id', 'int64'), ('counts', 'f8'),
                            ('name', 'a256')])
    table["id"] = ids
    table["counts"] = counts
    table["name"] = labelToName(ids)
    io.writeTable(
        os.path.join(dct['OutputDirectory'],
                     'Annotated_counts_intensities.csv'), table)

    #Without weigths (pure cell number):
    ids, counts = countPointsInRegions(points,
                                       labeledImage=dct['AnnotationFile'],
                                       intensities=None)
    table = np.zeros(ids.shape,
                     dtype=[('id', 'int64'), ('counts', 'f8'),
                            ('name', 'a256')])
    table["id"] = ids
    table["counts"] = counts
    table["name"] = labelToName(ids)
    io.writeTable(os.path.join(dct['OutputDirectory'], 'Annotated_counts.csv'),
                  table)

    print('Analysis Completed')

    return