# Jeff Hardin, Dept. of Integrative B )logy
# Univ. of Wisconsin-Madison
# jdhardin@wisc.edu
# July 30, 2025

#Additional colors could be added via org.jfree.chart.ChartColor
#Green = #32a852
#Purple = #7132a8
#Dark red = #9C2005
#Dark brown = #754F04
#Light brown = #9C6905

#This script imports data from one or more CSV files in the form x[i],y[i] as paired columns
#using ImageJ's built-in support for importing CSV files in a ResultsTable
#and ImageJ's built-in Plot functions.

#Currently uses the hard-wired colors built into ImageJ's Plot class and a few hexadecimal colors.
#Use the PlotWindow "More >> " button to change range, line thickness, colors, etc.

#Using JFreeChart would allow export as an editable SVG file, but has less flexibiity
#in changing appearance after generating the graph

from org.jfree.data.statistics import Statistics
from javax.swing import JFrame  
import java.awt.Color as Color
from java.awt import Dimension, BasicStroke
import java.awt.Frame as Frame
import java.awt.Window as Window
from java.io import File as File
from java.lang import System as System
from ij import WindowManager as WindowManager
from ij.plugin.frame import RoiManager as RoiManager
from ij.process import ImageStatistics as ImageStatistics
from ij.measure import Measurements as Measurements
from ij import IJ as IJ
from ij.measure import CurveFitter as CurveFitter
from ij.gui import Plot as Plot
from ij.gui import PlotWindow as PlotWindow
from ij.gui import ImageWindow as ImageWindow
from ij.text import TextWindow
from ij.gui import GenericDialog
from ij import ImagePlus as ImagePlus
from ij.io import FileInfo as FileInfo
from ij.measure import ResultsTable as ResultsTable
from ij import WindowManager as WindowManager
import math
import os
from os import path, mkdir
import csv

#below from 
#https://stackoverflow.com/questions/736043/checking-if-a-string-can-be-converted-to-float-in-python
def isfloat(value):
  try:
    float(value)
    return True
  except ValueError:
    return False
    
