
/****************************************************
ViewResults LUNCHER
****************************************************/
class ViewResultsluncher: MSA112_UIFrame
{
number sparsity
number maxLoadings
number ScoresCubed

string MSAlabel
number WaitingID

TagGroup CreateHead(object self)
	{
		TagGroup Upper = DLGCreateDialog("display results")
		Upper.DLGTableLayout(3,1,0)
	Upper.DLGAddElement(DLGCreateLabel(""+MSA112_Version()+"    "))
	Upper.DLGAddElement(self.InfoButton(20,210))	
	Upper.DLGAddElement(self.settingsButton(20,210,"Settings").DLGanchor("East"))
		TagGroup Lower = DLGCreatedialog("")
		Lower.DLGTableLayout(2,1,0)
	Lower.DLGAddElement(DLGcreateLabel("                   ").DLGAnchor("East").DLGIdentifier("Message"))
	Lower.DLGAddElement(DLGcreateLabel("hold ALT for info").DLGAnchor("East"))
	
	TagGroup Dialog2 = DLGCreateDialog("display results")
	Dialog2.DLGTableLayout(3,1,0)
	
	Dialog2.DLGAddElement(DLGCreateLabel("cluster"))
	Dialog2.DLGAddElement(DLGCreateIntegerField(0,4).DLGIdentifier("cluster").DLGanchor("West"))
		TagGroup Items
		TagGroup Meth = DLGcreateChoice(Items,0).DLGIdentifier("Method")
		Items.DLGaddPopupItemEntry("PCA",1)
		Items.DLGaddPopupItemEntry("ICA",2)
		Items.DLGaddPopupItemEntry("varimax",3)
		Items.DLGaddPopupItemEntry("free",4)

	Dialog2.DLGAddElement(Meth)

	TagGroup Dialog = DLGCreateDialog("display results")
	Dialog.DLGAddElement(Upper)
	Dialog.DLGAddElement(Lower)	
	Dialog.DLGAddElement(Dialog2)
		
	return Dialog
	}

string GetMethod(object self,number pos)
	{
	if(pos==0) return "PCA"
	if(pos==1) return "ICA"
	if(pos==2) return "VRM"
	if(pos==3) return "free"
	}
	
TagGroup Create_CABox(object self)
	{
	TagGroup Dialog = DLGCreateBox("View results")
	
	Dialog.DLGTableLayout(3,3,0)
	
	Dialog.DLGAddElement(DLGCreatePushButton("plot X-Y","PlotXY").DLGIdentifier("PlotScatter").DLGanchor("East"))	
	Dialog.DLGAddElement(DLGCreateIntegerField(1,5).DLGIdentifier("compF").DLGanchor("West"))
	Dialog.DLGAddElement(DLGCreateIntegerField(2,5).DLGIdentifier("compS").DLGanchor("West"))

	Dialog.DLGAddElement(DLGCreatePushButton("loadings","ShowLoadings").DLGanchor("East"))	
	Dialog.DLGAddElement(DLGCreateIntegerField(1,5).DLGIdentifier("IniCompL").DLGanchor("West"))
	Dialog.DLGAddElement(DLGCreateIntegerField(5,5).DLGIdentifier("FinCompL").DLGanchor("West"))

	Dialog.DLGAddElement(DLGCreatePushButton("  scores","ShowScores").DLGIdentifier("Scores").DLGanchor("East"))	
	Dialog.DLGAddElement(DLGCreateIntegerField(1,5).DLGIdentifier("IniCompS").DLGanchor("West"))
	Dialog.DLGAddElement(DLGCreateIntegerField(5,5).DLGIdentifier("FinCompS").DLGanchor("West"))
		
	return Dialog
	}

TagGroup Create_VarianceDialog(object self)
	{
	TagGroup Dialog = DLGCreateDialog("")	
	Dialog.DLGTableLayout(2,2,0)
	
	Dialog.DLGAddElement(DLGCreatePushButton("variance ","ShowVariance").DLGanchor("West"))	
	Dialog.DLGAddElement(DLGCreatePushButton("anisotropy","ShowAnisotropy").DLGanchor("West"))	
	Dialog.DLGAddElement(DLGCreatePushButton(" kurtosis ","ShowKurtosis").DLGanchor("West"))	
	Dialog.DLGAddElement(DLGCreatePushButton("get iterations","ShowItterations"))	
	return Dialog
	}
		
TagGroup CreateAllBoxes(object self)
	{
	TagGroup Dialog = DLGCreatedialog("")

	Dialog.DLGAddElement(self.CreateHead())
	Dialog.DLGAddElement(self.Create_CABox())
	Dialog.DLGAddElement(self.Create_VarianceDialog())
		
	return Dialog
	}
			
object init(object self,string Package,string Name,string MSAlabelP)
	{
	MSAlabel = MSAlabelP
	
