# Author: Benoit Lombardot, Scientific computing facility @ MPI-CBG  
# date: 2015-11-20


# This script is applying the transcript analysis (version 1.0.6 of the plugin) to a series of images

# load raw image from a user requested folder 
# raw images to process are expected to be in a <RAW-DATA> folder with the name <img_name>_<RAW-DATA>.tif
# the masks for cell and cell type are expected to be in a <MASKS> folder with the name <img_name>_<MASKS>.tif
# the suffix <MASKS> and <RAW-DATA> used can be changed if necessary in the input parameter


#################################################################
# class import
#################################################################

from fiji.util.gui import GenericDialogPlus
from ij import WindowManager
from ij.gui import WaitForUserDialog

from java.awt import Font
from java.lang import String
from java.io import File

from ij.io import DirectoryChooser;
from ij import IJ;
from ij.plugin import Duplicator;

#from mpicbg_scicomp.transcript_analysis.dev import cell_transcript_analysis_v3; 

import time;
import os;
from os import listdir, sep;
from os.path import isfile, join, exists, dirname;
from os import makedirs;
import sys

#################################################################
# user interface ################################################
version = "1.0.6" # define the plugin version that will be called
gd = GenericDialogPlus("Transcript Analysis ("+version+"-BATCH)");
		
title_font = Font("Arial", Font.BOLD, 16);
title2_font = Font("Arial", Font.BOLD, 12);
gd.addMessage("Transcripts analysis ("+version+"-BATCH)", title_font  );

# batch parameter
gd.addMessage("___________________________________________________\n" +
  		      "Data parameters:", title2_font );
gd.addDirectoryField("Source directory", ""); 
gd.addStringField("Mask suffix / subfolder", "MASKS");
gd.addStringField("Raw image suffix/ subfolder", "STITCHED");
gd.addStringField("Results subfolder", "RESULTS");
gd.addStringField("File extension", ".tif");
gd.addStringField("File pattern", "");

# nuclei segmentation parameters
gd.addMessage("___________________________________________________\n" +
					  "Nuclei segmentation parameters:", title2_font);
gd.addNumericField("Nuclei_channel",1, 0);
gd.addNumericField("nuclei_size (radius in pixel)", 50, 0);
gd.addNumericField("nuclei_threshold adjustment [0;2]", 1, 0);

# transcripts (i.e. tx) segmentation parameters
gd.addMessage("___________________________________________________\n" +
			  "Transcripts segmentation parameters:", title2_font);
gd.addStringField("Transcript_channel(s)", "2");
gd.addNumericField("Transcripts typical radius (in pixel)", 3, 0);
gd.addStringField("spot_minimum intensity", "300,100");
		
# foci segmentation parameters
gd.addMessage("___________________________________________________\n" +
			  "Foci segmentation parameters:", title2_font);
gd.addStringField("foci_intensity threshold adjustment", "1,1");                      
gd.addStringField("foci_volume threshold adjustment", "1,1" );
gd.addNumericField("Enlarge_nuclei_to_detect_foci (pixel)", 20, 0);     
gd.addCheckbox("Correct transcript over-segmentation", True);           
gd.addNumericField("Foci_maximum_radius_(in pixel)", 10, 0);            
		
# Output options :
gd.addMessage("___________________________________________________\n" +
			  "Misc. parameters:", title2_font);
gd.addCheckbox("Display_graph", False);
gd.addCheckbox("Save_graph to disk", True);
gd.addCheckbox("Display_result image", False);
gd.addCheckbox("Save_result image", True);
gd.addCheckbox("Display_transcripts_images", False);

gd.showDialog();
process = True
if gd.wasCanceled():
	IJ.log("Script was cancelled")
	process=False;
	#sys.exit()
	
# harvest parameters
base_directory = gd.getNextString(); # base directory containing the raw data and masks folders. the results folder will also be created there
masks_suffix   = gd.getNextString(); # use to determine masks folder name and file suffix
rawImg_suffix  = gd.getNextString(); 
results_suffix = gd.getNextString();
file_extension = gd.getNextString(); 
file_pattern   = gd.getNextString(); 

# nuclei parameters
nuclei_channel         	= gd.getNextNumber()
max_nuclei_size        	= gd.getNextNumber()
nuclei_thresh_adjust   	= gd.getNextNumber()

# transcript parameters
transcripts_channels   	= gd.getNextString(); # value must be in a table. multiple value can be set
tx_MaxRadius 		   	= gd.getNextNumber() 
transcripts_thresholds 	= gd.getNextString(); # value must be in a table. multiple value can be set

