Ejemplo n.º 1
0
                                labeledImage=annoImg_fn,
                                level=None,
                                collapse=None)

    #defField = deformationField(sink = [], transformParameterFile = transformParameterFN, transformDirectory = None, resultDirectory = transformResultDir)
    #defDistance = deformationDistance(defField, sink = None, scale = None)
    #print 'Mean Deformation distance= %d' %defDistance.mean()

    ids, counts = countPointsInRegions(points,
                                       labeledImage=annoImg_fn,
                                       intensities=None,
                                       collapse=None)
    #Table generation
    table = numpy.zeros(ids.shape,
                        dtype=[('id', 'int64'), ('counts', 'f8'),
                               ('name', 'a256')])
    table['id'] = ids
    table['counts'] = counts
    table['name'] = labelToName(ids)
    io.writeTable(tableFN, table)

    beforeAlign = plt.fredOverlayPoints(auto_R_fn,
                                        pointsRe,
                                        pointColor=[200, 0, 0])
    io.writeData(os.path.join(resultDir, 'BeforeAlign.tif'), beforeAlign)

    afterAlign = plt.fredOverlayPoints(refImg_fn,
                                       points,
                                       pointColor=[200, 0, 0])
    io.writeData(os.path.join(resultDir, 'AfterAlign.tif'), afterAlign)
Ejemplo n.º 2
0
table = numpy.zeros(ids0.shape, dtype = dtypes)
table["id"] = ids0;
table["structureOrder"] = labelToStructureOrder(ids0);
table["mean1"] = pc1i0.mean(axis = 1)/1000000;
table["std1"] = pc1i0.std(axis = 1)/1000000;
table["mean2"] = pc2i0.mean(axis = 1)/1000000;
table["std2"] = pc2i0.std(axis = 1)/1000000;
table["pvalue"] = pvalsi0;
table["qvalue"] = qvalsi0;

table["psign"] = psigni0;
for i in range(len(group1_roi)):
    table["count1_%d" % i] = pc10[:,i];
for i in range(len(group2_roi)):
    table["count2_%d" % i] = pc20[:,i];
table["name"] = labelToName(ids0);


#sort by qvalue
ii = numpy.argsort(pvalsi0);
tableSorted = table.copy();
tableSorted = tableSorted[ii];

with open(os.path.join(baseDirectory, 'counts-intensity_table.csv'),'w') as f:
    f.write(', '.join([str(item) for item in table.dtype.names]));
    f.write('\n');
    for sublist in tableSorted:
        f.write(', '.join([str(item) for item in sublist]));
        f.write('\n');
    f.close();
Ejemplo 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