def doPlot():
	k = len(listOfPaths)
	if (k < 2):
		IJ.showMessage("Incorrect data structure","This script required more than one dataset.")
		return None
	#Ask for options
	gd = GenericDialog("Options")
	gd.addCheckbox("Combine plots", True)
	gd.addCheckbox("Plot Y mean values", True)
	gd.addCheckbox("Show error bars", True)
	items = ["Std err", "Std dev"];
	gd.addRadioButtonGroup("Error Bars", items, 1, 2, "Std err");
	gd.addCheckbox("Curve fit means", True)
	gd.addChoice("Curve fitting method:", ["Single", "Double"], "Single")
	gd.addCheckbox("Force curve fit through origin for single exponential", True)
	gd.showDialog()	
	if gd.wasOKed():
		combinePlots = gd.getNextBoolean()
		plotMeans = gd.getNextBoolean()
		plotStdErrs = gd.getNextBoolean()
		errorBarType = gd.getNextRadioButton()
		fitMeans = gd.getNextBoolean()
		fitMethod = gd.getNextChoice()
		throughOrigin = gd.getNextBoolean()
	else: return None
		
	lineseparator = "\n"
	cellseparator = ","
	legendString = ""
	myTable = ResultsTable()
	#set the next to True so that we can throw NaN cells later
	myTable.setNaNEmptyCells(True)
	if (combinePlots):
		myPlot=Plot("Combined", "X", "Y")
		myPlot.setLineWidth(2)

	xMin = float()
	xMax = float()
	xMax = 0
	xMin = 0
	plotColor=[]
	plotColor = ("black", "red", "blue", "#32a852", "#7132a8", "#9C2005", "#754F04", "magenta", "darkGray", "gray", "lightGray", "green", "#9C6905", "cyan", "orange", "pink", "yellow");
	#Call below is a feature of Fiji/IJ2
	#See https://imagej.net/scripting/parameters
	#for i in range(0, k):
		#print(listOfPaths[i])

	for i in range(0, k):
		#read in FRAP curve data from CSV file
		#copies the whole file to an array of lines
		#have to type cast pathnames to Python str
		text_file = open(str(listOfPaths[i]), "r")		
		#read whole file to a string
		data = text_file.read()
		#close file
		text_file.close()		
		#separate into lines of text
		lines=data.split(lineseparator)
		numRows = len(lines)	
		# recreates the columns headers
		labels=lines[0].split(cellseparator)		
		#get total columns
		numCol = len(labels)
		#declare arrays to hold data points
		x1=[]
		y1=[]
		#IJ.open(str(listOfPaths[i]))
		with open(str(listOfPaths[i]), 'r') as read_obj:
			# pass the file object to reader() to get the reader object
			csv_reader = csv.reader(read_obj)
			# Iterate over each row in the csv using reader object
			header = next(csv_reader)
			for row in csv_reader:
			#need to add code to check for empty cells, since ImageJ
			#produces CSV files in which there can be unequal numbers of rows with empty cells
			#Jython interpreter crashes when trying to convert to float if cell is blank
			#ImageJ plot functions are savvy about blank cells, but this code isn't!
				if (isfloat(row[0])):
					x1.append(float(row[0]))
				if (isfloat(row[1])):
					y1.append(float(row[1]))
		
		#get min and mx for X axis
		if (min(x1) < xMin):
			xMin = min(x1)
		if (max(x1) > xMax):
			xMax = max(x1)

		#IJ.log("x1 length:")
		#IJ.log(str(len(x1)))
		#IJ.log("y1 length:")
		#IJ.log(str(len(y1)))

		#Use a Java method instead (need JVM 7+)
		file = File(str(listOfPaths[i]))
		#get file name using getName()
		filename = file.getName()
	
		#Now let's plot the XY data using ImageJ's Plot function
		if (combinePlots):
			if (i < len(plotColor)):
				colorString = plotColor[i]
			else:
				colorString = "black"
			myPlot.setColor(colorString)
			myPlot.setLineWidth(2.0)
			#Removes gridlines; delete if you like these...
			myPlot.setFormatFlags(0x330f)
			myPlot.add("Line",x1,y1)
			if (i == 0):
				legendString = legendString + File.getName(listOfPaths[i])
			else:
				legendString = legendString + "\t" + File.getName(listOfPaths[i])

		#create ResultTable for data
		for m in range(len(x1)):
			#IJ.log("m:")
			#IJ.log(str(m))
			#if first dataset, create new rows
			if (i == 0 ):
				myTable.incrementCounter()
				myTable.addValue(filename + "-x",x1[m])
				myTable.addValue(filename + "-y",y1[m])
			else:
				#myTable.setValue(filename + "-x",m,x1[m])
				myTable.setValue(filename + "-y",m,y1[m])

	#Calculate stats and graph mean + std err
	if (len(listOfPaths) > 1):
		yValues = []
		yMeans = []
		yStdDevs = []
		yMean = 0
		for j in range(len(x1)):
			for i in range(0, len(listOfPaths)):
				if (j == 0):
					yValues.append(myTable.getValueAsDouble(i+1,j))
				else:
					yValues[i] = myTable.getValueAsDouble(i+1,j)
			#Add columns for stats
			#print(yValues)
			myTable.setValue("Mean",j,Statistics.calculateMean(yValues))
			#Still need to add code to check for NaN if n = 2
			myTable.setValue("Std Dev",j,Statistics.getStdDev(yValues))
			myTable.setValue("Std Err",j,Statistics.getStdDev(yValues)/math.sqrt(len(listOfPaths)))

	myTable.show("Data")
	if (combinePlots):
		myPlot.show()
		myPlot.setLegend(legendString,Plot.AUTO_POSITION)
		myPlot.setLimitsToFit(True)
	#now graph the mean and std err
	if (plotMeans):
		#IJ.log("length of x1:")
		#IJ.log(str(len(x1)))
		myMeanPlot = Plot("Mean value", "X", "Y mean")
		myMeanPlot.setLineWidth(2)
		myMeanPlot.setColor("red")
		#Removes gridlines; delete if you like these...
		myMeanPlot.setFormatFlags(0x330f)
		#couldn't get myPlot.getColumn("Mean") to work, so do it manually
		ymean = []
		for i in range(len(x1)):
			ymean.append(myTable.getValue("Mean",i))
		myMeanPlot.add("Line",x1,ymean)
		legendString = "X vs. mean"
		if (plotStdErrs):
			if (errorBarType == "Std err"):
				legendString = "X vs. mean +/- SEM"
				yStdErr = []
				for i in range(len(x1)):
					yStdErr.append(myTable.getValue("Std Err",i))
					myMeanPlot.add("error bars", yStdErr)
			else:
				legendString = "X vs. mean +/- SD"
				yStdDev = []
				for i in range(len(x1)):
					yStdDev.append(myTable.getValue("Std Dev",i))
					myMeanPlot.add("error bars", yStdDev)		
		myMeanPlot.setLimitsToFit(True)
		myMeanPlot.setColor("black")
		myMeanPlot.setLegend(legendString,Plot.AUTO_POSITION)
		myMeanPlot.show()
		
		if (fitMeans):
			# Fitter
			yFit = []
			fitter = CurveFitter(x1, ymean)
			if fitMethod == "Single":
				if throughOrigin: 
					fitter.doFit(CurveFitter.EXP_RECOVERY_NOOFFSET)
				else:
					fitter.doFit(CurveFitter.EXP_RECOVERY)
				#myMeanPlot.add("fit", yStdErr)
				#fitter.plot
				param_values = fitter.getParams()
				for i in range(len(x1)):
					yFit.append( fitter.f( fitter.getParams(), x1[i]) )
					myTable.setValue("Fit",i,yFit[i])
				myMeanPlot.setColor("blue")
				myMeanPlot.add("Line",x1,yFit)
				myMeanPlot.setColor("black")
				myMeanPlot.setLegend(legendString + "\nFit",Plot.AUTO_POSITION)
				myMeanPlot.show()
				myTable.show("Data")
			else:
				eqn = "y = a*(1-exp(-b*x)) +c*(1-exp(-d*x)) + e"
				params = fitter.doCustomFit(eqn, None, False)
				for i in range(len(x1)):
					yFit.append( fitter.f( fitter.getParams(), x1[i]) )
					myTable.setValue("Fit",i,yFit[i])
				myMeanPlot.setColor("blue")
				myMeanPlot.add("Line",x1,yFit)
				myMeanPlot.setColor("black")
				myMeanPlot.setLegend(legendString + "\nFit",Plot.AUTO_POSITION)
				myMeanPlot.show()
				myTable.show("Data")
		
			#Output FRAP paramaters
			#need to fix this!
			time_units = "sec"
			myTextWindow = TextWindow("FRAP Results","",600,300)
			myTextWindow.append("Fit FRAP curve by " + fitter.getFormula() )
			param_values = fitter.getParams()
			if fitMethod == "Single":
				if throughOrigin:
					myTextWindow.append("Fit constrained through origin: TRUE")
				else:
					myTextWindow.append("Fit constrained through origin: FALSE")
				thalf = math.log(2) / param_values[1]
				mobile_fraction = param_values[0]
				str1 = ('Half-life = %.2f ' + time_units) % thalf
				myTextWindow.append( str1 )
				str2 = "Mobile fraction = %.1f %%" % (100 * mobile_fraction)
				myTextWindow.append( str2 )
				myTextWindow.append( "" )
				myTextWindow.append("*******Details********" + fitter.getResultString() )

			else:
				thalf1 = math.log(2) / param_values[1]
				thalf2 = math.log(2) / param_values[3]
				mobile_fraction = param_values[0] + param_values[2]
				str1 = ('Half-life #1= %.2f ' + time_units) % thalf1
				myTextWindow.append( str1 )
				str2 = ('Half-life #2= %.2f ' + time_units) % thalf2
				myTextWindow.append( str2 )
				str3 = "Mobile fraction = %.1f %%" % (100 * mobile_fraction)
				myTextWindow.append( str3 )
				myTextWindow.append( "" )
				myTextWindow.append("*******Details********" + fitter.getResultString() )

		
#main
#@ File[] listOfPaths (label="select files", style="files")
doPlot()