# foci detection parameters
foci_thresh_adjust_I    = gd.getNextString(); # value must be in a table. multiple value can be set
foci_thresh_adjust_Area = gd.getNextString(); # value must be in a table. multiple value can be set
NucEnlarge_foci 		= gd.getNextNumber() 
Correct_tx_overseg 		= gd.getNextBoolean()
foci_MaxRadius 			= gd.getNextNumber() 

# misc parameters
display_graph          = gd.getNextBoolean()
save_graph             = gd.getNextBoolean()
display_result         = gd.getNextBoolean()
save_result            = gd.getNextBoolean() # _cell file and _spot_ch<N> files
display_tx 			   = gd.getNextBoolean()






#################################################################
# process a dataset
#################################################################

def process_file(rawImg_path, masks_path, save_results_path):
	
	# load raw data
	imp_rawImg = IJ.openImage( rawImg_path );
	rawImg_name = imp_rawImg.getTitle();
	imp_rawImg.show()
	
	# load masks data
	masks_name = "-- None --"
	if isfile(masks_path) :
		imp_Masks = IJ.openImage( masks_path );
		masks_name = imp_Masks.getTitle();
		imp_Masks.show()

	correct = ""
	if Correct_tx_overseg:
		correct = "correct "

	display_graph_str = ""
	if display_graph:
		display_graph_str = "display_graph "

	display_result_str = ""
	if display_result:
		display_result_str = "display_result "

	save_graph_str = ""
	if save_graph:
		save_graph_str = "save_graph "

	save_result_str = ""
	if save_result:
		save_result_str = "save_result "
		
	display_tx_str = ""
	if display_tx:
		display_tx_str = "display_transcripts_images ";
	
	paramString = "input=["+rawImg_name+"] " +\
	"cell/tissue=["+masks_name+"] " +\
	"nuclei_channel="+str(nuclei_channel)+" "+\
	"nuclei_size="+str(max_nuclei_size)+" " +\
	"nuclei_threshold="+str(nuclei_thresh_adjust)+" " +\
	"transcript_channel(s)="+transcripts_channels+" " +\
	"transcripts="+str(tx_MaxRadius)+" "+\
	"spot_minimum="+transcripts_thresholds+" " +\
	"foci_intensity="+foci_thresh_adjust_I+" " +\
	"foci_volume="+foci_thresh_adjust_Area+" " +\
	"enlarge_nuclei_to_detect_foci="+str(NucEnlarge_foci)+" " +\
	correct +\
	"foci_maximum_radius_(in="+str(foci_MaxRadius)+" " +\
	display_graph_str +\
	save_graph_str +\
	display_result_str +\
	save_result_str +\
	display_tx_str +\
	"save=["+ save_results_path +"]"
	
	print paramString
	
	IJ.run(imp_rawImg,"Cell transcript analysis ("+version+")", paramString );
	

	imp_rawImg.hide()
	if not (masks_name == "-- None --") :
		imp_Masks.hide();
		
	return True;



#################################################################
# Main script
#################################################################


if process :
	IJ.log("\n\n=============================")
	IJ.log("====== Transcript Analysis ======\n")
	main_folder = base_directory;
	
	result_folder = join(main_folder, results_suffix) ;
	if not exists(result_folder ):
	    makedirs(result_folder);
	rawImg_path  = join(main_folder, rawImg_suffix);
	masks_path   = join(main_folder, masks_suffix);
	
	
	if exists(rawImg_path) :
		rawImg_files_list = [ f for f in listdir(rawImg_path) if (    isfile(join(rawImg_path,f)) \
																	& f.endswith(file_extension)  \
																	& (rawImg_suffix in f)        \
																	& (file_pattern in f)         \
																	)];	
		# loop on datasets
		count= 0;
		max_count = len(rawImg_files_list);
		for f_raw in rawImg_files_list :
			
			count = count +1;
			IJ.log("processing file "+f_raw+" ("+str(count)+"/"+str(max_count)+")")
	
			f_raw2      = join(rawImg_path , f_raw);
			f_prefix    = f_raw.split("_"+rawImg_suffix)[0];
			f_masks = join(masks_path , f_prefix +"_"+ masks_suffix + ".tif");
			result_folder2 = result_folder.replace("\\","\\\\")
			processed = process_file(f_raw2, f_masks, result_folder2)
			
	
	IJ.log("\n======== Script Finished ========")
	IJ.log("=============================\n")