	self.MSA112_initUIFrame(self.CreateAllBoxes(),Package,Name)	
	
	sparsity = self.MSA112P_sparsity()
	maxLoadings = self.MSA112P_maxLoadings()
	ScoresCubed = self.MSA112P_ScoresCubed()
	
	MSA112_reset()
		
	return self
	}

void CloseUIFrame(object self)
	{
	//add some actions if neccesary
	}

/*********************Setting****************************/
void Settings(object self)
	{
	number NumberLines = 3		//number of adjusted parameters
	TagGroup SettingList = DLGCreateBox("Settings").DLGTableLayout(1,NumberLines,1)
	
	taggroup tg1 =	self.AddSettingsLine_Int(SettingList,self.MSA112P_sparsity(),6)
	taggroup tg2 =	self.AddSettingsLine_Int(SettingList,self.MSA112P_maxLoadings(),4)
	taggroup tg3 =	self.AddSettingsLine_Check(SettingList,self.MSA112P_ScoresCubed())

	MSA112_reset()
	
	object SettingsFrame = Alloc(UIframe).init(SettingList)
	if(SettingsFrame.Pose())
		{
		sparsity = self.SettingNumberParameter(tg1)
		maxLoadings = self.SettingNumberParameter(tg2)
		ScoresCubed = self.SettingNumberParameter(tg3)
		}
	}

void PlotXY(object self)
	{
	self.MSA112_Info("show X-Y",-10,110,\
	"show scatter plot"+\
	"\nfor two indicated"+\
	"\ncomponents"+\
	"\nfrom front-most" +\
	"\nMSA container")
	
	string method = self.GetMethod(self.LookUpElement("Method").DLGgetValue())
	number First = self.LookUpElement("compF").DLGgetValue()
	number Second = self.LookUpElement("compS").DLGgetValue()
	number CurrCluster = self.LookUpElement("cluster").DLGgetValue()	
//result("\nXY plot "+F+ "-"+S+" current cluseter "+currCluster)

	image MSAimage := getFrontImage()
	
	//check if MSA matrix
	TagGroup MatrixTags = MSA112_GetMatrixTags(MSAimage,0)
	if(!MatrixTags.TagGroupIsValid()) exit(0)

	//check if PCA components extracted
	number CompN
	number check = MSA112_CheckNumberOfComponents(CurrCluster,CompN,MatrixTags,Method)
	if(check==0) exit(0)
	if(check==(-1))
		{
			TagGroup ConfirmTags = DLGCreatedialog("")
			ConfirmTags.DLGAddElement(DLGcreateLabel("Data are clustered"))	
			TagGroup ColorBox =DLGCreateCheckBox("plot clusters colored",1)
			ConfirmTags.DLGAddElement(ColorBox)
		object ConfirmFrame = alloc(UIFrame).init(ConfirmTags)
		if(!pose(ConfirmFrame)) throw("")
		if(DLGGetValue(ColorBox)) currCluster =(-1)
		else currCluster =0
		}
	
	image scatter :=MSA112_PlotXY(MSAimage,currCluster,Method,First,Second,sparsity) //plot 0-cluster in color
	scatter.showimage()
	
	}
		
	
void ShowLoadings(object self,string Method)
	{
	self.MSA112_Info("loadings",10,120,\
	"show loadings"+\
	"\nof components"+\
	"\nin the indicated"+\
	"\nrange of indexes"+\
	"\nfrom front-most" +\
	"\nMSA container")
	
	number IniComp = self.LookUpElement("IniCompL").DLGgetValue()
	number FinComp = self.LookUpElement("FinCompL").DLGgetValue()	
	if((FinComp-IniComp)>=maxLoadings) FinComp = IniComp + maxLoadings-1
	image MSAimage := getFrontImage()

	string DataName = MSAimage.getName()
	TagGroup MatrixTags = MSA112_GetMatrixTags(MSAimage,0)
	if(!MatrixTags.TagGroupIsValid()) exit(0)
	
	
	number CurrCluster = self.LookUpElement("cluster").DLGgetValue()
	number CompN
	if(!MSA112_CheckNumberOfComponents(CurrCluster,CompN,MatrixTags,Method)) exit(0)
	
	if(!MSA112_CheckValidityOfComponents(IniComp,FinComp,CompN,CurrCluster)) exit(0)
	if(IniComp>FinComp) Throw("First component must be not greater then Last one !!")
	
	image AverSpec := MSA112_GetAverageSpectrum(MatrixTags,CurrCluster)
	image Pall = MSA112_GetLoadings(MatrixTags,Method,CurrCluster)
	image Components := MSA112_GetComponents(MatrixTags,Method,CurrCluster) //might not exist

	DataName = left(DataName,len(DataName)-4)	//remove MSA
	MSA112_DisplayLoads(AverSpec,Pall,IniComp,FinComp,DataName+" LOAD("+CurrCluster+")",Method,Components)
	}
	
void ShowLoadings(object self) 
	{
	string method = self.GetMethod(self.LookUpElement("Method").DLGgetValue())
//result("\n"+method)
	self.ShowLoadings(method)
	}


void ShowAllScores(object self)
	{
	string method = self.GetMethod(self.LookUpElement("Method").DLGgetValue())
	number CurrCluster = self.LookUpElement("cluster").DLGgetValue()	
	number IniComp = self.LookUpElement("IniCompS").DLGgetValue()
	number FinComp = self.LookUpElement("FinCompS").DLGgetValue()	
	
	image MSAimage := getFrontImage()
	string DataName = MSAimage.getName()
	TagGroup MatrixTags = MSA112_GetMatrixTags(MSAimage,0)
	if(!MatrixTags.TagGroupIsValid()) {self.EndThread("Scores",WaitingID);exit(0);}
	
	number width,height
	MatrixTags.MSA112_GetSIWidthHeight(width,height)
	
	number scaleX,scaleY,originX,originY
	string unitX,unitY
	MatrixTags.MSA112_GetCalibration(scaleX,originX,unitX,"X")
	MatrixTags.MSA112_GetCalibration(scaleY,originY,unitY,"Y")

	number Points =MatrixTags.MSA112_GetNumberPoints()
	
	number CompN
	if(!MSA112_CheckNumberOfComponents(CurrCluster,CompN,MatrixTags,Method)) {self.EndThread("Scores",WaitingID);exit(0);}

result("\nwidth "+width+" height "+height+" "+CompN+" components, take "+IniComp+"-"+FinComp)

	if(!MSA112_CheckValidityOfComponents(IniComp,FinComp,CompN,CurrCluster)) {self.EndThread("Scores",WaitingID);exit(0);}
	if(IniComp>FinComp) Throw("First component must be not greater than Last one !!")

	image Tall:= MSA112_GetScores(MatrixTags,Method,CurrCluster)
	//Tall.showimage()
	
	//tune clustering
	image RTall
	if(currCluster!=0) RTall = MSA112_ProjectClusteredScore(MatrixTags,Tall,currCluster)
	else RTall = Tall
	
	DataName = left(DataName,len(DataName)-4)	//remove MSA
	
	//set out-clusterPixels
	if(currCluster!=0) RTall = MSA112_SetOutClusterPixels(MatrixTags,RTall,currCluster)
	
	//convert to cube
	number numberComp = FinComp-IniComp+1
	image scoreCube := realimage(DataName+" SCOR("+CurrCluster+") "+Method,4,width,height,NumberComp)
	number compSlice
	for(number comp=IniComp;comp<=FinComp;comp++)
		{	
		scoreCube[0,0,compSlice,width,height,compSlice+1] = RTall[0,comp-1,Points,comp].MSA112_ConvertColumnTo2D(width,height)
		compSlice++
		}
	
	scoreCube.ImageSetDimensionCalibration(0,OriginX,ScaleX,unitX,1)	
	scoreCube.ImageSetDimensionCalibration(1,OriginY,ScaleY,unitY,1)	
		
	if(ScoresCubed==0) for(number j=0;j<NumberComp;j++)
		{	
		image Score = scoreCube[0,0,j,width,height,j+1]
		score.ImageSetDimensionCalibration(0,OriginX,ScaleX,unitX,1)	
		score.ImageSetDimensionCalibration(1,OriginY,ScaleY,unitY,1)
		score.ImageSetName(DataName+" SCOR("+CurrCluster+") "+Method+" "+(iniComp+j))
		score.showimage()
		}
	else {scoreCube.showimage();}
	
	self.EndThread("Scores",WaitingID)
	}

void ShowScores(object self) 
	{
	self.MSA112_Info("scores",10,140,\
	"show scores"+\
	"\nof components"+\
	"\nin the indicated"+\
	"\nrange of indexes"+\
	"\nfrom front-most" +\
	"\nMSA container")
	
	WaitingID = self.StartThreadFromDLG("ShowAllScores","Scores")	
	}
	
void EigenValues(object self,string Method,string ValName)
	{
	image MSAimage := getFrontImage()
	string DataName = MSAimage.getName()
	TagGroup MatrixTags = MSA112_GetMatrixTags(MSAimage,0)
	if(!MatrixTags.TagGroupIsValid()) exit(0)
	
	number CurrCluster = self.LookUpElement("cluster").DLGgetValue()
	number CompN
	if(!MSA112_CheckNumberOfComponents(CurrCluster,CompN,MatrixTags,Method))  exit(0)

	string 	clusterLabel = MSA112_GetClusterLabel(currCluster)

	image Values 

		Values :=MatrixTags.MSA112_GetEigenValues(ValName,currCluster,Method)
		
		if(ValName == "Variance") Values = log(Values)
//result("\n#"+ClusterLabel+":"+Method+":Eigenvalues")

	image Components := integerImage("components",1,0,1,CompN+1)
	MatrixTags.TagGroupGetTagAsArray(ClusterLabel+":"+Method+":Components",Components)
		
 	MSA112_DisplayEigenValues(Values,"Cluster "+CurrCluster+" "+ValName,Method,Components)
	}
	
void ShowVariance(object self)
	{
	self.MSA112_Info("variance",10,200,\
	"show screeplot"+\
	"\nof variances"+\
	"\nfor all extracted"+\
	"\ncomponents"+\
	"\nfrom front-most" +\
	"\nMSA container")
	
	string method = self.GetMethod(self.LookUpElement("Method").DLGgetValue())
	string ValName = "Variance"
	self.EigenValues(Method,ValName)
	}

void ShowKurtosis(object self)
	{	
	self.MSA112_Info("kurtosis",10,220,\
	"show plot of"+\
	"\nkurtosis values"+\
	"\nfor all extracted"+\
	"\ncomponents"+\
	"\nfrom front-most" +\
	"\nMSA container")
	
	string method = self.GetMethod(self.LookUpElement("Method").DLGgetValue())
	string ValName = "Kurtosis"
	self.EigenValues(Method,ValName)
	}


void ShowAnisotropy(object self)
	{	
	self.MSA112_Info("anisotropy",330,200,\
	"show plot of"+\
	"\nanisotropy values"+\
	"\nfor all extracted"+\
	"\ncomponents"+\
	"\nfrom front-most" +\
	"\nMSA container")
	
	}
	
void DisplayItterations(object self,image Itterated,image itterations,string Method)
{
number CompN,maxIt
Itterated.getSize(CompN,maxIt)
maxIt -=1	//first pixel for specs

number maxIter = max(itterations)
if(maxIter>maxIt) throw("wrong max iteration input !!")

image Evolution := realimage("",4,maxIt+1,1)

imagedisplay imdisp
Evolution.setName(Itterated.getName()+" iterations")
Evolution.ImagesetDimensionCalibration(0,-0.5,1,"iterations",1)
Evolution.showimage()
imdisp = ImageGetImageDisplay(Evolution,0)
ImageDisplaySetSliceLabelByID(imdisp,ImageDisplayGetSliceIDByIndex(imdisp,0)," ")
for(number i=0;i<CompN;i++)
	{
	number IterN = Itterations.getPixel(i,0)
	if(IterN>1)
		{
		image current = MatrixTranspose(Itterated[1,i,IterN+1,i+1])
		imdisp.imageDisplayAddImage(current,Method+" "+(i+1))
		}
	}
imdisp.LinePlotImageDisplaySetLegendShown(1)
}
	
void ShowItterations(object self,string Method)
	{
	self.MSA112_Info("get iterations",350,200,\
	"show available"+\
	"\ninformation about"+\
	"\niterations to"+\
	"\nobtain components"+\
	"\nfrom front-most" +\
	"\nMSA container")
	
	if(Method=="free") throw("free rotation does not involve iterations")
	
	number CurrCluster = self.LookUpElement("cluster").DLGgetValue()
	string ClusterLabel = MSA112_GetClusterLabel(currCluster)	
	image MSAimage := getFrontImage()
	string DataName = MSAimage.getName()
	DataName = left(DataName,len(DataName)-4)	//remove MSA
	TagGroup MatrixTags = MSA112_GetMatrixTags(MSAimage,0)
	if(!MatrixTags.TagGroupIsValid()) exit(0)	

	string ValueName
	if(Method=="PCA") ValueName = "Scree Plot"
	if(Method=="ICA") ValueName = "Kurtosis"	
	
	image deviaAll :=MatrixTags.MSA112_getImageFromTags(ClusterLabel+":"+Method+":Precisions")
	image VsAll :=MatrixTags.MSA112_getImageFromTags(ClusterLabel+":"+Method+":Valuesflow")
	image SpikesAll :=MatrixTags.MSA112_getImageFromTags(ClusterLabel+":"+Method+":Outliers")
	image Itterations :=MatrixTags.MSA112_getImageFromTags(ClusterLabel+":"+Method+":Iterations")
	
	if(deviaAll.ImageIsValid()) 
		{
		deviaAll.setName(DataName+" ("+CurrCluster+") Precisions")
		self.DisplayItterations(deviaAll,Itterations,Method)
		}
		
	if(VsAll.ImageIsValid()) 
		{
		VsAll.setName(DataName+" ("+CurrCluster+") "+ValueName)
		self.DisplayItterations(VsAll,Itterations,Method)		
		}
		
	if(SpikesAll.ImageIsValid()) 
		{
		SpikesAll.setName(DataName+" ("+CurrCluster+") outliers")
		number spikesCode 
		if(spikesAll.ImageIsValid()) spikesCode= spikesAll.getPixel(0,0)
		if(spikesCode>0) self.DisplayItterations(SpikesAll,Itterations,Method)
		}
		
	if(Itterations.ImageIsValid()) 
		{
		Itterations.setName(DataName+" ("+CurrCluster+") number of iterations")
		Itterations.ImagesetDimensionCalibration(0,-0.5,1,"components",1)
		Itterations.showimage()
		}
	
	}
	
void ShowItterations(object self)
	{
	string method = self.GetMethod(self.LookUpElement("Method").DLGgetValue())
	self.ShowItterations(method)
	}

}

void createAll()
{
alloc(ViewResultsluncher).init(MSA112_MSApath(),"MSA view results",MSA112_Label()) 

}

createAll()
