diff --git a/.gitattributes b/.gitattributes index 1ef325f1b111266a6b26e0196871bd78baa8c2f3..de6409ef47cab5ef4475c169534c5d58f28afc9a 100644 --- a/.gitattributes +++ b/.gitattributes @@ -57,3 +57,29 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text # Video files - compressed *.mp4 filter=lfs diff=lfs merge=lfs -text *.webm filter=lfs diff=lfs merge=lfs -text +data/imagej_macro/ImageJ_plugins/3D_suite/imageware.jar filter=lfs diff=lfs merge=lfs -text +data/imagej_macro/ImageJ_plugins/3D_suite/mcib3d-core3.93.jar filter=lfs diff=lfs merge=lfs -text +data/imagej_macro/ImageJ_plugins/3D_suite/mcib3d_plugins3.93.jar filter=lfs diff=lfs merge=lfs -text +data/imagej_macro/ImageJ_plugins/3D_viewer/3D_Viewer-4.0.1.jar filter=lfs diff=lfs merge=lfs -text +data/imagej_macro/ImageJ_plugins/3D_viewer/VIB-lib-2.1.1.jar filter=lfs diff=lfs merge=lfs -text +data/imagej_macro/ImageJ_plugins/3D_viewer/gluegen-rt-2.3.2.jar filter=lfs diff=lfs merge=lfs -text +data/imagej_macro/ImageJ_plugins/3D_viewer/j3dcore-1.6.0-scijava-2.jar filter=lfs diff=lfs merge=lfs -text +data/imagej_macro/ImageJ_plugins/3D_viewer/j3dutils-1.6.0-scijava-2.jar filter=lfs diff=lfs merge=lfs -text +data/imagej_macro/ImageJ_plugins/3D_viewer/jogl-all-2.3.2-natives-linux-amd64.jar filter=lfs diff=lfs merge=lfs -text +data/imagej_macro/ImageJ_plugins/3D_viewer/jogl-all-2.3.2-natives-macosx-universal.jar filter=lfs diff=lfs merge=lfs -text +data/imagej_macro/ImageJ_plugins/3D_viewer/jogl-all-2.3.2-natives-windows-amd64.jar filter=lfs diff=lfs merge=lfs -text +data/imagej_macro/ImageJ_plugins/3D_viewer/jogl-all-2.3.2.jar filter=lfs diff=lfs merge=lfs -text +data/imagej_macro/ImageJ_plugins/3D_viewer/vecmath-1.6.0-scijava-2.jar filter=lfs diff=lfs merge=lfs -text +data/imagej_macro/ImageJ_plugins/spatial3dtissuej_plugin/TissueJ4Merfish_v14.jar filter=lfs diff=lfs merge=lfs -text +data/imagej_macro/ImageJ_plugins/utils/3D_Convex_Hull.jar filter=lfs diff=lfs merge=lfs -text +data/imagej_macro/ImageJ_plugins/utils/imagescience.jar filter=lfs diff=lfs merge=lfs -text +data/imagej_macro/ImageJ_plugins/utils/mpicbg_-1.4.1.jar filter=lfs diff=lfs merge=lfs -text +data/imagej_macro/cell_zone_detection/TissueJ4Merfish_v14.jar filter=lfs diff=lfs merge=lfs -text +data/imagej_macro/cell_zone_detection/merFISH_01_025_08-SEG.tif filter=lfs diff=lfs merge=lfs -text +data/imagej_macro/cell_zone_detection/merFISH_01_025_08-mask.tif filter=lfs diff=lfs merge=lfs -text +data/imagej_macro/nuclei_segmentation/cell_zone_results/aligned_images_fov0_z18_01_cell_zone_rad_5.0.tif filter=lfs diff=lfs merge=lfs -text +data/imagej_macro/nuclei_segmentation/demo_results/aligned_images_fov0_z18_01_SEG_demo_only.tif filter=lfs diff=lfs merge=lfs -text +data/imagej_macro/nuclei_segmentation/seg_results/aligned_images_fov0_z18_01_SEG.tif filter=lfs diff=lfs merge=lfs -text +data/imagej_macro/nuclei_segmentation/seg_results/aligned_images_fov0_z18_02_SEG.tif filter=lfs diff=lfs merge=lfs -text +data/imagej_macro/nuclei_segmentation/testing_images/aligned_images_fov0_z18_01.tif filter=lfs diff=lfs merge=lfs -text +data/imagej_macro/nuclei_segmentation/testing_images/aligned_images_fov0_z18_02.tif filter=lfs diff=lfs merge=lfs -text diff --git a/data/Correlation/correlation.py b/data/Correlation/correlation.py new file mode 100644 index 0000000000000000000000000000000000000000..afdb1c3ff10a331dcd232b192f6b1c8798610578 --- /dev/null +++ b/data/Correlation/correlation.py @@ -0,0 +1,204 @@ + + + + +# Import +import cProfile +from distutils import core +from pathlib import Path +import numpy as np +import scipy as sp +import pandas as pd +import matplotlib.pyplot as plt +from matplotlib.backends.backend_pdf import PdfPages +import seaborn as sns +import os +import pickle +import scipy.stats as stats +import argparse +from adjustText import adjust_text +import matplotlib.backends.backend_pdf + + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('-b', type = str, help = 'Path to barcodes') + parser.add_argument('-xp', type = str, help = 'Experiment ID') + parser.add_argument('-c', type = str, default = "D:\BCCAncer\FILES\codebook_0_C1E1_van.csv", help = 'Path to codebook') + parser.add_argument('-a', type = str, default = "D:\BCCAncer\FILES\XP2474_4T1_C1E1_new_bulk.csv", help = 'Path to bulk file (abundance file)') + parser.add_argument('-o', type = str, default = "D:\BCCAncer\EXP\XP7174\Correlations\BulkCorr", help = 'Path to save processed files') + parser.add_argument('-is_cambridge', type = bool, default = False, help = 'Are the results for Cambridge datasets?') + parser.add_argument('-drop_blanks', type = bool, default = False, help = 'Remove blanks before correlation') + parser.add_argument('-log', type =bool, default = True, help = 'Do we want to take log while correlation of bulk?') + parser.add_argument("-d", nargs="+", type = float, default=0.65, help = 'Max mean distance threshold for an area of detected barcode') + parser.add_argument("-removeZ", nargs="+", type=int, default=None, help="Z slices to remove from evaluation") + #parser.add_argument('-gene_list', type = str, action='append', required=True, help = 'List of genes which we want to exclude from analysis') + + + args = parser.parse_args() + + if not os.path.exists(args.o): + os.makedirs(args.o) + + info_np = np.zeros(shape = (len(args.d), 7)) + + # read sheet and remove undesired z slices + df = read_sheet(args.b) + if args.removeZ is not None: + removeZ_set = set(args.removeZ) + df = df[~df['z'].isin(removeZ_set)] + + + + pdf = matplotlib.backends.backend_pdf.PdfPages(f'{args.o}/{args.xp}_correlation.pdf') + correlation = Correlation(args.c, df, args.a, args.o, args.xp, args.is_cambridge, pdf) + args.d.sort(reverse = True) + + + for idx, dist_threshold in enumerate(args.d): + filter_df = correlation.filter_distance(dist_threshold) + gp_df = correlation.groupby(filter_df) + gp_df = correlation.merge_df_cb(gp_df) + + tot_counts = gp_df.counts.sum() + blank_counts = gp_df.loc[gp_df['gene_symbol'].isin(['Blank_01', 'Blank_02', 'Blank_03', 'Blank_04', 'Blank_05', 'Blank_06'])].counts.sum() + + info_np[idx][0] = dist_threshold + info_np[idx][3] = int(tot_counts) + info_np[idx][4] = int(blank_counts) + info_np[idx][5] = int(len(gp_df)) + + gp_df = correlation.df_bulk(gp_df) + + if args.drop_blanks: + gp_df = correlation.remove_blanks(gp_df) + + """ + if args.gene_list: + print('removing') + gp_df = correlation.remove_specific_genes(gp_df) + """ + + info_np[idx][-1] = len(gp_df) + + gp_df['log_counts'] = np.log2(gp_df['counts']+1) + gp_df['log_tpm'] = np.log2(gp_df['bulk_exp']+0.0001) + + gp_df.to_csv(f'{args.o}/{args.xp}_{dist_threshold}.csv') + + + info_np[idx][1], info_np[idx][2] = correlation.log_correlation(gp_df, dist_threshold) + + pdf.close() + + info_df = pd.DataFrame(info_np, columns = ['Distance Threshold',\ + 'Pearson correlation',\ + 'Spearman correlation',\ + '# detected barcodes (including control barcodes)',\ + '# detected control (blanks) barcodes',\ + '# genes at dist threshold in correlation',\ + '# barcodes counted towards correlaton estimation']) + info_df.to_csv(f'{args.o}/info_{args.xp}.csv') + +def read_sheet(file): + + ext = file.split(".")[-1] + if ext == "csv": + df = pd.read_csv(file) + elif ext == "tsv": + df = pd.read_csv(file, '\t') + elif ext in {"xls", "xlsx", "xlsm", "xlsb"}: + df = pd.read_excel(file) + else: + raise ValueError("Unexpected file extension") + return df + +class Correlation: + def __init__(self, codebook, barcodes, bulk, output_dir, name, is_cambridge, pdf_object): + self.codebook = read_sheet(codebook) + self.barcodes = barcodes + self.bulk = read_sheet(bulk) + self.output_dir = output_dir + self.name = name + self.is_cambridge = is_cambridge + self.pdf_object = pdf_object + #self.remove_genes_list = remove_genes_list + + def filter_distance(self, distance_threshold): + return self.barcodes.loc[self.barcodes['mean_distance']0: + full_raw_path = results[0].group(1) + else: + full_raw_path='' + + + return sorted(list(set(zs)),key=int),sorted(list(set(fovs)),key=int),sorted(list(set(irs)),key=int),sorted(list(set(wvs)),key=int),full_raw_path + + +download_azure() +zs,fovs,irs,wvs,full_raw_path = check_params() + + +default_message= "rule {rule}, {wildcards}, threads: {threads}" + +rule all_done: + input: + os.path.join(config['results_path'],'brightness_report.t'), + os.path.join(config['results_path'],'focus_report.t'), + os.path.join(config['results_path'],'deconvolved_brightness_report.t'), + os.path.join(config['results_path'],'masked_brightness_report.t'), + os.path.join(config['results_path'],'decodability_report.t') + output: + os.path.join(config['results_path'],'all_done.t') + run: + if config["isRemote"]=="Y": + shell("rm -rf \"{}\"".format(os.path.join(config['results_path'],'data'))) + if config["delete_stack"]=="Y": + shell("rm -f \"{}\"".format(os.path.join(config['results_path'],'img*'))) + shell("touch \"{output[0]}\"") + +rule all: + threads:1 + input: + os.path.join(config['results_path'],'all_done.t') + + +def isRemote(wildcards): + + if config["isRemote"]=="N": + return config["raw_data_path"] + else: + return directory(os.path.join(config['results_path'],'data')) + +rule create_image_stack: + threads:1 + message: default_message + input: + isRemote + output: + out_file = os.path.join(config['results_path'],'imgstack_{fov}_{z}.npy'), + coord_file = os.path.join(config['results_path'],'coord_{fov}_{z}.json') + run: + fileIO.create_image_stack(os.path.join(full_raw_path,config['raw_image_format']), + wildcards.fov,wildcards.z,irs,wvs,output.out_file,output.coord_file) + + +rule deconvolve_images: + threads:1 + message: default_message + input: + in_file = os.path.join(config['results_path'],'imgstack_{fov}_{z}.npy'), + output: + out_file = os.path.join(config['results_path'],'deconvolved','deconvolved_{fov}_{z}.npy') + run: + imgproc._deconvolute(input.in_file,output.out_file) + + + + +rule deconvolved_brightness_report: + threads:1 + message: default_message + input: + img_stack = os.path.join(config['results_path'],'deconvolved','deconvolved_{fov}_{z}.npy'), + coord_file = os.path.join(config['results_path'],'coord_{fov}_{z}.json') + output: + out=os.path.join(config['results_path'],'deconvolved_brightness_report_{fov}_{z}.pdf') + run: + reports.generate_brightness_reports(input.img_stack,input.coord_file,output.out,wildcards.fov,wildcards.z) + + +rule compile_deconvolved_brightness_report: + threads:1 + message: default_message + input: + expand(os.path.join(config['results_path'],'deconvolved_brightness_report_{fov}_{z}.pdf'),fov=fovs,z=zs) + output: + os.path.join(config['results_path'],'deconvolved_brightness_report.t') + shell: + "touch \"{output}\"" + + +rule create_mask_images: + threads:1 + message: default_message + input: + img_stack = os.path.join(config['results_path'],'deconvolved','deconvolved_{fov}_{z}.npy'), + output: + out_mask=os.path.join(config['results_path'],'masked','mask_{fov}_{z}.npy') + run: + imgproc.maskImages(input.img_stack,output.out_mask) + + +rule masked_brightness_report: + threads:1 + message: default_message + input: + img_stack = os.path.join(config['results_path'],'imgstack_{fov}_{z}.npy'), + masks = os.path.join(config['results_path'],'masked','mask_{fov}_{z}.npy'), + coord_file = os.path.join(config['results_path'],'coord_{fov}_{z}.json') + output: + out=os.path.join(config['results_path'],'masked_brightness_report_{fov}_{z}.pdf') + run: + reports.generate_masked_brightness_reports(input.img_stack,input.coord_file,output.out,wildcards.fov,wildcards.z,input.masks) + +rule compile_masked_brightness_report: + threads:1 + message: default_message + input: + expand(os.path.join(config['results_path'],'masked_brightness_report_{fov}_{z}.pdf'),fov=fovs,z=zs) + output: + os.path.join(config['results_path'],'masked_brightness_report.t') + shell: + "touch \"{output}\"" + +rule brightness_report: + threads:1 + message: default_message + input: + img_stack = os.path.join(config['results_path'],'imgstack_{fov}_{z}.npy'), + coord_file = os.path.join(config['results_path'],'coord_{fov}_{z}.json') + output: + out=os.path.join(config['results_path'],'brightness_report_{fov}_{z}.pdf') + run: + reports.generate_brightness_reports(input.img_stack,input.coord_file,output.out,wildcards.fov,wildcards.z) + +rule compile_brightness_report: + threads:1 + message: default_message + input: + expand(os.path.join(config['results_path'],'brightness_report_{fov}_{z}.pdf'),fov=fovs,z=zs) + output: + os.path.join(config['results_path'],'brightness_report.t') + shell: + "touch \"{output}\"" + + + + +rule focus_report: + threads:1 + message: default_message + input: + img_stack = expand(os.path.join(config['results_path'],'imgstack_{{fov}}_{z}.npy'),z=zs), + coord_file = expand(os.path.join(config['results_path'],'coord_{{fov}}_{z}.json'),z=zs) + output: + out=os.path.join(config['results_path'],'focus_report_{fov}.pdf'), + out_csvs = os.path.join(config['results_path'],'focus_report_{fov}.csv') + run: + reports.generate_focus_reports(input.img_stack,input.coord_file,output.out,output.out_csvs,wildcards.fov) + +rule compile_focus_report: + threads:1 + message: default_message + input: + files = expand(os.path.join(config['results_path'],'focus_report_{fov}.pdf'),fov=fovs), + csvs = expand(os.path.join(config['results_path'],'focus_report_{fov}.csv'),fov=fovs) + output: + combined = os.path.join(config['results_path'],'focus_report_all_fov.pdf'), + out = os.path.join(config['results_path'],'focus_report.t') + run: + reports.compile_focus_report(input.csvs,output.combined,irs,wvs) + shell("touch \"{output.out}\"") + + +rule decodability_report: + threads:1 + message: default_message + input: + img_stack = os.path.join(config['results_path'],'deconvolved','deconvolved_{fov}_{z}.npy'), + coord_file = os.path.join(config['results_path'],'coord_{fov}_{z}.json'), + codebook_file = config["codebook_file"], + data_organization_file = config["data_org_file"] + output: + out=os.path.join(config['results_path'],'decodability_report_{fov}_{z}.pdf'), + out_stats = os.path.join(config['results_path'],'decodability_stats_{fov}_{z}.txt') + run: + reports.generate_decodability_reports(input.img_stack,input.coord_file,output.out,input.codebook_file,input.data_organization_file,wildcards.fov,wildcards.z,output.out_stats) + + +rule compile_decodability_report: + threads:1 + message: default_message + input: + expand(os.path.join(config['results_path'],'decodability_report_{fov}_{z}.pdf'),fov=fovs,z=zs) + output: + os.path.join(config['results_path'],'decodability_report.t') + shell: + "touch \"{output}\"" \ No newline at end of file diff --git a/data/config.json b/data/config.json new file mode 100644 index 0000000000000000000000000000000000000000..25605241ae1364830f7f5728b36344e549160546 --- /dev/null +++ b/data/config.json @@ -0,0 +1,14 @@ +{ + "raw_data_path":"/Volumes/MERFISH_COLD/XP2059", + "results_path":"/Volumes/MERFISH_COLD/XP2059/1/1/2059_merFISH_report_results", + "raw_image_format": "{wv}nm, Raw/merFISH_{ir}_{fov}_{z}.TIFF", + "channel": [], + "fov": ["001"], + "ir": [], + "z": ["01","02","03"], + "isRemote":"N", + "azure_command":"azcopy cp \"{}\" \"{}\" --recursive", + "delete_stack":"N", + "codebook_file": "/Volumes/MERFISH_COLD/Codebooks/C1E1_codebook_shahid.csv", + "data_org_file":"/Volumes/MERFISH_COLD/data_organization/data_organization.csv" +} diff --git a/data/debug_reports.py b/data/debug_reports.py new file mode 100644 index 0000000000000000000000000000000000000000..ffcaa731b6d3c566e1a85c0d4bc8fc7eb9fbb696 --- /dev/null +++ b/data/debug_reports.py @@ -0,0 +1,176 @@ +import json +import os +import numpy as np +from utils import fileIO,imgproc +import reports +import makereports +from pathlib import Path +import time +import re + +coord_file = "config.json" +a_file = open(coord_file, "r") +config = json.load(a_file) + + +fov = '001' +z='02' + +def download_azure(): + + if config["isRemote"]=="N" or os.path.exists(os.path.join(config['results_path'],'data')): + return None + + os.system(config["azure_command"].format(config["raw_data_path"],os.path.join(config['results_path'],'data'))) + + return None + +def check_params(): + + # Check to see if there are any params that need to be found + b_findz = len(config['z'])==0 + b_findfov = len(config['fov'])==0 + b_findir = len(config['ir'])==0 + b_findwv = len(config['channel'])==0 + + + # get all the images + if config["isRemote"] == "Y": + files = Path(os.path.join(config['results_path'],'data')).rglob('*.TIFF') + else: + files = Path(config['raw_data_path']).rglob('*.TIFF') + files = list(map(str,files)) + # Find all channel, ir, fov, and z from the file names + re_filter = r"(.*)(\d{3})(?=nm).*(\B\d{2})\D(\B\d{3})\D(\B\d{2}\b)" + param_filter = re.compile(re_filter) + results = list(map(param_filter.search,files)) + + results =list(filter(lambda x: isinstance(x,re.Match), results)) + # Get the list of parameters if they are needed + # Group 0 is the full match, so each capture group is 1 indexed + if b_findz: + zs = list(map(lambda x: x.group(5),results)) + else: + zs = config['z'] + + if b_findir: + irs = list(map(lambda x: x.group(3),results)) + else: + irs = config['ir'] + + if b_findfov: + fovs = list(map(lambda x: x.group(4),results)) + else: + fovs = config['fov'] + + if b_findwv: + wvs = list(map(lambda x: x.group(2),results)) + else: + wvs = config['channel'] + + if isinstance(results,list) and len(results)>0: + full_raw_path = results[0].group(1) + else: + full_raw_path='' + + + return sorted(list(set(zs)),key=int),sorted(list(set(fovs)),key=int),sorted(list(set(irs)),key=int),sorted(list(set(wvs)),key=int),full_raw_path + + +def check_dirs(files): + """Checks to see if the directories for the files in the list exist. If they dont, then make those directories + + Args: + files (list[str]): the list of files whose directory paths to create. Needs to be the full, not relative paths + + """ + if not type(files) == list: + d = os.path.dirname(files) + if not os.path.isdir(d): + # print(files+'files' + d +'Does not exist') + os.makedirs(d) + else: + for f in files: + + d = os.path.dirname(f) + if d != "" and not os.path.isdir(d): + # print(f+'files' + d +'Does not exist') + os.makedirs(d) + +download_azure() +zs,fovs,irs,wvs,full_raw_path = check_params() + +def create_image_stack(): + + out_file = os.path.join(config['results_path'],f'imgstack_{fov}_{z}.npy') + coord_file = os.path.join(config['results_path'],f'coord_{fov}_{z}.json') + check_dirs(out_file) + + fileIO.create_image_stack(os.path.join(full_raw_path,config['raw_image_format']),fov,z,irs,wvs,out_file,coord_file) + +def create_deconvolved_images(): + in_file = os.path.join(config['results_path'],f'imgstack_{fov}_{z}.npy') + + out_file = os.path.join(config['results_path'],'deconvolved',f'deconvolved_{fov}_{z}.npy') + check_dirs(out_file) + imgproc._deconvolute(in_file,out_file) + +def create_brightness_report(): + + img_stack = os.path.join(config['results_path'],f'imgstack_{fov}_{z}.npy') + coord_file = os.path.join(config['results_path'],f'coord_{fov}_{z}.json') + + out=os.path.join(config['results_path'],f'brightness_report_{fov}_{z}.pdf') + check_dirs(out) + + makereports.brightness_worker(img_stack,coord_file,out,fov,z) + +def create_focus_report(): + + img_stack = [os.path.join(config['results_path'],f'imgstack_{fov}_{z}.npy')] + coord_file = [os.path.join(config['results_path'],f'coord_{fov}_{z}.json')] + + out=os.path.join(config['results_path'],f'focus_report_{fov}.pdf') + out_csv = os.path.join(config['results_path'],f'focus_report_{fov}.csv') + check_dirs(out) + makereports.focus_worker(img_stack,coord_file,out,out_csv,fov) + + +def compile_focus_reports(): + + in_files = [os.path.join(config['results_path'],f'focus_report_{fov}.csv')] + output = 'full_report_debug.csv' + + makereports.compile_focus_report(in_files,output=output,irs=irs,wvs=wvs) + + +if __name__=='__main__': + start_time = time.time() + + sub_start_time = time.time() + create_image_stack() + sub_end_time = time.time() + print(f'Image Stack: {sub_end_time-sub_start_time}') + + sub_start_time = time.time() + create_deconvolved_images() + sub_end_time = time.time() + print(f'Deconvolved Stack: {sub_end_time-sub_start_time}') + + sub_start_time = time.time() + create_brightness_report() + sub_end_time = time.time() + print(f'Brightness Report: {sub_end_time-sub_start_time}') + + sub_start_time = time.time() + create_focus_report() + sub_end_time = time.time() + print(f'Focus Report: {sub_end_time-sub_start_time}') + + sub_start_time = time.time() + compile_focus_reports() + sub_end_time = time.time() + print(f'Compiled Focus Report: {sub_end_time-sub_start_time}') + + end_time = time.time() + print(f'Total Time: {end_time-start_time}') \ No newline at end of file diff --git a/data/environment.yml b/data/environment.yml new file mode 100644 index 0000000000000000000000000000000000000000..34464c21f1a70d1efe631081e09094bbc9d76d69 --- /dev/null +++ b/data/environment.yml @@ -0,0 +1,11 @@ +name: experiment_report +channels: + - conda-forge + - bioconda +dependencies: + - python=3.7 + - snakemake + - matplotlib + - scikit-image + - numpy + - scikit-learn diff --git a/data/imagej_macro/ImageJ_plugins/3D_suite/combinatoricslib-2.0.jar b/data/imagej_macro/ImageJ_plugins/3D_suite/combinatoricslib-2.0.jar new file mode 100644 index 0000000000000000000000000000000000000000..71650efa93fbef1c767071b464e529d0ec3942df Binary files /dev/null and b/data/imagej_macro/ImageJ_plugins/3D_suite/combinatoricslib-2.0.jar differ diff --git a/data/imagej_macro/ImageJ_plugins/3D_suite/droplet_finder.jar b/data/imagej_macro/ImageJ_plugins/3D_suite/droplet_finder.jar new file mode 100644 index 0000000000000000000000000000000000000000..b9ed09224d69226162f708853c2e44909d527e57 Binary files /dev/null and b/data/imagej_macro/ImageJ_plugins/3D_suite/droplet_finder.jar differ diff --git a/data/imagej_macro/ImageJ_plugins/3D_suite/imageware.jar b/data/imagej_macro/ImageJ_plugins/3D_suite/imageware.jar new file mode 100644 index 0000000000000000000000000000000000000000..6c51d38d72293e5589f8612a409dd313c845ca2b --- /dev/null +++ b/data/imagej_macro/ImageJ_plugins/3D_suite/imageware.jar @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d0f521c689ff44fbbea7f87b8125c9f86e12923388a88892ae6120c4062b511d +size 103743 diff --git a/data/imagej_macro/ImageJ_plugins/3D_suite/mcib3d-core3.93.jar b/data/imagej_macro/ImageJ_plugins/3D_suite/mcib3d-core3.93.jar new file mode 100644 index 0000000000000000000000000000000000000000..97fad55214475caf6941667f31f3e8b13c796dad --- /dev/null +++ b/data/imagej_macro/ImageJ_plugins/3D_suite/mcib3d-core3.93.jar @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1d3b90de88264aa7c1969ccb4fd8c2c74768f5f8b437c55e4257dda154bc97e0 +size 814496 diff --git a/data/imagej_macro/ImageJ_plugins/3D_suite/mcib3d_plugins3.93.jar b/data/imagej_macro/ImageJ_plugins/3D_suite/mcib3d_plugins3.93.jar new file mode 100644 index 0000000000000000000000000000000000000000..a48640a24fd6579914d56a4d4c185e6800c1f0ee --- /dev/null +++ b/data/imagej_macro/ImageJ_plugins/3D_suite/mcib3d_plugins3.93.jar @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e265339b392cdfe621265430f7fb850a1bba60686ecdbb22d3b3be19e810a716 +size 252590 diff --git a/data/imagej_macro/ImageJ_plugins/3D_viewer/.directory b/data/imagej_macro/ImageJ_plugins/3D_viewer/.directory new file mode 100644 index 0000000000000000000000000000000000000000..0012716db12436039259fb6266c6cc025e4e5fa0 --- /dev/null +++ b/data/imagej_macro/ImageJ_plugins/3D_viewer/.directory @@ -0,0 +1,4 @@ +[Dolphin] +PreviewsShown=true +Timestamp=2016,7,1,12,4,53 +Version=3 diff --git a/data/imagej_macro/ImageJ_plugins/3D_viewer/3D_Viewer-4.0.1.jar b/data/imagej_macro/ImageJ_plugins/3D_viewer/3D_Viewer-4.0.1.jar new file mode 100644 index 0000000000000000000000000000000000000000..5805ddc85020e79592a8b914c50936a232967837 --- /dev/null +++ b/data/imagej_macro/ImageJ_plugins/3D_viewer/3D_Viewer-4.0.1.jar @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:47af1d1a50ebeed443523822f7622c5fc787273ae9dafd08ead2c760389d6862 +size 548054 diff --git a/data/imagej_macro/ImageJ_plugins/3D_viewer/VIB-lib-2.1.1.jar b/data/imagej_macro/ImageJ_plugins/3D_viewer/VIB-lib-2.1.1.jar new file mode 100644 index 0000000000000000000000000000000000000000..4248e41ad29a2d793c1855823dbeb382a5820953 --- /dev/null +++ b/data/imagej_macro/ImageJ_plugins/3D_viewer/VIB-lib-2.1.1.jar @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c6ea31c1dfb7cd988534928269918dd744826e4904c3e7e913b5fba7cbaee582 +size 635940 diff --git a/data/imagej_macro/ImageJ_plugins/3D_viewer/gluegen-rt-2.3.2-natives-linux-amd64.jar b/data/imagej_macro/ImageJ_plugins/3D_viewer/gluegen-rt-2.3.2-natives-linux-amd64.jar new file mode 100644 index 0000000000000000000000000000000000000000..a2466f418a12a7f57b52b0a7dc8e5bd2304ec33d Binary files /dev/null and b/data/imagej_macro/ImageJ_plugins/3D_viewer/gluegen-rt-2.3.2-natives-linux-amd64.jar differ diff --git a/data/imagej_macro/ImageJ_plugins/3D_viewer/gluegen-rt-2.3.2-natives-macosx-universal.jar b/data/imagej_macro/ImageJ_plugins/3D_viewer/gluegen-rt-2.3.2-natives-macosx-universal.jar new file mode 100644 index 0000000000000000000000000000000000000000..15df5e8200e9eaa9e48217f0131ce31e85dad4c4 Binary files /dev/null and b/data/imagej_macro/ImageJ_plugins/3D_viewer/gluegen-rt-2.3.2-natives-macosx-universal.jar differ diff --git a/data/imagej_macro/ImageJ_plugins/3D_viewer/gluegen-rt-2.3.2-natives-windows-amd64.jar b/data/imagej_macro/ImageJ_plugins/3D_viewer/gluegen-rt-2.3.2-natives-windows-amd64.jar new file mode 100644 index 0000000000000000000000000000000000000000..517fb84c747408545f3c34ee7d93657f0351d58d Binary files /dev/null and b/data/imagej_macro/ImageJ_plugins/3D_viewer/gluegen-rt-2.3.2-natives-windows-amd64.jar differ diff --git a/data/imagej_macro/ImageJ_plugins/3D_viewer/gluegen-rt-2.3.2.jar b/data/imagej_macro/ImageJ_plugins/3D_viewer/gluegen-rt-2.3.2.jar new file mode 100644 index 0000000000000000000000000000000000000000..588871c2ef05c14630ce235449824e2f3aee9740 --- /dev/null +++ b/data/imagej_macro/ImageJ_plugins/3D_viewer/gluegen-rt-2.3.2.jar @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:084844543b18f7ff71b4c0437852bd22f0cb68d7e44c2c611c1bbea76f8c6fdf +size 345605 diff --git a/data/imagej_macro/ImageJ_plugins/3D_viewer/gluegen-rt-main-2.3.2.jar b/data/imagej_macro/ImageJ_plugins/3D_viewer/gluegen-rt-main-2.3.2.jar new file mode 100644 index 0000000000000000000000000000000000000000..5eed15883f1bdc88f602bfd0ff94e6a9a2b878d0 Binary files /dev/null and b/data/imagej_macro/ImageJ_plugins/3D_viewer/gluegen-rt-main-2.3.2.jar differ diff --git a/data/imagej_macro/ImageJ_plugins/3D_viewer/j3dcore-1.6.0-scijava-2.jar b/data/imagej_macro/ImageJ_plugins/3D_viewer/j3dcore-1.6.0-scijava-2.jar new file mode 100644 index 0000000000000000000000000000000000000000..24ab8530a4485dd99412aeaaf2f303a6c1597315 --- /dev/null +++ b/data/imagej_macro/ImageJ_plugins/3D_viewer/j3dcore-1.6.0-scijava-2.jar @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:53055934810716391f87fe5c0c9c73b9d5633baf3304a44a138d449a58908262 +size 1944932 diff --git a/data/imagej_macro/ImageJ_plugins/3D_viewer/j3dutils-1.6.0-scijava-2.jar b/data/imagej_macro/ImageJ_plugins/3D_viewer/j3dutils-1.6.0-scijava-2.jar new file mode 100644 index 0000000000000000000000000000000000000000..8831dc6e078a11bc78e15bfa32c3d47cbbaf5c2b --- /dev/null +++ b/data/imagej_macro/ImageJ_plugins/3D_viewer/j3dutils-1.6.0-scijava-2.jar @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:95ccfcea340debcbd0e519dd65d556e36aba2e97cf8474c83fd2b1d03324a8f1 +size 1047514 diff --git a/data/imagej_macro/ImageJ_plugins/3D_viewer/jogl-all-2.3.2-natives-linux-amd64.jar b/data/imagej_macro/ImageJ_plugins/3D_viewer/jogl-all-2.3.2-natives-linux-amd64.jar new file mode 100644 index 0000000000000000000000000000000000000000..a474b159eee446632176813337c2c2e147e6f977 --- /dev/null +++ b/data/imagej_macro/ImageJ_plugins/3D_viewer/jogl-all-2.3.2-natives-linux-amd64.jar @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:82637302ae9effdf7d6f302e1050ad6aee3b13019914ddda5b502b9faa980216 +size 224010 diff --git a/data/imagej_macro/ImageJ_plugins/3D_viewer/jogl-all-2.3.2-natives-macosx-universal.jar b/data/imagej_macro/ImageJ_plugins/3D_viewer/jogl-all-2.3.2-natives-macosx-universal.jar new file mode 100644 index 0000000000000000000000000000000000000000..0cd9110f6785466572c47cf31c2d6bac60908008 --- /dev/null +++ b/data/imagej_macro/ImageJ_plugins/3D_viewer/jogl-all-2.3.2-natives-macosx-universal.jar @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ef1ecb7ab2d900ba5df4eb8f44c7f9975031c19244afbdafc874ab85d82ad3c3 +size 443876 diff --git a/data/imagej_macro/ImageJ_plugins/3D_viewer/jogl-all-2.3.2-natives-windows-amd64.jar b/data/imagej_macro/ImageJ_plugins/3D_viewer/jogl-all-2.3.2-natives-windows-amd64.jar new file mode 100644 index 0000000000000000000000000000000000000000..307b7f5f30632a52bdeb38d735157dbaaff41004 --- /dev/null +++ b/data/imagej_macro/ImageJ_plugins/3D_viewer/jogl-all-2.3.2-natives-windows-amd64.jar @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8c53b1884cef19309d34fd10a94b010136d9d6de9a88c386f46006fb47acab5d +size 240721 diff --git a/data/imagej_macro/ImageJ_plugins/3D_viewer/jogl-all-2.3.2.jar b/data/imagej_macro/ImageJ_plugins/3D_viewer/jogl-all-2.3.2.jar new file mode 100644 index 0000000000000000000000000000000000000000..8d064b0d067e5240661e5be617bfb0ef48e5c479 --- /dev/null +++ b/data/imagej_macro/ImageJ_plugins/3D_viewer/jogl-all-2.3.2.jar @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e74603dc77b4183f108480279dbbf7fed3ac206069478636406c1fb45e83b31a +size 3414448 diff --git a/data/imagej_macro/ImageJ_plugins/3D_viewer/jogl-all-main-2.3.2.jar b/data/imagej_macro/ImageJ_plugins/3D_viewer/jogl-all-main-2.3.2.jar new file mode 100644 index 0000000000000000000000000000000000000000..5eed15883f1bdc88f602bfd0ff94e6a9a2b878d0 Binary files /dev/null and b/data/imagej_macro/ImageJ_plugins/3D_viewer/jogl-all-main-2.3.2.jar differ diff --git a/data/imagej_macro/ImageJ_plugins/3D_viewer/vecmath-1.6.0-scijava-2.jar b/data/imagej_macro/ImageJ_plugins/3D_viewer/vecmath-1.6.0-scijava-2.jar new file mode 100644 index 0000000000000000000000000000000000000000..0cc16d27e3b0e513707590403c65d35b9c449888 --- /dev/null +++ b/data/imagej_macro/ImageJ_plugins/3D_viewer/vecmath-1.6.0-scijava-2.jar @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9ff4ede53f0fd6e25dc32f8139640a14f7222bebaae45fc4bced6f51d797b8fd +size 164203 diff --git a/data/imagej_macro/ImageJ_plugins/readme.txt b/data/imagej_macro/ImageJ_plugins/readme.txt new file mode 100644 index 0000000000000000000000000000000000000000..3ae42d3cd71c05062ff93df8b6dec7da0e1cfc71 --- /dev/null +++ b/data/imagej_macro/ImageJ_plugins/readme.txt @@ -0,0 +1,35 @@ +Please copy all folders here to ImageJ/plugins/ folder and relaunch ImageJ platform + +For update, you just need to replace TissueJ4Merfish.jar in the folder spatial3dtissuej_plugin/ by the most updated plugin and relaunch ImageJ. + + + +Other notes: +For 3D viewer, you can copy 3dviewer plugins folder into your plugins directory +or install latest 3d viewer plugin from Fiij +Note: if the program do not work, the main issue may be due lack of supporting packages from 3D viewers. In this case, you can delete your current 3d viewer version, and replaced by the folder that I provided in this github + +For Fiji_plugins.jar you can use the latest version in your local ImageJ + +When launching ImageJ, platform will notice you a plugin with multiple versions in plugins folder, and overwrite it using one version. In this case, you can go into your local ImageJ/plugins folder, and remove one old version of plugin + +Acknowledgement: +See more at: +https://mcib3d.frama.io/3d-suite-imagej/ +J. Ollion, J. Cochennec, F. Loll, C. Escudé, T. Boudier. (2013) TANGO: A Generic Tool for High-throughput 3D Image Analysis for Studying Nuclear Organization. Bioinformatics 2013 Jul 15;29(14):1840-1. + +The 3D suite would like to thank P. Andrey, J.-F. Gilles and the developers of the following plugins : + + Imagescience + LocalThickness + ConvexHull3D + 3D Object Counter + Droplet Counter + +Links + BoneJ + 3D Shapes + LabKit + 3D Viewer + MorphoLibJ + CLIJ diff --git a/data/imagej_macro/ImageJ_plugins/spatial3dtissuej_plugin/TissueJ4Merfish_v14.jar b/data/imagej_macro/ImageJ_plugins/spatial3dtissuej_plugin/TissueJ4Merfish_v14.jar new file mode 100644 index 0000000000000000000000000000000000000000..ede9263bfdad80ffbde246927aa10b53dcd8b8f7 --- /dev/null +++ b/data/imagej_macro/ImageJ_plugins/spatial3dtissuej_plugin/TissueJ4Merfish_v14.jar @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7b4cbabea978a48df86ca4f3ace607854ca44c273a8a30cad872d4234f3807b7 +size 841067 diff --git a/data/imagej_macro/ImageJ_plugins/utils/3D_Convex_Hull.jar b/data/imagej_macro/ImageJ_plugins/utils/3D_Convex_Hull.jar new file mode 100644 index 0000000000000000000000000000000000000000..b48c742b016a10cbc53040f07fab2224f7731ac6 --- /dev/null +++ b/data/imagej_macro/ImageJ_plugins/utils/3D_Convex_Hull.jar @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:52c261d7c666b964ec6391a92739e7a65bc827e28a79983005e0883bf1741bb4 +size 130741 diff --git a/data/imagej_macro/ImageJ_plugins/utils/Fiji_Plugins-3.1.1.jar b/data/imagej_macro/ImageJ_plugins/utils/Fiji_Plugins-3.1.1.jar new file mode 100644 index 0000000000000000000000000000000000000000..48dff738a01f5b735faac917deb3459f3cc22c94 Binary files /dev/null and b/data/imagej_macro/ImageJ_plugins/utils/Fiji_Plugins-3.1.1.jar differ diff --git a/data/imagej_macro/ImageJ_plugins/utils/SlideJ_.jar b/data/imagej_macro/ImageJ_plugins/utils/SlideJ_.jar new file mode 100644 index 0000000000000000000000000000000000000000..354891280fd9610613a125f9fe9ca77156115cd7 Binary files /dev/null and b/data/imagej_macro/ImageJ_plugins/utils/SlideJ_.jar differ diff --git a/data/imagej_macro/ImageJ_plugins/utils/fiji-lib-2.1.2.jar b/data/imagej_macro/ImageJ_plugins/utils/fiji-lib-2.1.2.jar new file mode 100644 index 0000000000000000000000000000000000000000..bba3338b6b713f7fbc61116de9a83c63b18cab3b Binary files /dev/null and b/data/imagej_macro/ImageJ_plugins/utils/fiji-lib-2.1.2.jar differ diff --git a/data/imagej_macro/ImageJ_plugins/utils/imagescience.jar b/data/imagej_macro/ImageJ_plugins/utils/imagescience.jar new file mode 100644 index 0000000000000000000000000000000000000000..7a3a4fddaae8149d09754d7be73b2777a3dc93d7 --- /dev/null +++ b/data/imagej_macro/ImageJ_plugins/utils/imagescience.jar @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6975dcc17d4d9e0dc618060e93266c816dc62764379fe46bae2f7c6eaecfe134 +size 283410 diff --git a/data/imagej_macro/ImageJ_plugins/utils/mpicbg_-1.4.1.jar b/data/imagej_macro/ImageJ_plugins/utils/mpicbg_-1.4.1.jar new file mode 100644 index 0000000000000000000000000000000000000000..8d0f88ef288d5732463d10b3c1e31d483f54cd89 --- /dev/null +++ b/data/imagej_macro/ImageJ_plugins/utils/mpicbg_-1.4.1.jar @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a1c962431c6f7998d3e263a32308471128dd050373603d7419954fba456ce859 +size 138726 diff --git a/data/imagej_macro/ImageJ_plugins/utils/quickhull3d-1.0.0.jar b/data/imagej_macro/ImageJ_plugins/utils/quickhull3d-1.0.0.jar new file mode 100644 index 0000000000000000000000000000000000000000..0ff0124319eb2acfaca54c96b74b5d57c82b697d Binary files /dev/null and b/data/imagej_macro/ImageJ_plugins/utils/quickhull3d-1.0.0.jar differ diff --git a/data/imagej_macro/bleed_throught_validate/bleed_throught_macro.ijm b/data/imagej_macro/bleed_throught_validate/bleed_throught_macro.ijm new file mode 100644 index 0000000000000000000000000000000000000000..586532936da35e05e7b067cfb5ef037611156ec4 --- /dev/null +++ b/data/imagej_macro/bleed_throught_validate/bleed_throught_macro.ijm @@ -0,0 +1,155 @@ +//// How to use +//// Open macro from ImageJ menu +//// Change parameter setting here, and run entire macro +//// For input folder browser, choose the input image folder +//// It takes ~20 seconds to run this macro + +print("\\Clear"); + + +// Parameters setting +source_image="merFISH_02_007_01_wavelength_561.TIFF"; // change parameter here +target_image="merFISH_02_007_01_wavelength_647.TIFF"; // change parameter here +suffixe=".TIFF"; + + + + + + +print("----------------------------------------------------------------"); +//dir = getArgument; +dir=getDirectory("mouse"); // open a browser, allow you to choose input directory +//dir = "yourlocaldir/bleed_throught_validate/raw/"; +// ex: dir="/Users/htran/Documents/storage_tmp/merfish_XP2059/bleed_throught_validate/raw/"; +if (dir=="") + exit ("No argument!"); + +print("Working dir: "+dir+"\n"); + +results_dir=File.getParent(dir)+"/results/"; +if(!File.exists(results_dir)) + File.mkdir(results_dir); + + + + + + +short_name_source = substring(source_image,0,lastIndexOf(source_image,suffixe)); +short_name_target = substring(target_image,0,lastIndexOf(target_image,suffixe)); +IJ.log(short_name_source); +IJ.log(short_name_target); + +// Source image first +print("Loading image: "+source_image); +open(dir+source_image); +selectWindow(source_image); +run("Enhance Contrast", "saturated=0.35"); +if (bitDepth > 8) {run("8-bit");} +//run("Median...", "radius=2"); // in case you see lots of noises detected as signals +run("Convolve...", "text1=[-1 -1 -1 -1 -1\n-1 -1 -1 -1 -1\n-1 -1 24 -1 -1\n-1 -1 -1 -1 -1\n-1 -1 -1 -1 -1\n] normalize"); + + +////only signals with intensity values from 250 to 255 are considered as signals, from my observation of spots and noise in images. +////You can use other thresholds, this macro just give an estimation, not provide accurate results for publication. +setThreshold(250, 255, "raw"); +//setThreshold(250, 255); +setOption("BlackBackground", true); +run("Convert to Mask"); +run("Grays"); + +selectWindow(source_image); +bin_source=short_name_source+"_BINARY"; //can open zip file from ImageJ to have tif format +saveAs("ZIP", results_dir+bin_source+".zip"); +print("Deconvolution done!"); + + + + +print("Loading image: "+target_image); +open(dir+target_image); +selectWindow(target_image); +run("Enhance Contrast", "saturated=0.35"); +if (bitDepth > 8) {run("8-bit");} + +// ATTENTION: in case you see lots of noises detected as signals, because this image contains large amount of noises --> need to use median filter here +// If you don't see lots of noise, please comment median filter. +run("Median...", "radius=2"); + +run("Convolve...", "text1=[-1 -1 -1 -1 -1\n-1 -1 -1 -1 -1\n-1 -1 24 -1 -1\n-1 -1 -1 -1 -1\n-1 -1 -1 -1 -1\n] normalize"); +setThreshold(250, 255, "raw"); +//setThreshold(250, 255); +setOption("BlackBackground", true); +run("Convert to Mask"); +run("Grays"); + +selectWindow(target_image); +bin_target=short_name_target+"_BINARY"; //can open zip file from ImageJ to have tif format +saveAs("ZIP",results_dir+bin_target+".zip"); +print("Deconvolution done!"); + + + + + + +// histogram here + +//// First, extracting signals that are overlapped in source and target images +imageCalculator("AND create", bin_source+".tif", bin_target+".tif"); +selectWindow("Result of "+bin_source+".tif"); +output_image="bleedthrought_signals"; //can open zip file from ImageJ to have tif format +saveAs("ZIP",results_dir+output_image+".zip"); + + +//Counting number of spots in source image +selectWindow(bin_source+".tif"); +nBins = 256; +getHistogram(values, counts, nBins); +source_spots=counts[255]; // number of spots +IJ.log("Source image is: "+source_image); +IJ.log("Number of spots in source image is: "+source_spots); + + +//Counting number of spots in bleedthrought image +selectWindow(output_image+".tif"); +getHistogram(values, counts, nBins); +bleedthrought_spots=counts[255]; // number of spots +IJ.log("Number of spots that bleed throught other wavelength channel is: "+bleedthrought_spots); + + +//Counting number of spots in target image +selectWindow(bin_target+".tif"); +getHistogram(values, counts, nBins); +target_spots=counts[255]; // number of spots +IJ.log("Target image is: "+target_image); +IJ.log("Number of spots in target image is: "+target_spots); + + +pct_bleed=100*bleedthrought_spots/source_spots; +IJ.log("Percentage of bleed throught is: "+pct_bleed); + +pct_bleed_target=100*bleedthrought_spots/target_spots; +IJ.log("Percentage of bleed throught is: "+pct_bleed_target); + + +// Save results into a csv file +setResult("source_img", 0, source_image); +setResult("target_img", 0, target_image); +setResult("pct_bleedthrought_source", 0, pct_bleed); +setResult("pct_bleedthrought_target", 0, pct_bleed_target); +updateResults(); + +selectWindow("Results"); +saveAs("Results",results_dir+"bleed_throught_report.csv"); +selectWindow("Results"); +run("Close"); +print("Save output into the folder: "+results_dir); + +run("Close All"); + +print("Completed"); +print("----------------------------------------------------------------"); + + diff --git a/data/imagej_macro/bleed_throught_validate/raw/merFISH_02_007_01_wavelength_561.TIFF b/data/imagej_macro/bleed_throught_validate/raw/merFISH_02_007_01_wavelength_561.TIFF new file mode 100644 index 0000000000000000000000000000000000000000..dea22dcd671a5a00991314eab72471d0b1c12a3a --- /dev/null +++ b/data/imagej_macro/bleed_throught_validate/raw/merFISH_02_007_01_wavelength_561.TIFF @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:224c7e7ed6eb8e4a3dc655412cab88971a255dcc72d43433a0fe746656f20260 +size 5171598 diff --git a/data/imagej_macro/bleed_throught_validate/raw/merFISH_02_007_01_wavelength_647.TIFF b/data/imagej_macro/bleed_throught_validate/raw/merFISH_02_007_01_wavelength_647.TIFF new file mode 100644 index 0000000000000000000000000000000000000000..b37c29e082880af127f9cfbf2af081b5812a1d09 --- /dev/null +++ b/data/imagej_macro/bleed_throught_validate/raw/merFISH_02_007_01_wavelength_647.TIFF @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d1ab714c0baf8900a2b8e2f6e5d76b2a3308f16ed301567b7636ee55d40225f +size 5171598 diff --git a/data/imagej_macro/bleed_throught_validate/results/bleed_throught_report.csv b/data/imagej_macro/bleed_throught_validate/results/bleed_throught_report.csv new file mode 100644 index 0000000000000000000000000000000000000000..740e3040be5004ee42267b98b05b197ee57ede48 --- /dev/null +++ b/data/imagej_macro/bleed_throught_validate/results/bleed_throught_report.csv @@ -0,0 +1,2 @@ + ,source_img,target_img,pct_bleedthrought_source,pct_bleedthrought_target +1,merFISH_02_007_01_wavelength_561.TIFF,merFISH_02_007_01_wavelength_647.TIFF,0.258,17.386 diff --git a/data/imagej_macro/bleed_throught_validate/results/bleedthrought_signals.zip b/data/imagej_macro/bleed_throught_validate/results/bleedthrought_signals.zip new file mode 100644 index 0000000000000000000000000000000000000000..88724038d2b713f0dd10aac4f59d28da76a34243 --- /dev/null +++ b/data/imagej_macro/bleed_throught_validate/results/bleedthrought_signals.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:169ff3492e5cff7155db973c062af8d630354b5898c2609de67e47438628b843 +size 3099 diff --git a/data/imagej_macro/bleed_throught_validate/results/merFISH_02_007_01_wavelength_561_BINARY.zip b/data/imagej_macro/bleed_throught_validate/results/merFISH_02_007_01_wavelength_561_BINARY.zip new file mode 100644 index 0000000000000000000000000000000000000000..401c173f11c75870863398180bff78ce074cf8f9 --- /dev/null +++ b/data/imagej_macro/bleed_throught_validate/results/merFISH_02_007_01_wavelength_561_BINARY.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7cf64e0aa94e2cd897db6da10ae9e84cd84c700b8539e7f97fc947b84ef10712 +size 72243 diff --git a/data/imagej_macro/bleed_throught_validate/results/merFISH_02_007_01_wavelength_647_BINARY.zip b/data/imagej_macro/bleed_throught_validate/results/merFISH_02_007_01_wavelength_647_BINARY.zip new file mode 100644 index 0000000000000000000000000000000000000000..04d611eefbca64e39455e6a90f946d234738cc6a --- /dev/null +++ b/data/imagej_macro/bleed_throught_validate/results/merFISH_02_007_01_wavelength_647_BINARY.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:81d81d26f2259ef6cb28be1943b649b131f70f8683b25cb57c3b5bc9eeaf202d +size 3953 diff --git a/data/imagej_macro/blur_detector/dataset1/merFISH_01_025_05.TIFF b/data/imagej_macro/blur_detector/dataset1/merFISH_01_025_05.TIFF new file mode 100644 index 0000000000000000000000000000000000000000..26be9bd0c5ab9051d582161a17d5359a6bcd4337 --- /dev/null +++ b/data/imagej_macro/blur_detector/dataset1/merFISH_01_025_05.TIFF @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:87d350e4df369288588e2e235342641861845a827a7893a9e3bb21d6a4715b05 +size 500247 diff --git a/data/imagej_macro/blur_detector/dataset1/merFISH_08_025_05.TIFF b/data/imagej_macro/blur_detector/dataset1/merFISH_08_025_05.TIFF new file mode 100644 index 0000000000000000000000000000000000000000..e873cda98d8c9f830dffa674ee8bea2c21b3d948 --- /dev/null +++ b/data/imagej_macro/blur_detector/dataset1/merFISH_08_025_05.TIFF @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b165e1ea8c361cad39638197ffccb95ab68de06223b6bf86e8ed9b186e811ead +size 500247 diff --git a/data/imagej_macro/blur_detector/dataset2/merFISH_05_025_05.TIFF b/data/imagej_macro/blur_detector/dataset2/merFISH_05_025_05.TIFF new file mode 100644 index 0000000000000000000000000000000000000000..d73d7980e9e254dff179838b3a904b554fe11976 --- /dev/null +++ b/data/imagej_macro/blur_detector/dataset2/merFISH_05_025_05.TIFF @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a7ab993b728c287b4506bfe2792f724fa8bca5632c47e88aba807c3b317d27cb +size 500247 diff --git a/data/imagej_macro/blur_detector/dataset2/merFISH_06_025_05.TIFF b/data/imagej_macro/blur_detector/dataset2/merFISH_06_025_05.TIFF new file mode 100644 index 0000000000000000000000000000000000000000..58bf6f8a6c24126244ddf251b7b9b9fcb77e9bfc --- /dev/null +++ b/data/imagej_macro/blur_detector/dataset2/merFISH_06_025_05.TIFF @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d753615bc135dd70608e3bd09fbca6caa56e18eb97797f9bb26ff527b677378d +size 500247 diff --git a/data/imagej_macro/blur_detector/detecting_blur_image.R b/data/imagej_macro/blur_detector/detecting_blur_image.R new file mode 100644 index 0000000000000000000000000000000000000000..355c35e4a62f049e73fa6860635d3cfd0fc86403 --- /dev/null +++ b/data/imagej_macro/blur_detector/detecting_blur_image.R @@ -0,0 +1,85 @@ +suppressPackageStartupMessages({ + # library(tidyverse) + library(dplyr) + library(ggplot2) + # library(igraph) + # library(ggraph) + library(data.table) + library(RColorBrewer) +}) + + +read_input_data <- function(input_dir, total_pixels){ + fns <- list.files(input_dir) + fns <- fns[grepl('.csv',fns)] + print("Number of csv histogram files: ") + print(length(fns)) + good_signals_intensity_thrs <- 5 + summary_stat <- tibble::tibble() + for(fn in fns){ + df <- data.table::fread(paste0(input_dir, fn)) + nbOverExp <- df %>% + dplyr::filter(intensity_val=='greater_30') %>% + dplyr::pull(counts) + total_counts <- df %>% + dplyr::filter(intensity_val!='greater_30')%>% + dplyr::mutate(intensity_val=as.numeric(intensity_val)) %>% + dplyr::filter(intensity_val>good_signals_intensity_thrs)%>% + dplyr::summarise(total_counts=sum(counts)) %>% + dplyr::pull(total_counts) + + stat <- tibble::tibble(image_fn=fn, + pct_signals=round(100*total_counts/total_pixels,2), + nb_overExp=nbOverExp) + summary_stat <- dplyr::bind_rows(summary_stat, stat) + + + } + return(summary_stat) +} + +get_stat <- function(summary_stat, datatag, save_dir){ + # fn <- 'merFISH_02_006_05_histogram.csv' + # View(df) + outliers <- tibble::tibble() + dim(summary_stat) + summary_stat$pct_overExp <- round(100*summary_stat$nb_overExp/total_pixels,3) + # summary(summary_stat$pct_signals) + # summary(summary_stat$pct_overExp) + # head(summary_stat) + + ## Detecting all outliers + outliers_top_thrs <- 0.95 + outliers_top_FOVs <- summary_stat %>% + dplyr::filter(pct_signals > quantile(pct_signals, outliers_top_thrs)) + print('Amount of outliers with large number of signals: ') + print(dim(outliers_top_FOVs)) + outliers_top_FOVs$desc <- 'high_pct_signals' + outliers <- dplyr::bind_rows(outliers, outliers_top_FOVs) + + outliers_bottom_thrs <- 0.05 + outliers_bottom_FOVs <- summary_stat %>% + dplyr::filter(pct_signals < quantile(pct_signals, outliers_bottom_thrs)) + print('Amount of outliers with low signals: ') + print(dim(outliers_bottom_FOVs)) + outliers_bottom_FOVs$desc <- 'low_pct_signals' + outliers <- dplyr::bind_rows(outliers, outliers_bottom_FOVs) + + artifact_thres <- 0.3 + outliers_artifacts <- summary_stat %>% + dplyr::filter(pct_overExp>=artifact_thres) + outliers_artifacts$desc <- 'contain_artifacts' + outliers <- dplyr::bind_rows(outliers, outliers_artifacts) + print('Amount of artifacts: ') + print(dim(outliers_artifacts)) + data.table::fwrite(outliers, paste0(save_dir, datatag, '_outliers.csv')) + +} + + +total_pixels = 1608 * 1608 +datatag <- 'XP2509' +input_dir <- '/Users/htran/Documents/merfish_temp_storage/testing/results/' +summary_stat <- read_input_data(input_dir, total_pixels) +save_dir <- input_dir +get_stat(summary_stat, datatag, save_dir) diff --git a/data/imagej_macro/blur_detector/execute_blur_detector_dataset1.sh b/data/imagej_macro/blur_detector/execute_blur_detector_dataset1.sh new file mode 100644 index 0000000000000000000000000000000000000000..38fcd4b0c38466a71f8128e55ab03f230e6733fd --- /dev/null +++ b/data/imagej_macro/blur_detector/execute_blur_detector_dataset1.sh @@ -0,0 +1,59 @@ +#!/bin/sh + +# batch macro input_filename +# Ref: page 20: https://imagej.nih.gov/ij/docs/macro_reference_guide.pdf + +## Configuration MacOS +imagej_dir="/Applications/ImageJ.app" ## MacOS ImageJ java run folder +macro_dir="/Users/hoatran/Documents/BCCRC_projects/merfish/datasets_reduced_size/blur_detector/" +project_dir="/Users/hoatran/Documents/BCCRC_projects/merfish/datasets_reduced_size/blur_detector/" + +series="dataset1/" +task="blur_detector1" + +## ImageJ/ Fiji can be installed to Applications, or put into any folder in your drive. +# imagej_dir="/Applications/ImageJ.app" ## MacOS ImageJ java run folder +# imagej_dir="/Applications/Fiji.app" ## MacOS Fiji java run folder +# imagej_dir="/Users/htran/Downloads/Fiji.app/" ## MacOS Fiji java run folder - from my computer + + +# imagej_exe_file=${imagej_dir}jars/ij-1.53q.jar ## Fiji file location, in general file name is ij.jar, sometimes include version here +imagej_exe_file=${imagej_dir}/Contents/Java/ij.jar ## ImageJ exe file location, in general file name is ij.jar, sometimes include version here + + +macro_fn="${macro_dir}macro_blur_detector.ijm" + + + +log_file="${macro_dir}${task}.log" +echo $log_file +exec >> $log_file 2>&1 && tail $log_file + +input_dir="${project_dir}${series}" +echo "__________________________________\n" +echo "Input directory is: \n" +echo $input_dir +echo "Blur detector \n" +## You can change memory amount, ex: 20000m to 30000m so program will run faster. +## MacOS background mode here + +## If you have java environment jre installed in your computer +java -Xmx10000m -jar ${imagej_exe_file} -ijpath $imagej_dir/ -batch $macro_fn $input_dir + +## Otherwise using existing jre env from Fiji here +# /Users/htran/Downloads/Fiji.app/java/macosx/adoptopenjdk-8.jdk/jre/Contents/Home/bin/java -Xmx20000m -jar $imagej_dir/Contents/Java/ij.jar -ijpath $imagej_dir/ -batch $macro_fn $input_dir +# ${imagej_dir}java/macosx/adoptopenjdk-8.jdk/jre/Contents/Home/bin/java -Xmx20000m -jar ${imagej_exe_file} -ijpath $imagej_dir/ -batch $macro_fn $input_dir + +## Linux background mode here, using xvfb-run in case you run in server (graphical env), in local computer, java command is enough +# xvfb-run -a java -Xmx15000m -jar $imagej_dir/ij.jar -ijpath $imagej_dir/ -batch $macro_fn $input_dir + +## In Linux local computer, java command is sufficient +# java -Xmx15000m -jar $imagej_dir/ij.jar -ijpath $imagej_dir/ -batch $macro_fn $input_dir + +echo "Nucleus Segmentation Completed!" +echo "__________________________________\n" + + + + + diff --git a/data/imagej_macro/blur_detector/execute_blur_detector_dataset2.sh b/data/imagej_macro/blur_detector/execute_blur_detector_dataset2.sh new file mode 100644 index 0000000000000000000000000000000000000000..3467d156c7c1287e376e3ca41dc2a75ed3949398 --- /dev/null +++ b/data/imagej_macro/blur_detector/execute_blur_detector_dataset2.sh @@ -0,0 +1,59 @@ +#!/bin/sh + +# batch macro input_filename +# Ref: page 20: https://imagej.nih.gov/ij/docs/macro_reference_guide.pdf + +## Configuration MacOS +imagej_dir="/Applications/ImageJ.app" ## MacOS ImageJ java run folder +macro_dir="/Users/hoatran/Documents/BCCRC_projects/merfish/datasets_reduced_size/blur_detector/" +project_dir="/Users/hoatran/Documents/BCCRC_projects/merfish/datasets_reduced_size/blur_detector/" + +series="dataset2/" +task="blur_detector2" + +## ImageJ/ Fiji can be installed to Applications, or put into any folder in your drive. +# imagej_dir="/Applications/ImageJ.app" ## MacOS ImageJ java run folder +# imagej_dir="/Applications/Fiji.app" ## MacOS Fiji java run folder +# imagej_dir="/Users/htran/Downloads/Fiji.app/" ## MacOS Fiji java run folder - from my computer + + +# imagej_exe_file=${imagej_dir}jars/ij-1.53q.jar ## Fiji file location, in general file name is ij.jar, sometimes include version here +imagej_exe_file=${imagej_dir}/Contents/Java/ij.jar ## ImageJ exe file location, in general file name is ij.jar, sometimes include version here + + +macro_fn="${macro_dir}macro_blur_detector.ijm" + + + +log_file="${macro_dir}${task}.log" +echo $log_file +exec >> $log_file 2>&1 && tail $log_file + +input_dir="${project_dir}${series}" +echo "__________________________________\n" +echo "Input directory is: \n" +echo $input_dir +echo "Blur detector \n" +## You can change memory amount, ex: 20000m to 30000m so program will run faster. +## MacOS background mode here + +## If you have java environment jre installed in your computer +java -Xmx10000m -jar ${imagej_exe_file} -ijpath $imagej_dir/ -batch $macro_fn $input_dir + +## Otherwise using existing jre env from Fiji here +# /Users/htran/Downloads/Fiji.app/java/macosx/adoptopenjdk-8.jdk/jre/Contents/Home/bin/java -Xmx20000m -jar $imagej_dir/Contents/Java/ij.jar -ijpath $imagej_dir/ -batch $macro_fn $input_dir +# ${imagej_dir}java/macosx/adoptopenjdk-8.jdk/jre/Contents/Home/bin/java -Xmx20000m -jar ${imagej_exe_file} -ijpath $imagej_dir/ -batch $macro_fn $input_dir + +## Linux background mode here, using xvfb-run in case you run in server (graphical env), in local computer, java command is enough +# xvfb-run -a java -Xmx15000m -jar $imagej_dir/ij.jar -ijpath $imagej_dir/ -batch $macro_fn $input_dir + +## In Linux local computer, java command is sufficient +# java -Xmx15000m -jar $imagej_dir/ij.jar -ijpath $imagej_dir/ -batch $macro_fn $input_dir + +echo "Nucleus Segmentation Completed!" +echo "__________________________________\n" + + + + + diff --git a/data/imagej_macro/blur_detector/macro_blur_detector.ijm b/data/imagej_macro/blur_detector/macro_blur_detector.ijm new file mode 100644 index 0000000000000000000000000000000000000000..665f4c431ba9938ed94d0adcc01de5a6b9e91c44 --- /dev/null +++ b/data/imagej_macro/blur_detector/macro_blur_detector.ijm @@ -0,0 +1,24 @@ +setBatchMode(true); +print("\\Clear"); + +input_dir = getArgument; +//input_dir = "/Users/yourdir/dataset1/"; // for testing purpose, you can disable line above, and use this +if (input_dir=="") + exit ("No argument!"); + + + +save_dir=File.getParent(input_dir)+"/"+File.getName(input_dir)+"_results/"; +if(!File.exists(save_dir)) + File.mkdir(save_dir); + +print("Working dir: "+input_dir+"\n"); +print("Output dir: "+save_dir+"\n"); + +number_neighbors=48; + +// Running program +run("BLUR DETECTOR ENTIRE FOLDER", "input="+input_dir+" save="+save_dir+" number="+number_neighbors); + + +setBatchMode(false); diff --git a/data/imagej_macro/cell_zone_detection/Macro_cell_zone_extension.ijm b/data/imagej_macro/cell_zone_detection/Macro_cell_zone_extension.ijm new file mode 100644 index 0000000000000000000000000000000000000000..7edce6cadad86611cf3e27688b83659119e3288b --- /dev/null +++ b/data/imagej_macro/cell_zone_detection/Macro_cell_zone_extension.ijm @@ -0,0 +1,81 @@ +//====================================================================================== +//// Installation +//// See at https://github.com/nhuhoa/Spatial3DTissueJ/tree/master/ImageJ_plugins_jar/list_plugin_readme.txt +//// Specific plugin to run functions here: TissueJ4Merfish_v14.jar, need version >=14 +//====================================================================================== +//// Preparation +//// nuclei segmented input images + + + +//====================================================================================== +setBatchMode(true); +print("________________cell zone detection with pre-defined radius___________________________"); + +// Please modify the dir input parameter here +//dir="YourDirectory/demo_watershed_seg/"; +dir="/Users/hoatran/Documents/BCCRC_projects/merfish/image_processing/demo_watershed_seg/"; +seg_image_fn="merFISH_01_025_08-SEG.tif"; +radius_extension=15; +save_dir=File.getParent(dir)+"/cell_zone_detection/"; + +open(dir + seg_image_fn); +run("DETECTING CELL ZONE", "save_dir="+save_dir+" nuclei="+seg_image_fn+" radius_max="+radius_extension+" save"); + +run("Close All"); +print("Completed!"); +setBatchMode(false); + + + + +//====================================================================================== +setBatchMode(true); +print("______________ cell zone detection with infinite extension _____________________________"); +print(" Radius = 0 means no max radius"); + +// Please modify the dir input parameter here +dir="YourDirectory/demo_watershed_seg/"; +dir="/Users/hoatran/Documents/BCCRC_projects/merfish/image_processing/demo_watershed_seg/"; +seg_image_fn="merFISH_01_025_08-SEG.tif"; +radius_extension=0; +save_dir=File.getParent(dir)+"/cell_zone_detection/"; + +open(dir + seg_image_fn); +run("DETECTING CELL ZONE", "save_dir="+save_dir+" nuclei="+seg_image_fn+" radius_max="+radius_extension+" save"); + +run("Close All"); +print("Completed!"); +setBatchMode(false); + + +//====================================================================================== +setBatchMode(true); +print("_______________cell zone detection with nuclei as seed, and binary cell mask and max radius of extension____________________________"); + +// Please modify the dir input parameter here +//dir="YourDirectory/demo_watershed_seg/"; +dir="/Users/hoatran/Documents/BCCRC_projects/merfish/image_processing/demo_watershed_seg/"; +seg_image_fn="merFISH_01_025_08-SEG.tif"; +cell_mask_fn="merFISH_01_025_08-mask.tif"; +radius_extension=15; +save_dir=File.getParent(dir)+"/cell_zone_detection/"; + +open(dir + seg_image_fn); +open(dir + cell_mask_fn); +suffixe_filename=".tif"; +cell_mask_fn = substring(cell_mask_fn,0,lastIndexOf(cell_mask_fn,suffixe_filename)); +seg_image_fn = substring(seg_image_fn,0,lastIndexOf(seg_image_fn,suffixe_filename)); + +run("3D Watershed Split", "binary="+cell_mask_fn+" seeds="+seg_image_fn+" radius="+radius_extension); + + +selectWindow("Split"); +saveAs("Tiff", save_dir+seg_image_fn+"_cell_zone_detection_with_cell_mask.tif"); + +// For compressed format, that can open from ImageJ, compressed ~100 times but same quality +//saveAs("ZIP", save_dir+seg_image_fn+"_cell_zone_detection_with_cell_mask.zip"); + +run("Close All"); +print("Completed!"); +setBatchMode(false); diff --git a/data/imagej_macro/cell_zone_detection/TissueJ4Merfish_v14.jar b/data/imagej_macro/cell_zone_detection/TissueJ4Merfish_v14.jar new file mode 100644 index 0000000000000000000000000000000000000000..ede9263bfdad80ffbde246927aa10b53dcd8b8f7 --- /dev/null +++ b/data/imagej_macro/cell_zone_detection/TissueJ4Merfish_v14.jar @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7b4cbabea978a48df86ca4f3ace607854ca44c273a8a30cad872d4234f3807b7 +size 841067 diff --git a/data/imagej_macro/cell_zone_detection/merFISH_01_025_08-SEG.tif b/data/imagej_macro/cell_zone_detection/merFISH_01_025_08-SEG.tif new file mode 100644 index 0000000000000000000000000000000000000000..e1c2b07148e8e074ffa843ab955e58ab4459f386 --- /dev/null +++ b/data/imagej_macro/cell_zone_detection/merFISH_01_025_08-SEG.tif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:388fd61b0a5cff353623bc4c4f6b06867906910fa68d77b674f75155bc448286 +size 1281812 diff --git a/data/imagej_macro/cell_zone_detection/merFISH_01_025_08-mask.tif b/data/imagej_macro/cell_zone_detection/merFISH_01_025_08-mask.tif new file mode 100644 index 0000000000000000000000000000000000000000..126827f65630ba2ff30b3bf2482a1b321b581342 --- /dev/null +++ b/data/imagej_macro/cell_zone_detection/merFISH_01_025_08-mask.tif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b8a6a731ec94b4986e7c673a1e2f3bd5fc4df4b6d508a222176c8fb83352a7d0 +size 640236 diff --git a/data/imagej_macro/counting_spots/counting_spots_FOVs_display.py b/data/imagej_macro/counting_spots/counting_spots_FOVs_display.py new file mode 100644 index 0000000000000000000000000000000000000000..f6adae0999d4421dbf8658bb5989666778c4b07f --- /dev/null +++ b/data/imagej_macro/counting_spots/counting_spots_FOVs_display.py @@ -0,0 +1,98 @@ +from re import L +from turtle import shape +import pandas as pd +import seaborn as sns +import matplotlib.pyplot as plt +from pathlib import Path +import os +import numpy as np +#load csv files +#returns files names as well to preserve laser channel information +def load_data(path:Path) -> tuple: + files=[os.path.join(path,file) for file in os.listdir(path)] + dfs=[] + for f in files: + if ".csv" in f.lower(): + df=pd.read_csv(f) + dfs.append(df) + return tuple(dfs) + + +def find_rect(fovs:int): + area=fovs + w=area + l=2 + while l <=w : + if (area/l)%1==0: w=area/l + l+=1 + return int(w) + +def min_max_scale_percent(df,val): + max_spot=np.max(df["total_spots"]) + min_spot=np.min(df["total_spots"]) + return round((val-min_spot)/(max_spot-min_spot)*100,2) + +#shows simple heatmap with median spot count per tile +#counts are scaled between 1-100 just to get a sense of a good tile +def plot_heatmap(df): + total_fov=np.max(df["FOV"]) + + w=find_rect(total_fov) + l=int(total_fov/w) + heatmap=np.empty(shape=(w,l),dtype=int) + index=1 + for y in range(heatmap.shape[0]): + for x in range(heatmap.shape[1]): + print(index) + val=min_max_scale_percent( + df, + np.median(df["total_spots"][df["FOV"] == index]) + ) + heatmap[y][x]=val + index+=1 + sns.heatmap(data=heatmap,annot=True) + plt.show() + + + +#plots 2*num_tiles bar graphs each showing spots captured in a round for that tile +def plot_grid(ch1,ch2,savePath:Path): + os.chdir(savePath) + total_fov=np.max(ch1["FOV"]) + ymax=np.max(ch1["total_spots"]) if np.max(ch1["total_spots"])>np.max(ch2["total_spots"]) else np.max(ch2["total_spots"]) + fig, axs= plt.subplots(figsize=(16,120),nrows=total_fov,ncols=2,tight_layout=True) + + for i in range(axs.shape[0]): + axs[i][0].set_title(f"FOV: {i+1}") + axs[i][0].set_ylabel(f"# of spots", fontsize=15) + axs[i][0].set_xlabel("imaging round", fontsize=10) + axs[i][0].set_ylim(ymax) + axs[i][0].bar( + ch1["imaging_round"][ch1["FOV"]==i+1], + ch1["total_spots"][ch1["FOV"]==i+1] + ) + axs[i][0].invert_yaxis() + axs[0][0].set_title("647\nFOV: 1") + for i in range(axs.shape[0]): + axs[i][1].set_title(f"FOV: {i+1}") + axs[i][1].set_ylabel(f"# of spots", fontsize=15) + axs[i][1].set_xlabel("imaging round", fontsize=10) + axs[i][1].set_ylim(ymax) + axs[i][1].bar( + ch2["imaging_round"][ch2["FOV"]==i+1], + ch2["total_spots"][ch2["FOV"]==i+1] + ) + axs[i][1].invert_yaxis() + axs[0][1].set_title("750\nFOV: 1") + + plt.tight_layout(pad=0.4,w_pad=0.5,h_pad=1) + plt.savefig(os.path.join(savePath, "spots_accross_FOVs.pdf"),format="pdf") + + + + +if __name__ == "__main__": + path= r"C:\Users\Isaac von Riedemann\Downloads\counting_spots_across_FOVs_dataset_XP2059_647" + dfs=load_data(path) + + plot_grid(dfs[0],dfs[1],path) \ No newline at end of file diff --git a/data/imagej_macro/counting_spots/counting_spots_z_display.py b/data/imagej_macro/counting_spots/counting_spots_z_display.py new file mode 100644 index 0000000000000000000000000000000000000000..34ea875398b213aa61cf80d58380e68c2d727426 --- /dev/null +++ b/data/imagej_macro/counting_spots/counting_spots_z_display.py @@ -0,0 +1,70 @@ +import os +from pathlib import Path +import numpy as np +import pandas as pd +from matplotlib import pyplot as plt +import skimage +import argparse + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--input_dir', type = str, help = 'Input directory to csv files') + parser.add_argument('--output_dir', type = str, help = 'Output directory to store the results') + parser.add_argument('--exp_name', type = str, help = 'Experiment name, e.g.: XP2059') + parser.add_argument('--ch', type = int, help='Channel of concern') + parser.add_argument('--bar_width', type = float, default = 0.4, help = 'Width of bar') + + args = parser.parse_args() + + if not args.output_dir: + args.output_dir = args.input_dir + + f_list = irlist(args.input_dir, '*.csv') + + num_zslices = len(pd.read_csv(f_list[0])) + + num_irs = len(f_list) + + fov = f_list[0].split('_')[-3][3:] + + spots, xlist, X = get_xy(f_list, num_zslices) + + ymax = np.amax(spots) + + fig, axes = plt.subplots(nrows=num_irs, ncols=1, figsize=(30, 60)) + fig.suptitle(f'Counting spots for {args.exp_name}, FOV = {fov}, channel = {args.ch} nm', fontsize = 40) + + + for i, ax in enumerate(axes.flat): + ax.set_xticks(X, xlist[i], fontsize = 25) + ax.set_xticklabels(xlist[i], rotation = 45) + ax.set_ylabel(f'# spots in IR {i+1}', fontsize = 28, fontweight="bold") + ax.set_ylim([0,ymax]) + ax.tick_params(axis='y', labelsize=25) + ax.bar(X, spots[:,i], width = args.bar_width) + + + plt.tight_layout() + + fig.savefig(args.output_dir+f'/{args.exp_name}_{fov}_{args.ch}.pdf', transparent = 'False', format = 'pdf') + +def irlist(idir, match_str): + idir = Path(idir) + return [str(i) for i in sorted(list(idir.rglob(match_str)))] + +def get_xy(csv_list, zslices): + num_ir = len(csv_list) + spots_arr = np.zeros(shape=(zslices,num_ir)) + x_ticks = [] + for i in range(num_ir): + df = pd.read_csv(csv_list[i]) + spots_arr[:,i] = df['Spots'].to_numpy() + x = [s.replace('merFISH_', "") for s in sorted(list(df['Image']))] + x_ticks.append(x) + X = np.arange(zslices) + return spots_arr, x_ticks, X + +if __name__ == '__main__': + main() + #python counting_spots_z_display.py --input_dir /Users/ythapliyal/Counting_spots_old/XP2059/647 --exp_name XP2059 --ch 647 + diff --git a/data/imagej_macro/counting_spots/macro_counting_metric.txt b/data/imagej_macro/counting_spots/macro_counting_metric.txt new file mode 100644 index 0000000000000000000000000000000000000000..1c4abb77c47f57f368839272cb3e83b1840c5412 --- /dev/null +++ b/data/imagej_macro/counting_spots/macro_counting_metric.txt @@ -0,0 +1,85 @@ +// Open this macro from ImageJ +// Change the input_dir: a directory which contain 8 images of same wavelength. +// or a big folder image, and define the pattern of image as image_fn below. +// then run entire macro: run macro from menu bar or Cmd + R in mac, ctrl + R in other os sys I think. + +input_dir="/Users/hoatran/Documents/BCCRC_projects/merfish/XP2059_FOV25/"; + + +output_dir=input_dir+"counting_spots/"; + +if(!File.exists(output_dir)) + File.mkdir(output_dir); + +for (r=1; r<=8; r++) { + +//r=8; + + + +image_fn="merFISH_0"+r+"_025_05.TIFF"; + +open(input_dir+image_fn); +short_name = substring(image_fn,0,indexOf(image_fn,'.TIFF')); + +run("8-bit"); + +run("Enhance Contrast...", "saturated=0.2 normalize"); + +run("Convolve...", "text1=[-1 -1 -1 -1 -1\n-1 -1 -1 -1 -1\n-1 -1 24 -1 -1\n-1 -1 -1 -1 -1\n-1 -1 -1 -1 -1\n] normalize"); + +//open(input_dir+"demo/mask.tif"); + +selectWindow(image_fn); + +//imageCalculator("AND create", image_fn,"mask.tif"); + +//selectWindow("mask.tif"); + +//close(); + +//selectWindow("Result of "+image_fn); + +//selectWindow(image_fn); + +nBins = 256;   + +row = 0; + +getHistogram(values, counts, nBins); + +for (i=250; i0){ + for (i=0; i 8) {run("8-bit");} + //run("Median...", "radius=2"); // in case you see lots of noises detected as signals + run("Convolve...", "text1=[-1 -1 -1 -1 -1\n-1 -1 -1 -1 -1\n-1 -1 24 -1 -1\n-1 -1 -1 -1 -1\n-1 -1 -1 -1 -1\n] normalize"); + + + ////only signals with intensity values from 250 to 255 are considered as signals, from my observation of spots and noise in images. + ////You can use other thresholds, this macro just give an estimation, not provide accurate results for publication. + setThreshold(250, 255, "raw"); + //setThreshold(250, 255); + setOption("BlackBackground", true); + run("Convert to Mask"); + run("Grays"); + +} + +//FOV=25; +//r=1; +c=0; +for (FOV=1; FOV<=nbFOVs; FOV++) { + if(FOV<10){ // Isaac: is this the correct format for FOV? + FOV_label="0"+FOV; + }else{ + FOV_label=""+FOV; + } + for (r=1; r<=nbRounds; r++) { + print("--------------------------------------------"); + print("FOV: "+FOV_label+" round: "+r); + output_img = "total_signals_round"+r; + for (z=1; z<=nbZslices; z++) { + if(z<10){ + zslice="0"+z; + }else{ + zslice=""+z; + } + short_name = "merFISH_0"+r+"_0"+FOV_label+"_"+zslice; + image_fn=short_name+suffix; + //print(image_fn); + open(input_dir+image_fn); + //short_name = substring(image_fn,0,indexOf(image_fn, suffix)); + deconvolute_binarization_image (image_fn); + if(z==1){ + selectWindow(image_fn); + rename(output_img); + //IJ.log('First assignment: '+output_img); + }else{ + //IJ.log('Sum: '+image_fn); + imageCalculator("OR create", output_img, image_fn); + selectWindow(image_fn); + close(); + selectWindow(output_img); + close(); + selectWindow("Result of "+output_img); + rename(output_img); + + } + } + nBins = 256; + getHistogram(values, counts, nBins); + IJ.log("Number of spots: "+counts[255]); + // //Save results into a csv file + setResult("FOV", c, FOV); + setResult("imaging_round", c, r); + setResult("total_spots", c, counts[255]); + updateResults(); + c++; + selectWindow(output_img); + close(); + } +} +selectWindow("Results"); +saveAs("Results",output_dir+"spots_across_FOV_report.csv"); +selectWindow("Results"); +run("Close"); +print("Save output into the folder: "+output_dir); + +run("Close All"); + +print("Completed"); +print("----------------------------------------------------------------"); +setBatchMode(false); + + + + + + diff --git a/data/imagej_macro/counting_spots/macro_counting_metric_v3_across_rounds.txt b/data/imagej_macro/counting_spots/macro_counting_metric_v3_across_rounds.txt new file mode 100644 index 0000000000000000000000000000000000000000..6bb78c3f61d008a98fa5e4ae3f97e2c6837fd4b4 --- /dev/null +++ b/data/imagej_macro/counting_spots/macro_counting_metric_v3_across_rounds.txt @@ -0,0 +1,104 @@ +// Open this macro from ImageJ +// Change the input_dir: a directory which contain 8 images of same wavelength. +// or a big folder image, and define the pattern of image as image_fn below. +// then run entire macro: run macro from menu bar or Cmd + R in mac, ctrl + R in other os sys I think. + +// Counting pixels corresponding to spots across different rounds. + +setBatchMode(true); +print("\\Clear"); +print("Counting pixels corresponding to spots across different rounds"); +print("----------------------------------------------------------------"); +input_dir="/Users/hoatran/Documents/BCCRC_projects/merfish/XP2059_FOV25/"; +FOV=25; +z=5; +suffix=".TIFF"; +test_case = "counting_pixels_spots_FOV0"+FOV+"_z0"+z; +output_dir=input_dir+test_case+"/"; + +if(!File.exists(output_dir)) + File.mkdir(output_dir); + +print(input_dir); +print(output_dir); + + +for (r=1; r<=8; r++) { + +//r=8; + + +short_name="merFISH_0"+r+"_0"+FOV+"_0"+z; +image_fn=short_name+suffix; + +open(input_dir+image_fn); +//short_name = substring(image_fn,0,indexOf(image_fn, suffix)); + +run("8-bit"); + +run("Enhance Contrast...", "saturated=0.2 normalize"); + +run("Convolve...", "text1=[-1 -1 -1 -1 -1\n-1 -1 -1 -1 -1\n-1 -1 24 -1 -1\n-1 -1 -1 -1 -1\n-1 -1 -1 -1 -1\n] normalize"); + +//open(input_dir+"demo/mask.tif"); + +selectWindow(image_fn); + +//imageCalculator("AND create", image_fn,"mask.tif"); + +//selectWindow("mask.tif"); + +//close(); + +//selectWindow("Result of "+image_fn); + +//selectWindow(image_fn); + +nBins = 256; + + + +getHistogram(values, counts, nBins); + +nb_spots=0; + +for (i=250; i% as.data.frame() + f <- gsub(paste0('_',FOV,'_',z,'_hist.csv'),'',f) + f <- gsub(prefix,'R',f) + df$round <- f + counts <- dplyr::bind_rows(counts, df) +} +dim(counts) +head(counts) + +# Counting signals from 250 to 255 intensity values +stat <- counts %>% + dplyr::group_by(round) %>% + dplyr::summarise(Count=sum(Count)) +stat + +# Counting signals=255 intensity values only +stat_255 <- counts %>% + dplyr::filter(Value==255) %>% + dplyr::group_by(round) %>% + dplyr::summarise(Count=sum(Count)) +stat_255 + +p <- ggplot(stat, aes(x=round, y=Count)) + + geom_bar(stat="identity", fill="steelblue", width=0.4)+ + theme_minimal() + + labs(title='Counting pixels spots XP2059', x='Round',y='#pixels-spots') +p + +png(paste0(input_dir,"XP2059_spots_count.png"),height = 2*350, width=2*500,res = 2*72) +print(p) +dev.off() + diff --git a/data/imagej_macro/counting_spots/plotting_spot_counts_FOVs.R b/data/imagej_macro/counting_spots/plotting_spot_counts_FOVs.R new file mode 100644 index 0000000000000000000000000000000000000000..15d4b0628ca689def8a4b1e167971c0e914b27cd --- /dev/null +++ b/data/imagej_macro/counting_spots/plotting_spot_counts_FOVs.R @@ -0,0 +1,136 @@ + +library(ggplot2) +library(dplyr) + + +library(dplyr) +library(ggplot2) +load_spots_counts <- function(input_dir, save_dir){ + + input_dir <- '/Users/htran/Documents/storage_tmp/merfish/merfish_materials-main/quality_control_results/' + save_dir <- '/Users/htran/Documents/storage_tmp/merfish/spots_across_FOVs/' + save_dir <- paste0(save_dir, 'figs_same_scales/') + dir.create(save_dir) + fns <- list.files(input_dir) + fns <- fns[grepl('XP',fns)] + suffix <- 'spots_across_FOV_report.csv' + plot_ls <- list() + for(datatag in fns){ + xp_dir <- paste0(input_dir, datatag,'/') + supfns <- list.files(xp_dir) + supfns <- supfns[grepl(suffix,supfns)] + if(length(supfns)==2){ #2 wavelength outputs + print(datatag) + # print(supfns) + df_w1 <- data.table::fread(paste0(xp_dir,supfns[1])) + df_w1$wavelength <- substr(supfns[1], 1, 3) + df_w2 <- data.table::fread(paste0(xp_dir,supfns[2])) + df_w2$wavelength <- substr(supfns[2], 1, 3) + df <- dplyr::bind_rows(df_w1, df_w2) + print(dim(df)) + # data.table::fwrite(df, paste0(save_dir, datatag,'_pixels_spots_counts.csv')) + p <- viz_spots_across_FOVs(df, datatag, save_dir) + plot_ls[[datatag]] <- p + } + } + + + + +} +viz_spots_across_FOVs <- function(df, datatag, save_dir){ + df$imaging_round <- as.factor(df$imaging_round) + df$V1 <- NULL + df$FOV <- as.factor(df$FOV) + p1 <- ggplot(df, aes(FOV, total_spots)) + + geom_jitter(aes(colour = imaging_round), width = 0.25) + + geom_violin()+ + # geom_hline(yintercept=250000, linetype="dashed", color = "red") + + facet_grid(rows = vars(wavelength)) + #, scales="free" + guides(colour = guide_legend(override.aes = list(shape = 15, size=6))) + + theme_bw()+ + theme(axis.text.x = element_text(size=15, color="black"), + strip.text = element_text(size=15, color="black"), + legend.position ='bottom') + # p1 + png(paste0(save_dir,datatag, "_eval_spots_across_FOVs.png"), height = 2*500, width=2*1200, res = 2*72) + print(p1) + dev.off() + return(p1) +} + + + + + + + +# input_dir <- '~/Documents/storage_tmp/merfish/counting_spots_across_FOVs_dataset_XP2059/' +# +# df1 <- data.table::fread(paste0(input_dir,'counting_spots_across_FOVs_dataset_XP2059_647/spots_across_FOV_report.csv')) %>% as.data.frame() +# df2 <- data.table::fread(paste0(input_dir,'counting_spots_across_FOVs_dataset_XP2059_750/spots_across_FOV_report.csv')) %>% as.data.frame() +# +# dim(df1) +# dim(df2) +# +# df1$wavelength <- '647' +# df2$wavelength <- '750' +# df <- dplyr::bind_rows(df1, df2) +# dim(df) +# colnames(df) +# df$V1[1] +# +# data.table::fwrite(df, paste0('~/Documents/storage_tmp/merfish_XP2059/spots_counting_Hoa/pixels_spots_counts.csv')) +# df$imaging_round <- as.factor(df$imaging_round) +# df$V1 <- NULL +# df$FOV <- as.factor(df$FOV) +# p1 <- ggplot(df, aes(FOV, total_spots)) + +# geom_jitter(aes(colour = imaging_round), width = 0.25) + +# geom_violin()+ +# # geom_hline(yintercept=250000, linetype="dashed", color = "red") + +# facet_grid(rows = vars(wavelength)) + +# guides(colour = guide_legend(override.aes = list(shape = 15, size=6))) + +# theme_bw()+ +# theme(axis.text.x = element_text(size=15, color="black"), +# strip.text = element_text(size=15, color="black"), +# legend.position ='bottom') +# p1 +# +# +# stat1$FOV <- as.numeric(stat1$FOV) +# stat1$FOV <- as.factor(stat1$FOV) +# +# p2 <- ggplot(stat1, aes(FOV, nb_objects)) + +# geom_col(width = 0.3) + +# ylim(0, max(stat1$nb_objects)+5) + +# theme_bw() + +# theme(axis.text.x = element_text(size=15, color="black"), +# axis.title.y = element_text(size=16, color="black"), +# axis.text.y = element_text(size=16, color="black")) +# +# p2 +# # BiocManager::install('cowplot') +# library(cowplot) +# p2 <- cowplot::plot_grid(p2, NULL, align = 'hozirontal',nrow=1, rel_widths = c(2,0.025)) +# p <- cowplot::plot_grid(p2, p1, align = 'vertical',ncol=1, rel_heights = c(1,3), +# labels = c('Number of objects across FOV','Pixel-Spots Counting')) +# p +# png(paste0(input_dir,"Evaluate_spots_across_FOV_XP2059.png"), height = 2*900, width=2*1400, res = 2*72) +# print(p) +# dev.off() +# +# +# df <- data.table::fread('~/Documents/storage_tmp/merfish_XP2059/spots_counting_Hoa/total_cell_areas_across_FOV.csv') +# +# +# +# df$FOV <- substr(df$cell_image_name, 12,14) +# df$FOV <- as.numeric(df$FOV) +# df$cell_image_name <- NULL +# dim(df) +# df$total_foreground_area +# sum(df$V1==df$FOV) +# df$V1 <- NULL +# data.table::fwrite(df, '~/Documents/storage_tmp/merfish_XP2059/spots_counting_Hoa/total_cell_areas_across_FOV.csv') +# +# diff --git a/data/imagej_macro/nuclei_segmentation/cell_zone_results/aligned_images_fov0_z18_01_cell_zone_rad_5.0.tif b/data/imagej_macro/nuclei_segmentation/cell_zone_results/aligned_images_fov0_z18_01_cell_zone_rad_5.0.tif new file mode 100644 index 0000000000000000000000000000000000000000..3bfd561314edf40708773ac58565a1bbebc441c8 --- /dev/null +++ b/data/imagej_macro/nuclei_segmentation/cell_zone_results/aligned_images_fov0_z18_01_cell_zone_rad_5.0.tif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eb1f9c41a44eade88e13d693a3edcf31c851eb03a85d28dd659b1ac5a4b68f07 +size 5171494 diff --git a/data/imagej_macro/nuclei_segmentation/cell_zone_results/aligned_images_fov0_z18_01_cell_zone_rad_5.0.zip b/data/imagej_macro/nuclei_segmentation/cell_zone_results/aligned_images_fov0_z18_01_cell_zone_rad_5.0.zip new file mode 100644 index 0000000000000000000000000000000000000000..549214474e4863b8f04cdadfb8c730aae8410b02 --- /dev/null +++ b/data/imagej_macro/nuclei_segmentation/cell_zone_results/aligned_images_fov0_z18_01_cell_zone_rad_5.0.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e414e57ddb1ecc0b5b5e0f7139d8d7bab69b1555c1029dc01c6e88bca0037453 +size 100356 diff --git a/data/imagej_macro/nuclei_segmentation/contour_ROI_extraction.txt b/data/imagej_macro/nuclei_segmentation/contour_ROI_extraction.txt new file mode 100644 index 0000000000000000000000000000000000000000..e84a36764426fa8f93c7459a5700ab7a43fb213a --- /dev/null +++ b/data/imagej_macro/nuclei_segmentation/contour_ROI_extraction.txt @@ -0,0 +1,76 @@ +//dir=getDirectory("mouse"); +//print(dir) +setBatchMode(true); +print("___________________________________________"); + + +suffixe=".tif"; // change this setting if your image ends with .tiff + + +// get input direction from shell script command +dir = getArgument; // dir contains segmented images + +// for testing purpose, you can disable line above, and set input dir from this param +//dir = "/Users/hoatran/Documents/BCCRC_projects/merfish/merFISH_report_pipeline/imagej_macro/nuclei_segmentation/testing_images/"; + +if (dir=="") + exit ("No argument! Exit program"); + +print("Working dir: "+dir+"\n"); + + +demo_dir=File.getParent(dir)+"/demo_results/"; +if(!File.exists(demo_dir)) + File.mkdir(demo_dir); + + +print("Creating demo ROI folder: "+demo_dir+"\n"); + +files=getFileList(dir); + +print("Nb of processing images: "+files.length+"\n"); + +for(f=0;f> $log_file 2>&1 && tail $log_file + +input_dir="${project_dir}" +echo "__________________________________\n" +echo "Input directory is: \n" +echo $input_dir +echo "Segment images \n" + + +## You can change memory amount, ex: 20000m to 30000m so program will run faster. +## MacOS background mode here + +## If you have java environment jre installed in your computer +# java -Xmx20000m -jar ${imagej_exe_file} -ijpath $imagej_dir/ -batch $macro_fn $input_dir + +## Otherwise using existing jre env from Fiji here +# /Users/htran/Downloads/Fiji.app/java/macosx/adoptopenjdk-8.jdk/jre/Contents/Home/bin/java -Xmx20000m -jar ${imagej_dir}Contents/Java/ij.jar -ijpath ${imagej_dir} -batch $macro_fn $input_dir +# ${imagej_dir}java/macosx/adoptopenjdk-8.jdk/jre/Contents/Home/bin/java -Xmx20000m -jar ${imagej_exe_file} -ijpath ${imagej_dir} -batch $macro_fn ${input_dir} + +## MacOS mode +${imagej_dir}jre/bin/java -Xmx20000m -jar $imagej_exe_file -ijpath $imagej_dir -batch $macro_fn $input_dir + + +## Linux background mode here, using xvfb-run in case you run in server (graphical env), in local computer, java command is enough +# xvfb-run -a java -Xmx15000m -jar $imagej_dir/ij.jar -ijpath $imagej_dir/ -batch $macro_fn $input_dir + +## In Linux local computer, java command is sufficient +# java -Xmx15000m -jar $imagej_dir/ij.jar -ijpath $imagej_dir/ -batch $macro_fn $input_dir + +echo "Nucleus Segmentation Completed!" +echo "__________________________________\n" + + + + + diff --git a/data/imagej_macro/nuclei_segmentation/nuc_seg.txt b/data/imagej_macro/nuclei_segmentation/nuc_seg.txt new file mode 100644 index 0000000000000000000000000000000000000000..e3310680665934a45789e34ffdff4d5c6946b1c2 --- /dev/null +++ b/data/imagej_macro/nuclei_segmentation/nuc_seg.txt @@ -0,0 +1,144 @@ +//dir=getDirectory("mouse"); +//print(dir) +setBatchMode(true); +print("___________________________________________"); + +// SEGMENTATION PARAMETERS +minSize=23; // minimum diameter +maxSize=41; // maximum diameter +// CELL ZONE DETECTION PARAMETERS +radius_max_cell_zone_extension=5; // from border of nucleus, extend into space with this radius + +suffixe=".tif"; // change this setting if your image ends with .tiff + + +background_threshold=50; // [0,255] intensity value range, if no pixel value higher than this threshold means background objects, skip all functions. + +// get input direction from shell script command +dir = getArgument; + +// for testing purpose, you can disable line above, and set input dir from this param +//dir = "/Users/hoatran/Documents/BCCRC_projects/merfish/merFISH_report_pipeline/imagej_macro/nuclei_segmentation/testing_images/"; + +if (dir=="") + exit ("No argument! Exit program"); + +print("Working dir: "+dir+"\n"); + +seg_dir=File.getParent(dir)+"/seg_results/"; +if(!File.exists(seg_dir)) + File.mkdir(seg_dir); + +demo_dir=File.getParent(dir)+"/demo_results/"; +if(!File.exists(demo_dir)) + File.mkdir(demo_dir); + +cell_zone_dir=File.getParent(dir)+"/cell_zone_results/"; +if(!File.exists(cell_zone_dir)) + File.mkdir(cell_zone_dir); + + +print("Creating segmentation folder: "+seg_dir+"\n"); + +files=getFileList(dir); + +//print("Nb of processing images: "+files.length+"\n"); + +for(f=0;f 8) {run("8-bit");} + getStatistics(area, mean, min, max, std); + print(getTitle+": max: "+max+" min: "+min+" mean: "+mean+" area: "+area+" std:"+std); + if(max 8) {run("8-bit");} + //run("Find Maxima..."); + setOption("ScaleConversions", true); + run("Find Maxima...", "prominence=10 output=List"); + selectWindow("Results"); + saveAs("Results",output_dir+short_name_img+"_centroids.csv"); + selectWindow("Results"); + run("Close"); + //print("Save output into the folder: "+results_dir); + run("Close All"); + +} + + +files=getFileList(input_dir); + +//print("Nb of processing images: "+files.length+"\n"); + +for(f=0;f% left_join(ndist, by='fb_idx') + + nidx_stat1 <- nidx_stat %>% + dplyr::filter(nearest_neighbour!=0) # can not find the neighbour with this radius + + nidx_stat2 <- nidx_stat %>% + dplyr::filter(eu_dist==0) # can not find the neighbour with this radius + + total_stat <- tibble::tibble(datatag=datatag, + roundSt=tag, pct_exact_match=round(100 * dim(nidx_stat2)[1]/dim(df2)[1],1), + pct_approx_match=round(100 * dim(nidx_stat1)[1]/dim(df2)[1],1), + avg_error_rate=round(mean(nidx_stat1$eu_dist),3)) + return(total_stat) + +} +viz_error_registration <- function(df){ + df$roundSt <- as.numeric(df$roundSt) + # df <- df[gtools::mixedorder(df$roundSt),] + # gtools::mixedorder(c('1','10','2')) + df_plt <- df %>% + dplyr::select(-avg_error_rate) + stat <- df_plt %>% + dplyr::group_by(datatag) %>% + dplyr::summarise(pct_approx_match_stat=round(mean(pct_approx_match),1)) + df_plt <- df_plt %>% left_join(stat, by='datatag') + df_plt$datatag <- paste0(df_plt$datatag,' ',df_plt$pct_approx_match_stat,'%') + df_plt <- df_plt %>% + dplyr::select(-pct_approx_match_stat) %>% + tidyr::pivot_longer(cols = starts_with('pct_'), + names_to = 'match_type', values_to='pct_match') + + # Grouped + p_pct <- ggplot(df_plt, aes(fill=match_type, y=pct_match, x=roundSt)) + + geom_bar(position="dodge", stat="identity", width=0.4) + + facet_wrap(~datatag, ncol = 3) + + theme_bw() + + scale_x_continuous(name="Round", breaks=rep(2:16,1))+ + theme(axis.text = element_text(size=12), + strip.text = element_text(size=13, face = 'bold'), + strip.background = element_rect(fill = 'white', colour = 'white'), + panel.grid.major = element_blank(), + panel.grid.minor = element_blank(), + legend.position = 'bottom') + # df$roundSt <- as.factor(df$roundSt) + + df_plt1 <- df + stat1 <- df_plt1 %>% + dplyr::group_by(datatag) %>% + dplyr::summarise(avg_error_rate_stat=round(mean(avg_error_rate),3)) + df_plt1 <- df_plt1 %>% left_join(stat1, by='datatag') + df_plt1$datatag <- paste0(df_plt1$datatag,': ',df_plt1$avg_error_rate_stat,' ') + + + p_dist <- ggplot(df_plt1, aes(x=roundSt, y= avg_error_rate, fill=as.factor(roundSt))) + + geom_bar(stat="identity", width=0.4) + + facet_wrap(~datatag, ncol = 3) + + theme_bw() + + scale_x_continuous(name="Round", breaks=rep(2:16,1))+ + theme(axis.text = element_text(size=12), + strip.text = element_text(size=13, face = 'bold'), + strip.background = element_rect(fill = 'white', colour = 'white'), + panel.grid.major = element_blank(), + panel.grid.minor = element_blank(), + legend.position = 'bottom') + return(list(p_pct=p_pct, p_dist=p_dist)) + +} + +base_dir <- '/Users/hoatran/Documents/BCCRC_projects/merfish/evaluate_registration/Aligned_fiducial_images/' + +series <- c("XP2059","XP4516","XP2504","XP2457","XP2453") + +input_dir <- paste0(base_dir,'results/') +fns <- list.files(input_dir) +fns <- fns[grepl('.csv', fns)] +length(fns) + +tags <- sapply(strsplit(fns,'_'), function(x){ + return(x[1]) +}) +fovs <- sapply(strsplit(fns,'_'), function(x){ + return(x[2]) +}) +rounds <- sapply(strsplit(fns,'_'), function(x){ + return(x[3]) +}) + +metadata <- data.frame(datatag=as.character(tags), + fov=as.character(fovs), + roundSt=gsub('.csv','',as.character(rounds)), + fn=fns) +head(metadata) +data.table::fwrite(metadata, paste0(base_dir, 'metadata_all_files.csv.gz')) +rownames(metadata) <- metadata$fn +ref_round <- '1' +summary_total <- tibble::tibble() +for(fn in fns){ + + if(metadata[fn,'roundSt']!='1'){ + df_ref <- data.table::fread(paste0(input_dir, metadata[fn,'datatag'],'_' + ,metadata[fn,'fov'],'_',ref_round,'.csv')) %>% as.data.frame() + df_aligned <- data.table::fread(paste0(input_dir, fn)) %>% as.data.frame() + df_ref$V1 <- NULL + df_aligned$V1 <- NULL + stat <- get_neighbour_stat(df_ref, df_aligned, + tag=metadata[fn,'roundSt'], + datatag=paste0(metadata[fn,'datatag'],'_',metadata[fn,'fov'])) + summary_total <- dplyr::bind_rows(summary_total, stat) + + } + +} +dim(df_ref) +dim(df_aligned) +metadata1 <- metadata %>% + dplyr::filter(datatag=='XP2504' & fov=='FOV26') +fn <- 'XP2504_FOV26_4.csv' +dim(summary_total) +summary_total$roundSt[1:3] +data.table::fwrite(summary_total, paste0(base_dir, 'summary_mapping_from_rounds_to_R1.csv.gz')) +colnames(summary_total) +plt_ls <- viz_error_registration(summary_total) + + +png(paste0(base_dir,"Evaluate_registration_matching.png"), + height = 2*450, width=2*900, res = 2*72) +print(plt_ls$p_pct) +dev.off() + +png(paste0(base_dir,"Evaluate_registration_error_rates.png"), + height = 2*450, width=2*900, res = 2*72) +print(plt_ls$p_dist) +dev.off() \ No newline at end of file diff --git a/data/imagej_macro/registration_evaluation/registration_evaluation_v2.txt b/data/imagej_macro/registration_evaluation/registration_evaluation_v2.txt new file mode 100644 index 0000000000000000000000000000000000000000..832121812de07bab1bea811830fa49e6a60aaff6 --- /dev/null +++ b/data/imagej_macro/registration_evaluation/registration_evaluation_v2.txt @@ -0,0 +1,100 @@ + + + +setBatchMode(true); +print("\\Clear"); + +print("-----------------Parameter Setting---------------------------"); +base_dir="/Users/hoatran/Documents/BCCRC_projects/merfish/evaluate_registration/Aligned_fiducial_images/"; + +//datatag="XP2059"; +//datatag="XP4516"; +datatag="XP2504"; +//datatag="XP2457"; +//datatag="XP2453"; + +input_dir=base_dir+datatag+"/"; + +suffix=".tif"; +output_dir=base_dir+"results/"; + +if(!File.exists(output_dir)) + File.mkdir(output_dir); + +print(input_dir); +print(output_dir); + +files=getFileList(input_dir); + +//print("Nb of processing images: "+files.length+"\n"); + +for(f=0;f 8) {run("8-bit");} + //run("Find Maxima..."); + //setOption("ScaleConversions", true); + run("Find Maxima...", "prominence=10 output=List"); + selectWindow("Results"); + saveAs("Results",output_dir+short_name_img+"_"+n+".csv"); + selectWindow("Results"); + run("Close"); + + } + selectWindow(image_fn); + run("Close"); + + } + } + +} + + +print("Completed"); + +print("----------------------------------------------------------------"); +setBatchMode(false); + + + +image_fn="XP2504_FOV52.tif"; + + +suffixe=".tif"; + base_dir="/Users/hoatran/Documents/BCCRC_projects/merfish/evaluate_registration/Aligned_fiducial_images/"; + output_dir=base_dir+"results/"; + short_name_img = substring(image_fn,0,lastIndexOf(image_fn,suffixe)); +for (n=1; n<=1; n++) { + + +if(n<10){ +prefix_fn="0"+n; +}else{ +prefix_fn=""+n; +} +selectWindow("XP2504_FOV52-00"+prefix_fn); + run("Gaussian Blur...", "sigma=2"); + run("Convolve...", "text1=[-1 -1 -1 -1 -1\n-1 -1 -1 -1 -1\n-1 -1 24 -1 -1\n-1 -1 -1 -1 -1\n-1 -1 -1 -1 -1\n] normalize"); + if (bitDepth > 8) {run("8-bit");} + //run("Find Maxima..."); + setOption("ScaleConversions", true); + run("Find Maxima...", "prominence=10 output=List"); + selectWindow("Results"); + saveAs("Results",output_dir+short_name_img+"_"+n+".csv"); + selectWindow("Results"); + run("Close"); +selectWindow("XP2504_FOV52-00"+prefix_fn); + run("Close"); + +} + diff --git a/data/imagej_macro/resize_images/resize_images_macro.ijm b/data/imagej_macro/resize_images/resize_images_macro.ijm new file mode 100644 index 0000000000000000000000000000000000000000..62fe1c56d54d3f7b91d292b126eff20ceded52da --- /dev/null +++ b/data/imagej_macro/resize_images/resize_images_macro.ijm @@ -0,0 +1,65 @@ + + + + +setBatchMode(true); +print("\\Clear"); +print("Zipping func"); +print("Noted: just for observation, can not use for other purposes, data will slightly change if you convert image into 8 bits"); +print("----------------------------------------------------------------"); + + +print("-----------------Parameter Setting---------------------------"); +input_dir="/Users/htran/Documents/storage_tmp/merfish_XP2059/wavelength647/"; +output_dir=File.getParent(input_dir)+"/"+File.getName(input_dir)+"_zip_format/"; +rescale_ratio=0.25; +suffix=".TIFF"; + + + +if(!File.exists(output_dir)) + File.mkdir(output_dir); + +print(input_dir); +print(output_dir); + + +start = getTime(); + +files=getFileList(input_dir); + +//print("Nb of processing images: "+files.length+"\n"); + +for(f=0;f 8) {run("8-bit");} +// run("Scale...", "x=0.25 y=0.25 width=161 height=161 interpolation=Bilinear average create"); + wd=round(getWidth()*rescale_ratio); + ht=round(getHeight()*rescale_ratio); + run("Scale...", "x="+rescale_ratio+" y="+rescale_ratio+" width="+wd+" "+"height="+ht+" interpolation=Bilinear average create"); + saveAs("ZIP", output_dir+short_name+".zip"); + close(); + + } + } +} +run("Close All"); +print("Time of execution is: "+(getTime()-start)/1000+" seconds"); +print("Save output into folder: "+output_dir); +print("Completed"); +print("----------------------------------------------------------------"); +setBatchMode(false); + diff --git a/data/imagej_macro/viz_deconvolution_img.zip b/data/imagej_macro/viz_deconvolution_img.zip new file mode 100644 index 0000000000000000000000000000000000000000..26a85d4af26899f5c1cbf8004c837f7e4ccd5bc0 --- /dev/null +++ b/data/imagej_macro/viz_deconvolution_img.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d3436cf5dfbd37b76b73c280a11386c2a109f4ad072a80a789a91b93e14792a4 +size 770594 diff --git a/data/makereports.py b/data/makereports.py new file mode 100644 index 0000000000000000000000000000000000000000..e77317671536599778213a639c84b78ac7947c8d --- /dev/null +++ b/data/makereports.py @@ -0,0 +1,132 @@ +from reports.BrightnessReport import BrightnessReport +from reports.DecodabilityReport import DecodabilityReport +from reports.MaskedBrightnessReport import MaskedBrightnessReport +from reports.FocusReport import FocusReport +import numpy as np +import matplotlib.pyplot as plt +from matplotlib.backends.backend_pdf import PdfPages + +import pandas as pd + + +# Brightness report worker------- +def generate_brightness_reports(image_stack_file,coord_info,out_file,fov,z): + #This was necessary to prototype on OSX...consider removing in the future after testing + import multiprocessing + job = multiprocessing.Process(target=brightness_worker,args=(image_stack_file,coord_info,out_file,fov,z)) + job.start() + + #brightness_worker(image_stack_file,coord_info,out_file,fov,fovs) + +def brightness_worker(image_stack_file,coord_info,out_file,fov,z): + br = BrightnessReport(image_stack_file,coord_info,fov,z) + br.set_pdf(PdfPages(filename=out_file)) + + br.preview_images() + br.brightness_infov_z() + br.brightness_on_images() + br.contrast_heatmap() + br.closePdf() + +# Masked Brightness report worker------- +def generate_masked_brightness_reports(image_stack_file,coord_info,out_file,fov,z,mask_stack): + #This was necessary to prototype on OSX...consider removing in the future after testing + import multiprocessing + job = multiprocessing.Process(target=masked_brightness_worker,args=(image_stack_file,mask_stack,coord_info,out_file,fov,z)) + job.start() + +def masked_brightness_worker(image_stack_file,mask_stack,coord_info,out_file,fov,z): + mbr = MaskedBrightnessReport(image_stack_file,mask_stack,coord_info,fov,z) + mbr.set_pdf(PdfPages(filename=out_file)) + + mbr.preview_images() + mbr.brightness_infov_z() + mbr.brightness_on_images() + mbr.contrast_heatmap() + mbr.closePdf() + + +# Decodability Report worker -------- +def generate_decodability_reports(image_stack_file,coord_info,out_file,codebook_file,data_org_file,fov,z,out_detection_stats,): + #This was necessary to prototype on OSX...consider removing in the future after testing + import multiprocessing + job = multiprocessing.Process(target=decodability_worker,args=(image_stack_file,coord_info,out_file,codebook_file,data_org_file,fov,z,out_detection_stats)) + job.start() + +def decodability_worker(image_stack_file,coord_info,out_file,codebook_file,data_org_file,fov,z,out_detection_stats): + dr = DecodabilityReport(image_stack_file,coord_info,codebook_file,data_org_file,fov,z,out_detection_stats) + dr.set_pdf(PdfPages(filename=out_file)) + + dr.make_bit_imgs() + dr.make_decodability_hists() + dr.closePdf() + + +# Focus report worker------- +def generate_focus_reports(image_stack_file,coord_info,out_file,out_csv,fov): + #This was necessary to prototype on OSX...consider removing in the future after testing + import multiprocessing + job = multiprocessing.Process(target=focus_worker,args=(image_stack_file,coord_info,out_file,out_csv,fov)) + job.start() + # focus_worker(image_stack_file,coord_info,out_file,out_csv,fov,fovs) + + +def focus_worker(image_stack_file,coord_info,out_file,out_csv,fov): + fr = FocusReport(image_stack_file,coord_info,fov,out_csv) + fr.set_pdf(PdfPages(filename=out_file)) + fr.f_measure_report() + fr.closePdf() + +# Compile reports---------------- + +def compile_focus_report(file_list:list,output,irs,wvs): + + full_df = pd.DataFrame() + for fl in file_list: + test = pd.read_csv(fl) + full_df = full_df.append(test,ignore_index=True) + + full_df.to_csv(output) + if not isinstance(irs,list): + irs = list(irs) + report_pdf = PdfPages(filename = output) + + + compiled_matrix = np.zeros(( + len(file_list), # length of fovs + len(wvs), + len(irs) + )) + + for iir, ir in enumerate(irs):#for each ir + + for iwv, wv in enumerate(wvs):#for each wv + data = full_df[["FOV",str(wv)]][(full_df["IR"]==int(ir))] #extract the FOVs...assume stuff is ordered + + data = data.to_numpy() # FOV x 2 + + compiled_matrix[:,iwv,iir] = data[:,1] #this is the z + + #ax[iir].plot("FOV",str(wv),data=data) + #x:FOV y:z spy:IR + f,ax = plt.subplots(nrows = len(wvs),ncols = 1,sharex=True,sharey=True,figsize=(8,len(irs)*4)) + + if not isinstance(ax,np.ndarray): + ax = np.array(ax) + + for iwv, wv in enumerate(wvs):#for each wv + ax[iwv].imshow(compiled_matrix[:,iwv,:]) + ax[iwv].set_xticks(np.arange(len(irs)), irs) + ax[iwv].set_yticks(np.arange(len(file_list)), np.arange(len(file_list))) + ax[iwv].set_ylabel("FOVS ") + ax[iwv].set_xlabel("Imaging Round") + plt.setp(ax[iwv].get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") + + for iir in range(len(irs)): + for ifl in range(len(file_list)): + text = ax[iwv].text(iir, ifl, int(compiled_matrix[ifl,iwv, iir]), ha="center", va="center", color="w") + ax[iwv].set_title(f"Wavelength: {wv} nm") + + + report_pdf.savefig() + report_pdf.close() diff --git a/data/merfish_barcode/LICENSE b/data/merfish_barcode/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f288702d2fa16d3cdf0035b15a9fcbc552cd88e7 --- /dev/null +++ b/data/merfish_barcode/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/data/merfish_barcode/environment.yml b/data/merfish_barcode/environment.yml new file mode 100644 index 0000000000000000000000000000000000000000..a273bda34ba2a24f077722b559a81ca8c6ea52b6 --- /dev/null +++ b/data/merfish_barcode/environment.yml @@ -0,0 +1,13 @@ +name: barcode_env +channels: + - conda-forge + - defaults +dependencies: + - opencv + - scikit-image + - python=3.7 + - matplotlib + - numpy + - click + - pip: + - reliability diff --git a/data/merfish_barcode/main.py b/data/merfish_barcode/main.py new file mode 100644 index 0000000000000000000000000000000000000000..43e109b50444eb3d62c0296b0688b5f2330303bf --- /dev/null +++ b/data/merfish_barcode/main.py @@ -0,0 +1,173 @@ +import matplotlib.pyplot as plt +import numpy as np +import skimage.io as skio +from glob import glob +import click +import os +from skimage import registration +import scipy.ndimage as ndi +from skimage.exposure import equalize_adapthist +import re +import cv2 +from reliability.Other_functions import crosshairs + +@click.group() +def cli(): + pass + +refPt = [] +@cli.command('makeBarcodeWithBead') +@click.argument('img647_dir',type=click.Path(exists=True)) +@click.argument('img750_dir',type=click.Path(exists=True)) +@click.argument('bead_dir',type=click.Path(exists=True)) +@click.option('--n_ref',default=0,type=int,help='The index of the file that will be used as datum for image registration (Default: 0)') +@click.option('--pattern',default=None,type=str,help='The glob pattern to be used for file extraction (Default: "*.TIFF")') +@click.option('--circle_size',default=15,type=int,help='The approximate diameter of a probe (Default: 15)') +@click.option('--thresh',default=0.995,type=float,help='Local percentile for intensity extraction (Default: 0.995)') +@click.option('--window_size',default=100,type=int,help='Size of the window used for local percentile extraction (Default: 100)') +@click.option('--img_scale',default=1.0,type=float,help='Multiplier for image values to make it viewable (Default: 1)') +def makeBarcodeWithBead(img647_dir:str,img750_dir:str,bead_dir:str,n_ref:int,pattern:str,circle_size:int,thresh:float,window_size:int,img_scale:float): + + + + + global refPt + if pattern is None: + pattern = "*.TIFF" + pattern647 = os.path.join(img647_dir,pattern) + pattern750 = os.path.join(img750_dir,pattern) + file_list_647 = glob(pattern647) + file_list_750 = glob(pattern750) + + file_list_647.sort(key=lambda f: int(re.sub('\D', '', f))) + file_list_750.sort(key=lambda f: int(re.sub('\D', '', f))) + + bead_dir_pattern = os.path.join(bead_dir,pattern) + bead_file_list = glob(bead_dir_pattern) + bead_file_list.sort(key=lambda f: int(re.sub('\D', '', f))) + + #Register the beads + bead_imgs = dict() + for idx,fn in enumerate(bead_file_list): + img = skio.imread(fn) + bead_imgs[idx]=img + #load images + imgs = dict() + file_list = file_list_647+file_list_750 + for idx,fn in enumerate(file_list): + + _img = skio.imread(fn) + + imgs[idx]=equalize_adapthist(_img, clip_limit=0.03) + + + for idx in range(1,len(bead_imgs)): + shift,_,_ = registration.phase_cross_correlation(bead_imgs[n_ref],bead_imgs[idx]) + + imgs[idx] = ndi.shift(imgs[idx],shift) + + + #Window size + window_Size =window_size + + ref_img = imgs[n_ref] + ref_img = ref_img*img_scale + + fig,ax = plt.subplots(num=1) + cid = fig.canvas.mpl_connect('button_release_event', recordClickLoc_mpl) + ax.imshow(ref_img,cmap='gray') + crosshairs() + plt.show() + while True: + + if len(refPt)<2: + if not plt.fignum_exists(num=1): + fig,ax = plt.subplots(num=1) + cid = fig.canvas.mpl_connect('button_release_event', recordClickLoc_mpl) + ax.imshow(ref_img,cmap='gray') + crosshairs() + plt.show() + continue + else: + print('Accepted') + print(refPt) + break + + #load and register all the images based on the bead registration + + + #Draw a circle of a certain radius in the image + img_circle = dict() + + n_cols = 3 + n_rows = int(np.ceil(len(imgs)/n_cols)) + plt.rcParams.update({'font.size': 22}) + f,ax = plt.subplots(n_rows,n_cols,figsize=(20,20),dpi=200) + ax = ax.flatten() + + for idx in range(len(imgs)): + img = imgs[idx] + spot_thresh = calcSpotThresh(img,thresh_percent=thresh) + canvas = np.zeros((img.shape[0],img.shape[1],3)) + circle_mask = cv2.circle(canvas,tuple(refPt),circle_size//2,(1,1,1),-1) + circle_test = circleTest(img,circle_mask,spot_thresh) + img_circle[idx] = centreCrop(cv2.circle(img,tuple(refPt),circle_size//2,(0,255,255),1), + refPt, + window_Size) + ax[idx].imshow(img_circle[idx]*img_scale,vmin=0,cmap='gray')#,vmax=np.max(img[idx]),) + ax[idx].axis('off') + ax[idx].set_title(circle_test) + plt.tight_layout() + + plt.savefig('./barcode_bead_example.png') + + + + + + +def recordClickLoc_mpl(event): + global refPt + refPt=[int(event.xdata),int(event.ydata)] + +def centreCrop(img,centrePt,window_size): + h=window_size//2 + + + y = np.maximum(centrePt[1] - h,0) + x = np.maximum(centrePt[0] - h,0) + + crop_img = img[int(y):int(y+window_size), int(x):int(x+window_size)] + return crop_img + +def circleTest(img,circle_mask, thresh): + res = np.multiply(img[:,:,np.newaxis].copy(),circle_mask)[:,:] + test = res[res>thresh].sum() + if test>0: + return 1 + else: + return 0 + +def calcSpotThresh(img:np.ndarray,thresh_percent:float = 0.9)->float: + _img = img[:,:].flatten() + + sorted_img = np.sort(_img) + + idx = np.floor(thresh_percent*sorted_img.size).astype(int) + + _thresh = sorted_img[idx] + + return _thresh + #create histogram of the image + #find the threshpercentile. i.e. sort the list, and then find the thresh_percent*len(list) + +if __name__=='__main__': + cli() + + # img647_dir = '/Volumes/shahidsWORK/647nm, Raw' + + # img750_dir = '/Volumes/shahidsWORK/750nm, Raw' + + # beads_dir = '/Volumes/shahidsWORK/561nm, Raw' + + # makeBarcodeWithBead(img647_dir,img750_dir,beads_dir,n_ref=0,pattern="merFISH_*_002_01.TIFF",circle_size=9,thresh=0.995,window_size=50,img_scale=1) diff --git a/data/napari_merfish/LICENSE b/data/napari_merfish/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f288702d2fa16d3cdf0035b15a9fcbc552cd88e7 --- /dev/null +++ b/data/napari_merfish/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/data/napari_merfish/barcode_viewer.ui b/data/napari_merfish/barcode_viewer.ui new file mode 100644 index 0000000000000000000000000000000000000000..c4a59b516c67339acecbe9eee96d7fa3669e4121 --- /dev/null +++ b/data/napari_merfish/barcode_viewer.ui @@ -0,0 +1,93 @@ + + + MainWindow + + + + 0 + 0 + 381 + 312 + + + + MainWindow + + + + + + 20 + 20 + 321 + 121 + + + + + + + + + Gene Name + + + + + + + + + + + + + + + + + + Barcode + + + + + + + + + + + + + + + + + + 20 + 160 + 100 + 32 + + + + Make Layer + + + + + + + 0 + 0 + 381 + 22 + + + + + + + + diff --git a/data/napari_merfish/config.json b/data/napari_merfish/config.json new file mode 100644 index 0000000000000000000000000000000000000000..bde3729a3fdc0fba84580e6990b674636518f4f8 --- /dev/null +++ b/data/napari_merfish/config.json @@ -0,0 +1,12 @@ +{ + "raw_data_dir": "/Volumes/MERFISH_COLD/XP1678 20220309 ONI merfish/", + "analysis_dir": "/Volumes/MERFISH_COLD/XP1678 20220309 ONI merfish/Analysis", + "stage2pix_scaling":0.116999998688698, + "stage2z_scaling":1, + "decoded_img":true, + "ir_upper":9, + "z_lower":1, + "z_upper":10, + "file_pattern": "merFISH_{{ir:02d}}_{fov}_*.tiff", + "codebook_name":"C1E1_codebook_shahid.csv" +} diff --git a/data/napari_merfish/environment.yaml b/data/napari_merfish/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9670eafbf3189adb3f92915abc3aef3072a827a8 --- /dev/null +++ b/data/napari_merfish/environment.yaml @@ -0,0 +1,12 @@ +name: conda +channels: + - defaults +dependencies: + - python=3.8 + - click + - pandas + - openpyxl + - dask-image + - pip + - pip: + - napari[all] diff --git a/data/napari_merfish/main.py b/data/napari_merfish/main.py new file mode 100644 index 0000000000000000000000000000000000000000..041b7616953aa02f58003a031894dfbe39a4027a --- /dev/null +++ b/data/napari_merfish/main.py @@ -0,0 +1,221 @@ +from magicgui import magicgui +import napari +import skimage.io as skio +import scipy.ndimage as ndi +import numpy as np +import pandas as pd +from dask_image.imread import imread +from dask_image.ndfourier import fourier_shift +import dask.array as da +from dask.array.image import imread as daimread +from dask import delayed +import json +import os +import functools +import pandas as pd +import matplotlib.pyplot as plt +from napari.types import ImageData, PointsData +import widgets +from magicgui import magicgui +import functools + +def gene_mask(arr,g): + v = da.equal(arr,g) + return v + +def dask_reshape(arr,gmax): + + gene_map = [gene_mask(arr-1,g) for g in range(gmax)] + x=da.stack(1*gene_map,axis=0) + return x + +def getTLBF(df:pd.DataFrame,im_shape): + # TODO: THIS NEEDS TO BE CHANGED WITH THE NEW CSV FORMAT + shift_r = [0] + shift_r.extend(df['shift_y'].to_list()) + shift_c = [0] + shift_c.extend(df['shift_x'].to_list()) + + dx_tl = np.max(np.maximum(shift_c,0)) + dy_tl = np.max(np.maximum(shift_r,0)) + + dx_br = np.min(np.minimum(shift_c,0)) + dy_br = np.min(np.minimum(shift_r,0)) + + tl = np.ceil([dy_tl,dx_tl]).astype(int) + br = np.floor([im_shape[0]+dy_br,im_shape[1]+dx_br]).astype(int) + return shift_r,shift_c,tl, br,dx_tl,dy_tl + +def load_img_and_shift(fn,shift,tl,br): + _img = skio.imread(fn) + #just perform the shift and then trim + + shifted_img = ndi.shift(_img,shift) + + cropped_img = shifted_img#[tl[0]:br[0],tl[1]:br[1]] + + return cropped_img + +if __name__=="__main__": + config = json.load(open('config.json')) + ir_upper=config["ir_upper"] #Has to 9 or less + raw_data_dir = config["raw_data_dir"] + analysis_dir = config["analysis_dir"] + stagepos_file = os.path.join(raw_data_dir,'stagePos_Round#1.xlsx') + + if os.path.isfile(stagepos_file): + stage = pd.read_excel(stagepos_file) + else: + stagepos_file = os.path.join(raw_data_dir,'stage_position_1.csv') + stage = pd.read_csv(stagepos_file) + + + z_lower = config["z_lower"] + z_num = config["z_upper"]#len(stage.columns)-5 + _fovs = [i for i in range(1,len(stage))] + fovs = list(map(lambda x: f'{x:03d}',_fovs)) + if 'Var1_ 1' in stage.columns: #Backwards compatability with old stagepos files + x_loc = stage['Var1_ 5'] + y_loc = stage['Var1_ 4'] + z_spacing = np.abs(stage['Var1_ 6'][0]-stage['Var1_ 7'][0]) + elif 'x_pos' in stage.columns: + x_loc = stage['y_pos'] + y_loc = stage['x_pos'] + z_spacing = np.abs(stage['z_slice_0'][0]-stage['z_slice_1'][0]) + else: + x_loc = stage['stage_pos_y'] + y_loc = stage['stage_pos_x'] + z_spacing = np.abs(stage['z_position_1'][0]-stage['z_position_2'][0]) + + x_loc = x_loc-x_loc.iloc[0] + y_loc = y_loc-y_loc.iloc[0] + + stage2pix_scaling=config["stage2pix_scaling"] # nikon/pix + stage2z_scaling = config["stage2pix_scaling"] #nikon/z + + viewer = napari.Viewer() + for idx,fov in enumerate(fovs): + shift_r=np.full((ir_upper,1),0) + shift_c=np.full((ir_upper,1),0) + tl,br = 0,0 + pattern_img = config["file_pattern"].format(fov=fov) + image_root = f'/decoding/decoded_images/decoded_{fov}'+'_{:02d}.npy' + alignment_root = f'/aligned/shift_{fov}.csv' + + if config["decoded_img"]: + shift_name =analysis_dir+alignment_root + + codebook_name = os.path.join(config["raw_data_dir"],config["codebook_name"]) + codebook_df = pd.read_csv(codebook_name,skiprows=3) + codebook_df=codebook_df.rename(columns={c:c.strip() for c in codebook_df.columns},errors='raise') + name =analysis_dir+image_root.format(z_lower) + if not os.path.isfile(name): + print(f"{name} does not exist") + continue + sample = np.load(name) + if os.path.isfile(shift_name): + df= pd.read_csv(shift_name) + shift_r,shift_c,tl, br, dx_tl,dy_tl= getTLBF(df,sample.shape) + num_genes = sample.max() + + lazy_npload = delayed(np.load) + lazy_reshapefn = delayed(dask_reshape) + _zs = np.arange(z_lower,z_num+1) + lazy_decodes = [lazy_npload(analysis_dir+image_root.format(z)) for z in _zs] + + dask_arrays = [ + da.from_delayed(delayed_reader, shape=sample.shape, dtype=sample.dtype) + for delayed_reader in lazy_decodes + ] + lazy_reshapes = [lazy_reshapefn(da,num_genes) for da in dask_arrays] + dask_arrays = [ + da.from_delayed(lr, shape=(num_genes,*sample.shape), dtype=sample.dtype) + for lr in lazy_reshapes + ] + + stack = da.stack(dask_arrays, axis=0) + + stack = da.broadcast_to(stack,(1,stack.shape[0],stack.shape[1],stack.shape[2],stack.shape[3])) + stack = da.transpose(stack,[2,0,1,3,4]) + #add decoded image + + viewer.add_image(stack,translate=(x_loc.iloc[idx]/stage2pix_scaling,-y_loc[idx]/stage2pix_scaling),name=f'decoded',scale=[1,1,z_spacing/stage2z_scaling,-1,1],blending='additive') + + #add 473 volume + channel = 473 + channel_format = f'{channel}nm, Raw/' + irs = [imread(raw_data_dir + channel_format + pattern_img.format(ir=ir)) for ir in range(1,ir_upper)] + stack = da.stack(irs) + viewer.add_image(stack, + translate=((x_loc[idx])/stage2pix_scaling, + (-y_loc[idx])/stage2pix_scaling), + name=f'fov:{fov}, {channel}nm volume', + opacity=0.5, + scale=[1,z_spacing/stage2z_scaling,-1,1], + contrast_limits=[0,2**16]) + #add 561 volume + channel = 561 + channel_format = f'{channel}nm, Raw/' + irs = [ + daimread(raw_data_dir + channel_format + pattern_img.format(ir=ir),functools.partial(load_img_and_shift, + shift = (shift_r[ir-1],shift_c[ir-1]),tl=tl,br=br + ) + ) + for ir in range(1,ir_upper) + ] + # irs = [imread(raw_data_dir + channel_format + pattern_img.format(ir)) for ir in range(1,ir_upper)] + stack = da.stack(irs) + viewer.add_image(stack, + translate=( + x_loc.iloc[idx]/stage2pix_scaling, + -y_loc[idx]/stage2pix_scaling), + name=f'fov:{fov}, {channel}nm volume', + opacity=0.5, + scale=[1,z_spacing/stage2z_scaling,-1,1], + contrast_limits=[0,2**16]) + #add 647 volume + channel = 647 + channel_format = f'{channel}nm, Raw/' + irs = [ + daimread(raw_data_dir + channel_format + pattern_img.format(ir=ir),functools.partial(load_img_and_shift, + shift = (shift_r[ir-1],shift_c[ir-1]),tl=tl,br=br + ) + ) + for ir in range(1,ir_upper) + ] + stack = da.stack(irs) + viewer.add_image(stack, + translate=(x_loc.iloc[idx]/stage2pix_scaling,-y_loc[idx]/stage2pix_scaling), + name=f'fov:{fov}, {channel}nm volume', + opacity=0.5, + scale=[1,z_spacing/stage2z_scaling,-1,1], + contrast_limits=[0,2**16], + colormap='yellow') + #add 750 volume + channel = 750 + channel_format = f'{channel}nm, Raw/' + irs = [ + daimread(raw_data_dir + channel_format + pattern_img.format(ir=ir),functools.partial(load_img_and_shift, + shift = (shift_r[ir-1],shift_c[ir-1]),tl=tl,br=br + ) + ) + for ir in range(1,ir_upper) + ] + stack = da.stack(irs) + viewer.add_image(stack, + translate=(x_loc.iloc[idx]/stage2pix_scaling,-y_loc[idx]/stage2pix_scaling), + name=f'fov:{fov}, {channel}nm volume', + opacity=0.5, + scale=[1,z_spacing/stage2z_scaling,-1,1], + contrast_limits=[0,2**16], + colormap='green') + viewer.dims.axis_labels = ['GN','IR', 'Z', 'Y', 'X'] + + + + if config["decoded_img"]: + barcode_viewer=widgets.FancyGUI(viewer,codebook_df,fovs=fovs,x_loc=x_loc.to_numpy()/stage2pix_scaling,y_loc=y_loc.to_numpy()/stage2pix_scaling,img_scale=[1,z_spacing/stage2z_scaling,-1,1]) + viewer.window.add_dock_widget(barcode_viewer,area='right') + + viewer.reset_view()# start the event loop and show the viewer + napari.run() diff --git a/data/napari_merfish/widgets.py b/data/napari_merfish/widgets.py new file mode 100644 index 0000000000000000000000000000000000000000..3a38e2db83e3841c6935b1073c6a1954d85c2102 --- /dev/null +++ b/data/napari_merfish/widgets.py @@ -0,0 +1,65 @@ +from qtpy.QtWidgets import QMainWindow, QLabel,QGridLayout +import napari +from qtpy import uic +from pathlib import Path +import pandas as pd +import dask.array as da + +# Define the main window class +class FancyGUI(QMainWindow): + def __init__(self, napari_viewer:napari.Viewer,codebook:pd.DataFrame,fovs,x_loc,y_loc,img_scale): # include napari_viewer as argument (it has to have this name) + super().__init__() + self.viewer = napari_viewer + self.fovs = fovs + self.x_loc = x_loc + self.y_loc = y_loc + self.img_scale=img_scale + + + + self.codebook = codebook + self.UI_FILE = str(Path(__file__).parent / "barcode_viewer.ui") # path to .ui file + uic.loadUi(self.UI_FILE, self) # load QtDesigner .ui file + # self.widgetArrangement = QGridLayout() + # self.widgetArrangement.addWidget(self.geneName) + # self.widgetArrangement.addWidget(self.barcode) + + # self.setLayout(self.widgetArrangement) + self.btnMakeLayer.clicked.connect(self.makeGeneLayer) + self.viewer.dims.events.connect(self.updateBarcode) + + + def updateBarcode(self): + + current_slice = self.viewer.dims.current_step + + self.lblDecodedBarcode.setText(self.codebook.iloc[current_slice[0]]['barcode']) + self.lbDecodedGeneName.setText(self.codebook.iloc[current_slice[0]]['name']) + + + def makeGeneLayer(self): + + current_slice = self.viewer.dims.current_step + for idx,fov in enumerate(self.fovs): + + + if idx==0: + l = self.viewer.layers[f"decoded"] + else: + try: + l = self.viewer.layers[f"decoded [{idx}]"] + except KeyError: + continue + + self.viewer.add_image( + da.repeat( + da.stack([l.data[current_slice[0],:,:,:,:]],axis=0), + repeats = len(self.codebook), + axis=0), + name=f"Gene: {current_slice[0]} decoded [{idx}]", + translate=(self.x_loc[idx],-self.y_loc[idx]), + scale=self.img_scale, + ) + + print("Layers added") + \ No newline at end of file diff --git a/data/reports/BaseReport.py b/data/reports/BaseReport.py new file mode 100644 index 0000000000000000000000000000000000000000..393c3df3d69b883100d088164a78f0946df113ce --- /dev/null +++ b/data/reports/BaseReport.py @@ -0,0 +1,110 @@ +import json +from typing import List, Union +import numpy as np + + +class BaseReport: + """The Abstract base class for all reports + """ + + def __init__(self, imgstack_files: str, coord_infos: str): + + self.imgstack = self._read_imgstack(imgstack_files) + + if isinstance(coord_infos, list): + merged_json = dict() + for coord_info in coord_infos: + a_file = open(coord_info, "r") + _contents = json.load(a_file) + + for k, v in _contents.items(): + # print(v) + if not (k in merged_json): + # if the key isnt in the merged dictionary, then add and initialise it. This is python 3.6+ behaviour + merged_json[k] = v + continue + + if not isinstance(merged_json[k], list) or isinstance( + merged_json[k], str + ): + # If there is unique data and the value at k in merged dict is not a list already, make it one + merged_json[k] = [merged_json[k]] + _test_dict = merged_json[k].copy() + _base_set = set(_test_dict) + + if isinstance(v, list): + _test_dict.extend(v) + else: + _test_dict.append(v) + + _test_set = set(_test_dict) + # print(_test_set) + # print(_base_set) + if len(_test_set) == len(_base_set): + # If there is nothing unique when making the set of the new content at that key and the old content, then skip + continue + if isinstance(v, list): + merged_json[k].extend(v) + else: + merged_json[k].append(v) + + self.coords = merged_json + # print(self.coords) + else: + a_file = open(coord_infos, "r") + self.coords = json.load(a_file) + + self.pdf = None + + # PDF controls-------------------------------------------- + def set_pdf(self, pdf) -> None: + """Takes a PdfPages object and sets that as the internal variable + + Args: + pdf : the pdf pages object + """ + self.pdf = pdf + + def get_pdf(self): + """Return the pdfpages object + + Returns: + _type_: _description_ + """ + return self.pdf + + def isPdf(self) -> bool: + """Checks if the pdf has been set + + Returns: + bool: _description_ + """ + if self.pdf is None: + return False + return True + + def closePdf(self) -> None: + """Closes the pdf + """ + if self.isPdf(): + self.pdf.close() + self.pdf = None + + def _read_imgstack(self, imgstack_files: Union[List[str], str]): + """Read in an image stack created by utils.fileIO function + + Args: + imgstack_files (str): The + + Returns: + _type_: Loaded Image stack + """ + if isinstance(imgstack_files, list): + # If there is a list of images, then extend the image stack along the last dimension + _imgstack = np.array( + [np.load(image_stack) for image_stack in imgstack_files] + ) + imgstack = np.stack(_imgstack, axis=-1) + else: + imgstack = np.load(imgstack_files) + return imgstack diff --git a/data/reports/BrightnessReport.py b/data/reports/BrightnessReport.py new file mode 100644 index 0000000000000000000000000000000000000000..297203055b888ee71f9ff2ebb8bbefb9774c40d2 --- /dev/null +++ b/data/reports/BrightnessReport.py @@ -0,0 +1,278 @@ +from .BaseReport import BaseReport + +from utils import imgproc + +import skimage.exposure as ske +import numpy as np + +import matplotlib.pyplot as plt +from mpl_toolkits.axes_grid1.inset_locator import inset_axes + + + + +class BrightnessReport(BaseReport): + def __init__(self,imgstack_file,coord_info,fov,z): + super().__init__(imgstack_file,coord_info) + + self.fov_name = fov + self.z_name = z + self.imgstack = self.imgstack # (y,x,wvs,irs) + self.contrast_tape = np.zeros((self.imgstack.shape[2], + self.imgstack.shape[3])) + + + + + #Helper---------------------------------------------- + def calc_HS_metric(self,img): + ''' + https://ieeexplore.ieee.org/document/6108900 + ''' + vals = np.percentile(img.ravel(),[75,25]) + max_val = np.max(img) + min_val = np.min(img) + + return (vals[0]-vals[1])/(max_val-min_val) + def calc_HF_metric(self,img): + ''' + https://ieeexplore.ieee.org/document/6108900 + ''' + + hist,_ = np.histogram(img.flatten(),bins = int(img.max()//2),range=(0,img.max())) + + return np.power(np.prod(hist),1/len(hist)) / hist.sum() * len(hist) + + + def ski_is_low_contrast(self,img,fraction_threshold = 0.25): + return ske.is_low_contrast(img,fraction_threshold=fraction_threshold) + + def contrast_test(self,img,threshold=0.25,method='ski'): + if method=='ski': + return self.ski_is_low_contrast(img,threshold) + elif method =='HS': + res = self.calc_HS_metric(img) + return res>threshold + elif method =='HF': + res = self.calc_HF_metric(img) + return res>threshold + + + + + + #Reports---------------------------------------------- + + def preview_images(self): + max_wv_val = self.imgstack.max(axis=0).max(axis=0).max(axis=1) + val_range = max_wv_val*0.9#self.imgstack.max()*0.90 + f,ax = plt.subplots(nrows=len(self.coords['irs']),ncols=len(self.coords['wvs']),sharex=True,sharey=True,figsize=(len(self.coords['wvs'])*4,len(self.coords['irs'])*4)) + plt.suptitle(f'FOV: {self.fov_name}; Z: {self.z_name}') + if not isinstance(ax,np.ndarray): + ax = np.array([ax]) + if len(ax.shape)==1: + if len(self.coords['irs'])==1: + ax=ax[np.newaxis,:] + elif len(self.coords['wvs'])==1: + ax=ax[:,np.newaxis] + for iwv,wv in enumerate(self.coords['wvs']): + for iir,ir in enumerate(self.coords['irs']): + img = self.imgstack[:,:,iwv,iir] + ax[iir,iwv].imshow(img,vmax=val_range[iwv],cmap='gray') + if iwv==0: + ax[iir,iwv].set_ylabel(f'ir:{ir}') + if iir==0: + ax[iir,iwv].set_title(f'channel: {wv}nm') + + plt.tight_layout() + self.pdf.savefig() + plt.close(f) + + + def brightness_infov_z(self): + largest = self.imgstack.max() + f,ax = plt.subplots(nrows=len(self.coords['irs']),ncols=len(self.coords['wvs']),sharex=True,sharey=True,figsize=(len(self.coords['wvs'])*4,len(self.coords['irs'])*4)) + if not isinstance(ax,np.ndarray): + ax = np.array([ax]) + if len(ax.shape)==1: + if len(self.coords['irs'])==1: + ax=ax[np.newaxis,:] + elif len(self.coords['wvs'])==1: + ax=ax[:,np.newaxis] + plt.suptitle(f'FOV: {self.fov_name}; Z: {self.z_name}') + + for iwv,wv in enumerate(self.coords['wvs']): + for iir,ir in enumerate(self.coords['irs']): + bin_num = int(largest//2) + + data = self.imgstack[:,:,iwv,iir] + self.contrast_tape[iwv,iir] = self.calc_HS_metric(data) + flat_data = data.ravel() + + ax[iir,iwv].hist(flat_data,bins=bin_num,range=(0,largest),log=True,histtype='step') + ax[iir,iwv].text(0.5, 0.5, f'HS:{self.contrast_tape[iwv,iir]}', + ha="center", va="center", + transform=ax[iir,iwv].transAxes) + if iwv==0: + ax[iir,iwv].set_ylabel(f'ir:{ir}') + if iir==0: + ax[iir,iwv].set_title(f'channel: {wv}nm') + + plt.tight_layout() + self.pdf.savefig() + plt.close(f) + + def brightness_on_images(self): + + + max_wv_val = self.imgstack.max(axis=0).max(axis=0).max(axis=1) + val_range = max_wv_val*0.9 + largest = self.imgstack.max() + f,ax = plt.subplots(nrows=len(self.coords['irs']),ncols=len(self.coords['wvs']),sharex=True,sharey=True,figsize=(len(self.coords['wvs'])*4,len(self.coords['irs'])*4)) + plt.suptitle(f'FOV: {self.fov_name}; Z: {self.z_name}') + if not isinstance(ax,np.ndarray): + ax = np.array([ax]) + if len(ax.shape)==1: + if len(self.coords['irs'])==1: + ax=ax[np.newaxis,:] + elif len(self.coords['wvs'])==1: + ax=ax[:,np.newaxis] + for iwv,wv in enumerate(self.coords['wvs']): + for iir,ir in enumerate(self.coords['irs']): + img = self.imgstack[:,:,iwv,iir] + bin_num = int(largest//2) + ax[iir,iwv].imshow(img,vmax=val_range[iwv],cmap='gray') + # Add histogram to the corner of the image + axins = inset_axes(ax[iir,iwv], width="25%", height="25%", loc=4, borderpad=1) + data = img.ravel() + axins.hist(data,bins=bin_num,range=(0,largest),log=True,histtype='step') + axins.tick_params(labelleft=False, labelbottom=False) + if iwv==0: + ax[iir,iwv].set_ylabel(f'ir:{ir}') + if iir==0: + ax[iir,iwv].set_title(f'channel: {wv}nm') + + plt.tight_layout() + self.pdf.savefig() + plt.close(f) + + def contrast_heatmap(self): + + f,ax = plt.subplots() + + ims = ax.imshow(self.contrast_tape) + ax.set_yticks(np.arange(len(self.coords['wvs'])), self.coords['wvs']) + ax.set_xticks(np.arange(len(self.coords['irs'])), self.coords['irs']) + ax.set_ylabel("Wavelength (nm)") + ax.set_xlabel("Imaging Round") + + ax.set_title(f'FOV: {self.fov_name}; Z: {self.z_name}') + plt.colorbar(ims) + plt.tight_layout() + self.pdf.savefig() + plt.close(f) + + def _brightness_through_z(self): + """This is deprecated. + """ + #Take the image stack and do a max projection from all the pixels through z + mip_z_stack = self.imgstack.max(axis=4) + + largest = mip_z_stack.max() + f,ax = plt.subplots(nrows=len(self.coords['irs']),ncols=len(self.coords['wvs']),sharex=True,sharey=True,figsize=(len(self.coords['wvs'])*4,len(self.coords['irs'])*4)) + if not isinstance(ax,np.ndarray): + ax = np.array([ax]) + if len(ax.shape)==1: + if len(self.coords['irs'])==1: + ax=ax[np.newaxis,:] + elif len(self.coords['wvs'])==1: + ax=ax[:,np.newaxis] + plt.suptitle(f'FOV: {self.fov_name}') + for iwv,wv in enumerate(self.coords['wvs']): + for iir,ir in enumerate(self.coords['irs']): + bin_num = int(largest//2) + + data = mip_z_stack[:,:,iwv,iir] + self.contrast_tape[iwv,iir] = self.calc_HS_metric(data) + flat_data = data.ravel() + + ax[iir,iwv].hist(flat_data,bins=bin_num,range=(0,largest),log=True,histtype='step') + ax[iir,iwv].text(0.5, 0.5, f'HS:{self.contrast_tape[iwv,iir]}', + ha="center", va="center", + transform=ax[iir,iwv].transAxes) + if iwv==0: + ax[iir,iwv].set_ylabel(f'ir:{ir}') + if iir==0: + ax[iir,iwv].set_title(f'channel: {wv}nm') + + plt.tight_layout() + self.pdf.savefig() + plt.close(f) + + + def _brightness_through_z_on_images(self): + """This is Deprecated. + """ + mip_z_stack = self.imgstack.max(axis=4) + + max_wv_val = self.imgstack.max(axis=0).max(axis=0).max(axis=1).max(axis=1) + val_range = max_wv_val*0.9 + largest = mip_z_stack.max() + f,ax = plt.subplots(nrows=len(self.coords['irs']),ncols=len(self.coords['wvs']),sharex=True,sharey=True,figsize=(len(self.coords['wvs'])*4,len(self.coords['irs'])*4)) + plt.suptitle(f'FOV: {self.fov_name}') + if not isinstance(ax,np.ndarray): + ax = np.array([ax]) + if len(ax.shape)==1: + if len(self.coords['irs'])==1: + ax=ax[np.newaxis,:] + elif len(self.coords['wvs'])==1: + ax=ax[:,np.newaxis] + for iwv,wv in enumerate(self.coords['wvs']): + for iir,ir in enumerate(self.coords['irs']): + img = mip_z_stack[:,:,iwv,iir] + bin_num = int(largest//2) + ax[iir,iwv].imshow(img,vmax=val_range[iwv],cmap='gray') + # Add histogram to the corner of the image + axins = inset_axes(ax[iir,iwv], width="25%", height="25%", loc=4, borderpad=1) + data = img.flatten() + axins.hist(data,bins=bin_num,range=(0,largest),log=True,histtype='step') + axins.tick_params(labelleft=False, labelbottom=False) + if iwv==0: + ax[iir,iwv].set_ylabel(f'ir:{ir}') + if iir==0: + ax[iir,iwv].set_title(f'channel: {wv}nm') + + plt.tight_layout() + self.pdf.savefig() + plt.close(f) + + + + def _preview_images(self): + """This is deprecated. + """ + mip_z_stack = self.imgstack.max(axis=4) + max_wv_val = self.imgstack.max(axis=0).max(axis=0).max(axis=1).max(axis=1) + val_range = max_wv_val*0.9#self.imgstack.max()*0.90 + + f,ax = plt.subplots(nrows=len(self.coords['irs']),ncols=len(self.coords['wvs']),sharex=True,sharey=True,figsize=(len(self.coords['wvs'])*4,len(self.coords['irs'])*4)) + plt.suptitle(f'FOV: {self.fov_name}') + if not isinstance(ax,np.ndarray): + ax = np.array([ax]) + if len(ax.shape)==1: + if len(self.coords['irs'])==1: + ax=ax[np.newaxis,:] + elif len(self.coords['wvs'])==1: + ax=ax[:,np.newaxis] + for iwv,wv in enumerate(self.coords['wvs']): + for iir,ir in enumerate(self.coords['irs']): + img = mip_z_stack[:,:,iwv,iir] + ax[iir,iwv].imshow(img,vmax=val_range[iwv],cmap='gray') + if iwv==0: + ax[iir,iwv].set_ylabel(f'ir:{ir}') + if iir==0: + ax[iir,iwv].set_title(f'channel: {wv}nm') + + plt.tight_layout() + self.pdf.savefig() + plt.close(f) diff --git a/data/reports/DecodabilityReport.py b/data/reports/DecodabilityReport.py new file mode 100644 index 0000000000000000000000000000000000000000..2bd9908f19dfd5009c0d0f3470c281009ef35952 --- /dev/null +++ b/data/reports/DecodabilityReport.py @@ -0,0 +1,522 @@ +import sys + +sys.path.append("../") +from utils.fileIO import Codebook, read_table +from utils.imgproc import warp_image,register_stack +from utils.helper_functions import performDumbExtraction, findErrorBits +from .BaseReport import BaseReport +import numpy as np +import matplotlib.pyplot as plt +import matplotlib as mpl +import scipy.ndimage as ndi +import skimage +from sklearn.neighbors import NearestNeighbors + +mpl.rcParams["image.interpolation"] = "none" + + +class DecodabilityReport(BaseReport): + """This report produces graphs and figures that provide insight into the decodeability of a dataset. + + Args: + deconvolved_img_stack (str): The path to the img stack of deconvolved images + coord_info (str): The path to the coordinate information file for the fov and z + codebook_file (str): The path to the codebook csv file + data_org_file (str): The path to the data organization file + fov (str): The fov name that belongs to the image stack + z (str): The z name that belongs to the image stack + out_detection_stats (str): The path that the detection stats will be printed into + + Raises: + AssertionError: If the number of wavelenghts is not 4 in the coordinate file, then the image warping in the data organization file wont work. + """ + def __init__( + self, + deconvolved_img_stack: str, + coord_info: str, + codebook_file: str, + data_org_file: str, + fov: int, + z: int, + out_detection_stats: str, + ): + + super().__init__(deconvolved_img_stack, coord_info) + if not (len(self.coords["wvs"]) == 4): + raise AssertionError("Image Stack must contain 4 channels") + + self.fov_name = fov + self.z_name = z + self.out_detection_stats = out_detection_stats + # Load the codebook file + self.codebook = Codebook(codebook_file) + + # Load the dataorg file + data_org = read_table(data_org_file).to_dict("records") + self.registered_images = register_stack(self.imgstack) + # Warp the deconvolved image stack into (16,x,y) + self.warped_imgs = warp_image(data_org, self.registered_images, 16) + + # Pass into the perform the dumb extraction + ( + self.filtered_warped_images, + self.bright_pixel_count, + self.bit_map, + self.bit_vector_map, + self.dist_map, + self.barcode_map, + self.error_bit_map, + self.detection_number_map, + self.codebook_bits, + ) = performDumbExtraction( + self.warped_imgs, self.codebook, clip_thresh=98.5 + ) + + """ + ====MAKE REPORTS===== + """ + + def make_bit_imgs(self): + """Generates the 3,4, and 5 bit detection images. + These are bits that are within 1 manhattan distance + to an entry in the codebook + """ + # make 3,4,5 bit images + image_blank = np.zeros( + (self.warped_imgs.shape[1], self.warped_imgs.shape[2]) + ) + + bc3_img = np.multiply( + np.reshape(self.barcode_map[3], image_blank.shape) + 1, + np.reshape(self.dist_map[3] == 1, image_blank.shape), + ) + bc4_img = np.multiply( + np.reshape(self.barcode_map[4], image_blank.shape) + 1, + np.reshape(self.dist_map[4] == 0, image_blank.shape), + ) + bc5_img = np.multiply( + np.reshape(self.barcode_map[5], image_blank.shape) + 1, + np.reshape(self.dist_map[5] == 1, image_blank.shape), + ) + + bc3_img = np.where(bc3_img > 0, 1, 0) + + bc4_img = np.where(bc4_img > 0, 1, 0) + + bc5_img = np.where(bc5_img > 0, 1, 0) + + f, ax = plt.subplots( + nrows=1, ncols=3, sharex=True, sharey=True, figsize=(3 * 10, 10) + ) + + ax[0].imshow( + bc3_img, cmap="gray", vmin=0, vmax=1, interpolation="none" + ) + ax[1].imshow( + bc4_img, cmap="gray", vmin=0, vmax=1, interpolation="none" + ) + ax[2].imshow( + bc5_img, cmap="gray", vmin=0, vmax=1, interpolation="none" + ) + + ax[0].set_title("Image of 3-bit Decodable barcodes") + ax[1].set_title("Image of 4-bit Decodable barcodes") + ax[2].set_title("Image of 5-bit Decodable barcodes") + + plt.tight_layout() + self.pdf.savefig() + plt.close(f) + + # Set the colour images + + colour_img = np.zeros((bc5_img.shape[0], bc5_img.shape[1], 3)) + + colour_img[:, :, 0] = bc3_img + colour_img[:, :, 1] = bc4_img + colour_img[:, :, 2] = bc5_img + + f, ax = plt.subplots(figsize=(40, 40)) + ax.imshow(colour_img, vmin=0, vmax=1, interpolation="none") + plt.title("Red: 3-bit words; Green: 4-bit words; Blue: 5-bit words") + plt.tight_layout() + self.pdf.savefig() + plt.close(f) + + # For each bit in the filtered warped image, spit out an RGB image + + f, axs = plt.subplots(4, 4, figsize=(43, 43)) + axs = axs.flatten() + window_half_width = 50 + + while True: + r, c = ( + np.random.randint(0, bc3_img.shape[0]), + np.random.randint(0, bc3_img.shape[1]), + ) + + tl = [int(r - window_half_width), int(c - window_half_width)] + + br = [int(r + window_half_width), int(c + window_half_width)] + + fwi = np.moveaxis(self.filtered_warped_images, 0, -1) + wi = np.moveaxis(self.warped_imgs, 0, -1) + masked3 = np.multiply( + fwi, + np.reshape(self.dist_map[3] == 1, image_blank.shape)[ + ..., None + ], + ) + + masked4 = np.multiply( + fwi, + np.reshape(self.dist_map[4] == 0, image_blank.shape)[ + ..., None + ], + ) + + masked5 = np.multiply( + fwi, + np.reshape(self.dist_map[5] == 1, image_blank.shape)[ + ..., None + ], + ) + + cropped_mask3 = masked3[tl[0]: br[0] + 1, tl[1]: br[1] + 1, :] + cropped_mask4 = masked4[tl[0]: br[0] + 1, tl[1]: br[1] + 1, :] + cropped_mask5 = masked5[tl[0]: br[0] + 1, tl[1]: br[1] + 1, :] + + if np.all(cropped_mask3 != 1) and np.all(cropped_mask5 != 1): + pass # If the cropped area is empty, then try it all again + else: + break + + mpl.rcParams["image.interpolation"] = "none" + for iax, ax in enumerate(axs): + colour_image = np.stack( + ( + cropped_mask3[:, :, iax], + cropped_mask4[:, :, iax], + cropped_mask5[:, :, iax], + ), + axis=2, + ) + + ax.imshow(colour_image * 255, vmin=0, vmax=1) + ax.set_title(f"Bit: {iax}") + plt.suptitle( + f"Red: 3-bit words; Green: 4-bit words; Blue: 5-bit words \n \ + Row: {r}, Column {c}, CropSize {2*window_half_width+1}" + ) + # plt.tight_layout() + self.pdf.savefig() + plt.close(f) + + f, axs = plt.subplots(4, 4, figsize=(43, 43)) + axs = axs.flatten() + + masked3 = np.multiply( + fwi, + np.reshape(self.dist_map[3] == 1, image_blank.shape)[..., None], + ) + + masked4 = np.multiply( + fwi, + np.reshape(self.dist_map[4] == 0, image_blank.shape)[..., None], + ) + + masked5 = np.multiply( + fwi, + np.reshape(self.dist_map[5] == 1, image_blank.shape)[..., None], + ) + + cropped_mask3 = masked3[tl[0]: br[0] + 1, tl[1]: br[1] + 1, :] + cropped_mask4 = masked4[tl[0]: br[0] + 1, tl[1]: br[1] + 1, :] + cropped_mask5 = masked5[tl[0]: br[0] + 1, tl[1]: br[1] + 1, :] + + row3, col3, z3 = np.where(cropped_mask3 == 1) + + row4, col4, z4 = np.where(cropped_mask4 == 1) + + row5, col5, z5 = np.where(cropped_mask5 == 1) + + for iax, ax in enumerate(axs): + crop = wi[tl[0]: br[0] + 1, tl[1]: br[1] + 1, iax] + crap_max = ndi.maximum_filter(crop, size=2, mode="constant") + peak = skimage.feature.peak_local_max(crap_max, min_distance=2) + # print(peak) + ax.imshow(crop, cmap="gray") + ax.scatter(col3, row3, s=15, color="red", marker="*") + ax.scatter(col4, row4, s=15, color="green", marker="*") + ax.scatter(col5, row5, s=15, color="blue", marker="*") + ax.scatter( + peak[:, 1], peak[:, 0], s=10, color="yellow", marker="*" + ) + ax.set_title(f"Bit: {iax}") + plt.suptitle( + "Red: 3-bit words; Green: 4-bit words; Blue: 5-bit words\n \ + Overlayed on smoothed deconvolved image" + ) + # plt.tight_layout() + self.pdf.savefig() + plt.close(f) + + f, axs = plt.subplots(4, 4, figsize=(40, 40)) + axs = axs.flatten() + for iax, ax in enumerate(axs): + crop = fwi[tl[0]: br[0] + 1, tl[1]: br[1] + 1, iax] + crap_max = ndi.maximum_filter(crop, size=2, mode="constant") + peak = skimage.feature.peak_local_max(crap_max, min_distance=2) + # print(peak) + ax.imshow(crop, cmap="gray") + ax.scatter(col3, row3, s=15, color="red", marker="*") + ax.scatter(col4, row4, s=15, color="green", marker="*") + ax.scatter(col5, row5, s=15, color="blue", marker="*") + ax.scatter( + peak[:, 1], peak[:, 0], s=10, color="yellow", marker="*" + ) + ax.set_title(f"Bit: {iax}") + plt.suptitle( + "Red: 3-bit words; Green: 4-bit words; Blue: 5-bit words\n \ + Overlayed thresholded deconvolved image" + ) + # plt.tight_layout() + self.pdf.savefig() + plt.close(f) + + def make_decodability_hists(self): + """Make the histograms that for determining decoability based on + thresholded pixels + """ + f, ax = plt.subplots(figsize=(10, 10)) + plt.hist( + self.bright_pixel_count.ravel(), bins=[i for i in range(17)], + ) + ax.set_xlim([1, 17]) + ax.set_ylim([0, 0.6e6]) + ax.vlines(x=[3, 6], ymin=0, ymax=ax.get_ylim()[1], colors=["r", "r"]) + ax.set_xticks( + ticks=[i + 0.5 for i in range(17)], labels=[i for i in range(17)] + ) + ax.set_title("Number of bright pixels stacked") + plt.tight_layout() + self.pdf.savefig() + plt.close(f) + codebook_bits = np.array(self.codebook.barcode_arrays) + nbrs = NearestNeighbors( + n_neighbors=1, algorithm="ball_tree", p=1 + ).fit(codebook_bits) + + bright_pix_3bcs = np.reshape(self.bit_map[3], (16, -1)).T + bright_pix_4bcs = np.reshape(self.bit_map[4], (16, -1)).T + bright_pix_5bcs = np.reshape(self.bit_map[5], (16, -1)).T + + bright_pix_3bcs = bright_pix_3bcs[bright_pix_3bcs.sum(axis=1) > 0, :] + bright_pix_4bcs = bright_pix_4bcs[bright_pix_4bcs.sum(axis=1) > 0, :] + bright_pix_5bcs = bright_pix_5bcs[bright_pix_5bcs.sum(axis=1) > 0, :] + + # Look at distances for 3 pixel barcodes + dist3, barcode3_ids = nbrs.kneighbors(bright_pix_3bcs) + dist3_fraction = (dist3 == 1).sum() / (dist3 > 0).sum() + f, ax = plt.subplots(figsize=(10, 10)) + plt.hist(dist3.ravel(), bins=[i for i in range(17)]) + plt.vlines(x=[1, 2], ymin=0, ymax=ax.get_ylim()[1], colors=["r", "r"]) + ax.set_xticks( + ticks=[i + 0.5 for i in range(17)], labels=[i for i in range(17)] + ) + ax.set_xlabel("Manhattan Distance away from entry in codebook") + ax.set_ylabel("Number of Pixels") + plt.title( + "3 Bright Pixel Barcodes: Manhattan Distance \n Detection fraction: \ + {:.02f}".format(dist3_fraction) + ) + plt.tight_layout() + self.pdf.savefig() + plt.close(f) + # Look at distances for 4 pixel barcodes + dist4, barcode4_ids = nbrs.kneighbors(bright_pix_4bcs) + dist4_fraction = (dist4 == 0).sum() / (dist4 > -1).sum() + f, ax = plt.subplots(figsize=(10, 10)) + plt.hist(dist4.ravel(), bins=[i for i in range(17)]) + plt.vlines(x=[0, 1], ymin=0, ymax=ax.get_ylim()[1], colors=["r", "r"]) + ax.set_xticks( + ticks=[i + 0.5 for i in range(17)], labels=[i for i in range(17)] + ) + ax.set_xlabel("Manhattan Distance away from entry in codebook") + ax.set_ylabel("Number of Pixels") + plt.title( + "4 Bright Pixel Barcodes: Manhattan Distance \n Detection fraction: \ + {:.02f}".format(dist4_fraction) + ) + plt.tight_layout() + self.pdf.savefig() + plt.close(f) + + # Look at distances for 5 pixel barcodes + dist5, barcode5_ids = nbrs.kneighbors(bright_pix_5bcs) + dist5_fraction = (dist5 == 1).sum() / (dist5 > -1).sum() + f, ax = plt.subplots(figsize=(10, 10)) + plt.hist(dist5.ravel(), bins=[i for i in range(17)]) + plt.vlines(x=[1, 2], ymin=0, ymax=ax.get_ylim()[1], colors=["r", "r"]) + ax.set_xticks( + ticks=[i + 0.5 for i in range(17)], labels=[i for i in range(17)] + ) + ax.set_xlabel("Manhattan Distance away from entry in codebook") + ax.set_ylabel("Number of Pixels") + plt.title( + "5 Bright Pixel Barcodes: Manhattan Distance \ + \n Detection fraction: {:.02f}".format( + dist5_fraction + ) + ) + plt.tight_layout() + self.pdf.savefig() + plt.close(f) + + """ + Find out what is the bit distribution of the spots that had 3-5 bits, + but didnt match the codebook + """ + + unique_dist3 = np.unique(dist3) + dist3_barcode_hist = np.zeros((16, 16)) + for ud3 in unique_dist3: + dist3_barcode_hist[int(ud3), :] = np.sum( + bright_pix_3bcs[np.squeeze(dist3 == ud3), :], axis=0 + ) + dist3_barcode_hist[int(ud3), :] = np.nan_to_num( + dist3_barcode_hist[int(ud3), :] + / dist3_barcode_hist[int(ud3), :].sum() + ) + + unique_dist4 = np.unique(dist4) + dist4_barcode_hist = np.zeros((16, 16)) + for ud4 in unique_dist4: + dist4_barcode_hist[int(ud4), :] = np.sum( + bright_pix_4bcs[np.squeeze(dist4 == ud4), :], axis=0 + ) + dist4_barcode_hist[int(ud4), :] = np.nan_to_num( + dist4_barcode_hist[int(ud4), :] + / dist4_barcode_hist[int(ud4), :].sum() + ) + + unique_dist5 = np.unique(dist5) + dist5_barcode_hist = np.zeros((16, 16)) + for ud5 in unique_dist5: + dist5_barcode_hist[int(ud5), :] = np.sum( + bright_pix_5bcs[np.squeeze(dist5 == ud5), :], axis=0 + ) + dist5_barcode_hist[int(ud5), :] = np.nan_to_num( + dist5_barcode_hist[int(ud5), :] + / dist5_barcode_hist[int(ud5), :].sum() + ) + + f, ax = plt.subplots(figsize=(10, 10)) + plt.imshow(dist3_barcode_hist) + for ud in range(dist3_barcode_hist.shape[0]): + for bp in range(dist3_barcode_hist.shape[0]): + _ = ax.text( + bp, + ud, + f"{dist3_barcode_hist[ud, bp]*100:.2f}%", + ha="center", + va="center", + color="w", + ) + ax.set_ylabel("Manhattan Distance away from entry in codebook") + ax.set_xlabel("Bit Number") + plt.title("3 Bright Pixel bit distribution") + plt.tight_layout() + self.pdf.savefig() + plt.close(f) + + f, ax = plt.subplots(figsize=(10, 10)) + plt.imshow(dist4_barcode_hist) + for ud in range(dist4_barcode_hist.shape[0]): + for bp in range(dist4_barcode_hist.shape[0]): + _ = ax.text( + bp, + ud, + f"{dist4_barcode_hist[ud, bp]*100:.2f}%", + ha="center", + va="center", + color="w", + ) + ax.set_ylabel("Manhattan Distance away from entry in codebook") + ax.set_xlabel("Bit Number") + plt.title("4 Bright Pixel bit distribution") + plt.tight_layout() + self.pdf.savefig() + plt.close(f) + + f, ax = plt.subplots(figsize=(10, 10)) + plt.imshow(dist5_barcode_hist) + for ud in range(dist5_barcode_hist.shape[0]): + for bp in range(dist5_barcode_hist.shape[0]): + _ = ax.text( + bp, + ud, + f"{dist5_barcode_hist[ud, bp]*100:.2f}%", + ha="center", + va="center", + color="w", + ) + ax.set_ylabel("Manhattan Distance away from entry in codebook") + ax.set_xlabel("Bit Number") + plt.title("5 Bright Pixel bit distribution") + plt.tight_layout() + self.pdf.savefig() + plt.close(f) + + errorBit3 = findErrorBits( + bright_pix_3bcs, + self.codebook_bits, + dist3, + barcode3_ids, + filter_val=1, + ) + + errorBit4 = findErrorBits( + bright_pix_4bcs, + self.codebook_bits, + dist4, + barcode4_ids, + filter_val=0, + ) + + errorBit5 = findErrorBits( + bright_pix_5bcs, + self.codebook_bits, + dist5, + barcode5_ids, + filter_val=1, + ) + + f, ax = plt.subplots(1, 3, figsize=(3 * 10, 10)) + ax[0].hist( + errorBit3.ravel(), bins=[i for i in range(17)], align="left" + ) + ax[1].hist( + errorBit4.ravel(), bins=[i for i in range(17)], align="left" + ) + ax[2].hist( + errorBit5.ravel(), bins=[i for i in range(17)], align="left" + ) + ax[0].set_title("Bits to correct for 3-bit detections") + ax[1].set_title("Bits to correct for 4-bit detections") + ax[2].set_title("Bits to correct for 5-bit detections") + self.pdf.savefig() + plt.close(f) + + # # Save the output of detected barcodes + number_report = [ + f"Number of 3bit Detections: {dist3[dist3==1].sum()}\n", + f"Number of 4bit Detections: {(1+dist4[dist4==0]).sum()}\n", + f"Number of 5bit Detections: {dist5[dist5==1].sum()}", + ] + + with open(f"{self.out_detection_stats}", "w") as f: + f.writelines(number_report) + + +if __name__ == "__main__": + print("test") diff --git a/data/reports/FocusReport.py b/data/reports/FocusReport.py new file mode 100644 index 0000000000000000000000000000000000000000..eeffdd051bbf8d3d7aa7ec89b4cb4eba2eca3564 --- /dev/null +++ b/data/reports/FocusReport.py @@ -0,0 +1,76 @@ +from .BaseReport import BaseReport + +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd + +import scipy.ndimage as ndi + +class FocusReport(BaseReport): + def __init__(self,imgstack_files,coord_infos,fov,out_csv): + super().__init__(imgstack_files,coord_infos) + + self.fov_name = fov + self.imgstack = self.imgstack #(y,x,wvs,irs,zs) + + self.peak_idx = np.zeros((self.imgstack.shape[2],self.imgstack.shape[3])) + self.out_csv = out_csv + def f_measure(self,img): + filter = np.array([ [1], + [0], + [-1], + [0], + [0]]) + + res = ndi.convolve(img,filter,mode='reflect') + res = np.power(res,2) + return res.sum() + + #Reports----- + def f_measure_report(self): + + + #create an empty matrix with dimensions of ir x wv x z (rows v cols v depth) + #Populate the matrix in the loop + #Then imshow and add text + + focus_matrix = np.zeros((len(self.coords['irs']), + len(self.coords['wvs']), + len(self.coords['zs'])) + ) + + for iir,ir in enumerate(self.coords['irs']): + for iwv,wv in enumerate(self.coords['wvs']): + for iz,z in enumerate(self.coords['zs']): + focus_matrix[iir,iwv,iz] = self.f_measure(self.imgstack[:,:,iwv,iir,iz]) + + viz_focus_matrix = np.argmax(focus_matrix,axis=2) + + f, ax = plt.subplots() + im = ax.imshow(viz_focus_matrix) + + ax.set_xticks(np.arange(len(self.coords['wvs'])), self.coords['wvs']) + ax.set_yticks(np.arange(len(self.coords['irs'])), self.coords['irs']) + ax.set_xlabel("Wavelength (nm)") + ax.set_ylabel("Imaging Round") + plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") + + for iir in range(len(self.coords['irs'])): + for iwv in range(len(self.coords['wvs'])): + text = ax.text(iwv, iir, viz_focus_matrix[iir, iwv], ha="center", va="center", color="w") + + + + plt.tight_layout() + self.pdf.savefig() + plt.close(f) + + #Save the pk idx to a csv information for each imaging round + df = pd.DataFrame() + for iwv,wv in enumerate(self.coords['wvs']): + df[str(wv)] = viz_focus_matrix[:,iwv] # each imaging round is a row + df["FOV"] = len(viz_focus_matrix[:,0])*[self.fov_name] + df["IR"] = self.coords['irs'] + df.to_csv(self.out_csv) + + diff --git a/data/reports/MaskedBrightnessReport.py b/data/reports/MaskedBrightnessReport.py new file mode 100644 index 0000000000000000000000000000000000000000..32e15ca51599cc7054f89ce5a45756db9b5e9778 --- /dev/null +++ b/data/reports/MaskedBrightnessReport.py @@ -0,0 +1,11 @@ +from reports.BrightnessReport import BrightnessReport +import numpy as np + + +class MaskedBrightnessReport(BrightnessReport): + def __init__(self,imgstack_file,masked_images,coord_info,fov,z): + super().__init__(imgstack_file,coord_info,fov,z) + self.mask_imgstack = self._read_imgstack(masked_images)# (y,x,wvs,irs) + + self.imgstack = np.multiply(self.imgstack,self.mask_imgstack) + \ No newline at end of file diff --git a/data/reports/__init__.py b/data/reports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/test_notebooks/clutering_metrics.ipynb b/data/test_notebooks/clutering_metrics.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/test_notebooks/get_registration_offsets.py b/data/test_notebooks/get_registration_offsets.py new file mode 100644 index 0000000000000000000000000000000000000000..7667a354b814f42422a965b0b0b68a577f6443b5 --- /dev/null +++ b/data/test_notebooks/get_registration_offsets.py @@ -0,0 +1,72 @@ +import argparse +import os +from pathlib import Path +import numpy as np +import pandas as pd + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('-i', type = str, help ="Input directory") + parser.add_argument('-o', type = str, help="Output directory") + parser.add_argument('-file_format', default = "*.npy", type = str, help = "File to open") + + args = parser.parse_args() + + if not args.o: + args.o = args.i + + if not os.path.exists(args.o): + os.makedirs(args.o) + + input_list = _get_file_paths(args.i, args.file_format) + + offset_x, offset_y = _get_x_y_offsets(input_list) + + _save_csv(args.o, offset_x, "x_offsets") + + _save_csv(args.o, offset_y, "y_offsets") + +def _get_file_paths(input_dir, img_format): + input_dir = Path(input_dir) + path_list = [str(path) for path in list(sorted(input_dir.rglob(img_format)))] + return path_list + +def _save_csv(output_dir, df, name): + df.to_csv(output_dir+"/"+name+".csv") + + +def _get_x_y_offsets(input_list): + nFOV = len(input_list) + num_datachannels = 16 + + offset_array_x = np.zeros(shape = (nFOV, num_datachannels+1)) + offset_array_y = np.zeros(shape = (nFOV, num_datachannels+1)) + + + for fov in range(nFOV): + tnx = np.load(input_list[fov], allow_pickle = True) + offset_array_x[fov,0] = int(fov+1) + offset_array_y[fov,0] = int(fov+1) + for j in range(num_datachannels): + offset_array_x[fov,j+1] = tnx[j].params[0][-1] + offset_array_y[fov,j+1] = tnx[j].params[1][-1] + + pd_columns = ['FOV', + 'Offset b/w IR1 & IR 1', + 'Offset b/w IR1 & IR 2', + 'Offset b/w IR1 & IR 3', + 'Offset b/w IR1 & IR 4', + 'Offset b/w IR1 & IR 5', + 'Offset b/w IR1 & IR 6', + 'Offset b/w IR1 & IR 7', + 'Offset b/w IR1 & IR 8'] + + offset_pd_x = pd.DataFrame(offset_array_x[:, ::2], columns=pd_columns) + offset_pd_y = pd.DataFrame(offset_array_y[:, ::2], columns=pd_columns) + + return offset_pd_x, offset_pd_y + + +if __name__ == '__main__': + main() + # python get_registration_offsets.py -i "/Users/ythapliyal/Documents/Merlin_results/FiducialCorrelationWarp/XP4516" diff --git a/data/utils/__init__.py b/data/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/utils/fileIO.py b/data/utils/fileIO.py new file mode 100644 index 0000000000000000000000000000000000000000..966a20840281a9ece2dcb1a72ef31f25206ac866 --- /dev/null +++ b/data/utils/fileIO.py @@ -0,0 +1,144 @@ +import csv +import re +from typing import List +import skimage.io as skio +import numpy as np +import json +import pandas as pds + +import matplotlib.colors as mcolors + + +base_colors = list(mcolors.BASE_COLORS) + + +def create_image_stack( + image_format: str, + fov: str, + z: str, + irs: List[str], + wvs: List[str], + out_file: str, + coord_file: str, +): + """Creates the images in an memory format for convenient data access in later reports + + Args: + image_format (str): The file image pattern that will be used to construct the image stacks + fov (str): The Fov of images to use for the stack + z (str): The z of the images to use for the stack + irs (List[str]): The list of imaging rounds for the stack + wvs (List[str]): The list of channels for the stack + out_file (str): The filename of the image stack produced + coord_file (str): The filename of the coordinate file produced + """ + # if any parameter is a single string, then make it into an iterable + # list object + + if not isinstance(irs, list): + irs = [irs] + if not isinstance(wvs, list): + wvs = [wvs] + + # Extract a test image to get size parameter out of + test_img = skio.imread(image_format.format(wv=wvs[0], fov=fov, ir=irs[0], z=z)) + + xyshape = test_img.shape + x = xyshape[1] + y = xyshape[0] + + # Load in all the data + + # Pre-allocate the image stack + img_stack = np.zeros((y, x, len(wvs), len(irs),)) + for iir, ir in enumerate(irs): + for iwv, wv in enumerate(wvs): + + img_stack[:, :, iwv, iir] = skio.imread( + image_format.format(wv=wv, fov=fov, ir=ir, z=z) + ) + # Drop it all into an npy file + np.save(out_file, img_stack) + + # Save all the coordinates for the dimensions into a seperate file + data = {"y": y, "x": x, "wvs": wvs, "irs": irs, "fovs": [fov], "zs": [z]} + a_file = open(coord_file, "w") + a_file = json.dump(data, a_file) + + +class Codebook: + """The Codebook helper class + + Args: + codebook_path (str): The path to the codebook file + """ + def __init__(self, codebook_path: str): + # TODO this could probably work well as a pandas df + self.names = [] + self.ids = [] + self.barcode_strings = [] + with open(codebook_path, encoding="utf8") as csv_file: + codebook_reader = csv.reader(csv_file) + for i, row in enumerate(codebook_reader): + if i == 0: + self.version = row[1] + elif i == 1: + self.codebook_name = row[1] + elif i == 2: + self.bit_names = row[1:] + elif i >= 4: + self.names.append(row[0]) + self.ids.append(row[1]) + self.barcode_strings.append(row[2]) + self.barcode_arrays = [ + np.array([int(char) for char in re.sub(r"\s", "", barcode)], dtype="uint8") + for barcode in self.barcode_strings + ] + + def __len__(self): + return len(self.names) + + def normalize_barcode(self, barcode_array): + if np.sum(barcode_array) == 0: + return barcode_array + return barcode_array / np.sqrt(np.sum(barcode_array ** 2)) + + def get_weighted_barcodes(self): + magnitudes = [np.sqrt(sum(barcodes ** 2)) for barcodes in self.barcode_arrays] + return [ + (self.barcode_arrays[i] / magnitudes[i]).astype("float16") + for i in range(len(self.barcode_arrays)) + ] + + def get_single_bit_error_matrix(self, barcode_id): + barcode_array = self.barcode_arrays[barcode_id] + bit_error_matrix = [self.normalize_barcode(barcode_array)] + for i in range(len(barcode_array)): + corrected_barcode = barcode_array.copy() + corrected_barcode[i] = np.logical_not(corrected_barcode[i]) + bit_error_matrix.append(self.normalize_barcode(corrected_barcode)) + return np.array(bit_error_matrix) + + +def read_table(file: str) -> pds.DataFrame: + """Reads a file differently depending on its extension + + Args: + file (str): The filename + + Raises: + ValueError: If the file extension is unrecognized + + Returns: + pandas.DataFrame: _description_ + """ + ext = file.split(".")[-1] + if ext == "csv": + df = pds.read_csv(file) + elif ext == "tsv": + df = pds.read_csv(file, "\t") + elif ext in {"xls", "xlsx", "xlsm", "xlsb"}: + df = pds.read_excel(file) + else: + raise ValueError("Unexpected file extension") + return df diff --git a/data/utils/helper_functions.py b/data/utils/helper_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..a4cb5b801f2c7d49489c0b792a0c6bc6d0e297f7 --- /dev/null +++ b/data/utils/helper_functions.py @@ -0,0 +1,147 @@ +import os +import numpy as np +from typing import List +from sklearn.neighbors import NearestNeighbors + + +def check_dirs(files: List[str]) -> None: + """Checks to see if the directories for the files in the list exist. If they dont, then make those directories + + Args: + files (list[str]): the list of files whose directory paths to create. Needs to be the full, not relative paths + + """ + if not type(files) == list: + d = os.path.dirname(files) + if not os.path.isdir(d): + # print(files+'files' + d +'Does not exist') + os.makedirs(d) + else: + for f in files: + + d = os.path.dirname(f) + if d != "" and not os.path.isdir(d): + # print(f+'files' + d +'Does not exist') + os.makedirs(d) + + +def identity(img): + return img + + +def transformWarpedImages(warped_images, transform, clip_thresh): + + pp_wi = list() + filtered_wi = list() + for wi in range(warped_images.shape[0]): + _img = transform(warped_images[wi, :, :]) + + pp_wi.append(_img) + + for wi in pp_wi: + _img = np.where(wi > np.percentile(wi, clip_thresh), 1, 0) + + filtered_wi.append(_img) + + filtered_wi = np.stack(np.array(filtered_wi), axis=0) + + return filtered_wi + + +def getBrightPixelCount(filtered_warped_images): + + bright_pix_count = filtered_warped_images.sum(axis=0) + + return bright_pix_count + + +def getBarcodesFromPixelStack(codebook, pixel_stack, filtered_wi): + + codebook_bits = np.array(codebook.barcode_arrays) + nbrs = NearestNeighbors(n_neighbors=1, algorithm="ball_tree", p=1).fit( + codebook_bits + ) + pixel_stack = pixel_stack[np.newaxis, :, :] + bit_map = dict() + barcode_map = dict() + dist_map = dict() + bit_vector_map = dict() + print(f"Pixel Stack Shape={pixel_stack.shape}") + print(f"Filtered WI Shape={filtered_wi.shape}") + + bit_map[3] = np.multiply(pixel_stack == 3, filtered_wi) + bit_map[4] = np.multiply(pixel_stack == 4, filtered_wi) + bit_map[5] = np.multiply(pixel_stack == 5, filtered_wi) + print(f"Bitmap 5 Shape={bit_map[5].shape}") + bit_vector_map[3] = np.reshape(bit_map[3], (16, -1)).T + bit_vector_map[4] = np.reshape(bit_map[4], (16, -1)).T + bit_vector_map[5] = np.reshape(bit_map[5], (16, -1)).T + + # Look at distances for 3 pixel barcodes + dist_map[3], barcode_map[3] = nbrs.kneighbors(bit_vector_map[3]) + dist_map[4], barcode_map[4] = nbrs.kneighbors(bit_vector_map[4]) + dist_map[5], barcode_map[5] = nbrs.kneighbors(bit_vector_map[5]) + + return bit_map, bit_vector_map, dist_map, barcode_map, codebook_bits + + +def filterDetections(barcode_ids, distances, filter_val): + return barcode_ids[distances == filter_val] + + +def findErrorBits(bright_pix, codebook_bits, dist, barcode_ids, filter_val=0): + + barcode_subset = barcode_ids[dist == filter_val] + bright_pix_subset = bright_pix[np.where(dist == filter_val)[0], :] + codebook_subset = codebook_bits[barcode_subset] + error_bit_locs = np.argmax(np.abs(bright_pix_subset - codebook_subset), axis=1) + + return error_bit_locs + + +def performDumbExtraction(warped_images, codebook, clip_thresh=98.5): + transform = identity + + filtered_warped_images = transformWarpedImages( + warped_images, transform, clip_thresh + ) + + bright_pixel_count = getBrightPixelCount(filtered_warped_images) + + ( + bit_map, + bit_vector_map, + dist_map, + barcode_map, + codebook_bits, + ) = getBarcodesFromPixelStack(codebook, bright_pixel_count, filtered_warped_images) + + error_bit_map = dict() + error_bit_map[3] = findErrorBits( + bit_vector_map[3], codebook_bits, dist_map[3], barcode_map[3], filter_val=1 + ) + + error_bit_map[4] = findErrorBits( + bit_vector_map[4], codebook_bits, dist_map[4], barcode_map[4], filter_val=0 + ) + + error_bit_map[5] = findErrorBits( + bit_vector_map[5], codebook_bits, dist_map[5], barcode_map[5], filter_val=1 + ) + + detection_number_map = dict() + detection_number_map[3] = dist_map[3][dist_map[3] == 1].sum() + detection_number_map[4] = (1 + dist_map[4][dist_map[4] == 0]).sum() + detection_number_map[5] = dist_map[5][dist_map[5] == 1].sum() + + return ( + filtered_warped_images, + bright_pixel_count, + bit_map, + bit_vector_map, + dist_map, + barcode_map, + error_bit_map, + detection_number_map, + codebook_bits, + ) diff --git a/data/utils/imgproc.py b/data/utils/imgproc.py new file mode 100644 index 0000000000000000000000000000000000000000..34371b7e1cc2017566d4bd5d328272596d3ff0d4 --- /dev/null +++ b/data/utils/imgproc.py @@ -0,0 +1,218 @@ +import numpy as np +from functools import partial +from skimage import restoration,filters +import skimage.io as skio +from skimage.exposure import equalize_adapthist +import skimage +from skimage import registration +import scipy.ndimage as ndi +import pandas as pd +def read_table(file): + """ + Reads a file into a data frame based on it's extension + :param file: the file to read + :return: the pandas DataFrame + """ + ext = file.split(".")[-1] + if ext == "csv": + df = pd.read_csv(file) + elif ext == "tsv": + df = pd.read_csv(file, '\t') + elif ext in {"xls", "xlsx", "xlsm", "xlsb"}: + df = pd.read_excel(file) + else: + raise ValueError("Unexpected file extension") + return df + +def load_data_organization(data_org_file): + """Loads the data organization file as a list of dictionaries + based on the extension + + Args: + data_org_file: a path to a data organaization in the standard format + + Returns: + data_org: a list of ditionaries containing each imaging rounds information + """ + return read_table(data_org_file).to_dict("records") + +def warp_image(data_org, image_stack,bit_num): + + warped_image_stack = [] + for bit_num in range(bit_num): + data_org_row = data_org[bit_num] + wv_idx =int(data_org_row["frame"]) - 1 + ir_idx = int(data_org_row["imagingRound"]) + im = image_stack[:,:,wv_idx,ir_idx] + + warped_image_stack.append(im) + + warped_imgs = np.stack(warped_image_stack,axis=0) + + return warped_imgs + + +def register_stack(image_stack): + # image stack is a 4d numpy array + # (x,y,wv,ir) + # take out the 2nd wavelength [should be 561] and then register all the images with respect to the first imaging round + fiducial_wv = 1 # wavelength index for beads channel + ref_img = image_stack[:,:,fiducial_wv,0] + registered_images = image_stack.copy() + for ir_idx in range(1,image_stack.shape[3]): + img = image_stack[:,:,fiducial_wv,ir_idx] + shift, _, _ = registration.phase_cross_correlation( + ref_img, img, upsample_factor=100 + ) + for wv_idx in range(image_stack.shape[2]): + _img = image_stack[:,:,wv_idx,ir_idx] + registered_images[:,:,wv_idx,ir_idx] = ndi.shift(_img,shift) + return registered_images + +# Deconvolute Images +def _deconvolute(image_stack,out_file): + """ Deconvolutes image to sharpen features with filtering and richardson lucy restoration + Args: + raw_image: 2D image + dtype: the dtype of the raw_image being passed in + + Returns: + img: filtered and restored image. This image maintains the original dtype + """ + + _imgstack = np.load(image_stack) #(y,x,wv,ir) + d_imgstack = _imgstack.copy() + for iir in range(_imgstack.shape[3]): + for iwv in range(_imgstack.shape[2]): + if iwv==1: + continue + raw_image = _imgstack[:,:,iwv,iir] + + img = raw_image.astype("uint16") + # High pass filtering + filt = ( + filters.gaussian( + img, sigma=3, mode="nearest", truncate=2, preserve_range=True + ) + .round() + .astype("uint16") + ) + img = np.subtract(img, filt, where=img > filt, out=np.zeros_like(img)) + + # Point spread function deconvolution + psf = _gaussian_kernel((10, 10), 2) + + np.where(img == np.nan, 0, img) + img = restoration.richardson_lucy(img, psf, iterations=20, clip=False) + + # Low pass filtering + img = filters.gaussian( + img, + sigma=1, + output=None, + cval=0, + multichannel=False, + preserve_range=True, + truncate=4.0, + ) + + d_imgstack[:,:,iwv,iir] = img + + np.save(out_file,d_imgstack) + + +def _get_psf(sigma): + """ Gets a point spread function for a gaussian kernel + Args: + sigma: variance + + Returns: + gaussian_kernel + """ + kernel_size = int(2 * np.ceil(2 * sigma) + 1) + return _gaussian_kernel(shape=(kernel_size, kernel_size), sigma=sigma) + + +def _gaussian_kernel(shape=(3, 3), sigma=0.5): + """ Generates a gaussian kernel + Args: + shape: kernel dimensions + sigma: variance + + Returns: + kernel: a gaussian kernel + """ + m, n = [int((ss - 1.0) / 2.0) for ss in shape] + y, x = np.ogrid[-m : m + 1, -n : n + 1] + kernel = np.exp(-(x * x + y * y) / (2.0 * sigma * sigma)) + kernel[kernel < np.finfo(kernel.dtype).eps * kernel.max()] = 0 + sumh = kernel.sum() + if sumh != 0: + kernel /= sumh + return kernel + + + + +def deconvolve_img(img,psf=None): + + if psf is None: + psf = getPSF() + + #perform high pass filtering first + + + + + deconvolved_RL = restoration.richardson_lucy(img, psf, num_iter=10) + + return deconvolved_RL + +def equalize_hist(img): + + + clip_limit=0.05 + kernel_size = 10 + + _img = equalize_adapthist(img,kernel_size=kernel_size,clip_limit=clip_limit) + + return _img + +def getPSF(sig=None,size=5): + if sig is None: + sig = size/6 + + x,y = np.mgrid[-int(size//2):int(size//2), + -int(size//2):int(size//2)] + + + return gaussianPSF(x,y,sig) + + +def gaussianPSF(x,y,sig): + t = np.array([[x],[y]]) + + if not isinstance(sig,np.array): + sigma = np.array([[sig]]) + else: + sigma = sig + + if sigma.shape[0] != sigma.shape[1] or len(sigma.shape)!=2: + print('sigma is baddddd') + + t = -0.5*t.T@np.linalg.inv(sigma)@t + + return np.exp(t) + + + +def maskImages(d_img_file,out_mask,percentile=98.5): + d_imgstack = np.load(d_img_file) + mask_imgstack = np.zeros_like(d_imgstack) + for iir in range(d_imgstack.shape[2]): + for iwv in range(d_imgstack.shape[3]): + _img = d_imgstack[:,:,iir,iwv] + clip = np.percentile(_img,percentile) + mask_imgstack[:,:,iir,iwv] = np.where(_img>clip,1,0) + + np.save(out_mask,mask_imgstack) \ No newline at end of file