#############################  Script-1 ##########################33

# This script multiplies the elements of chosen columns with a
# coefficient. This coeficient is obtained by dividing the sum of all 
# elements in a reference column selected by the user with another value 
# provided by the user.
# The resulting columns can either be appended to the current dataset,
# or can be written into a child data set created.
#
# In the first step, a reference column is chosen through user interface.
# In the second step, through another user interface, we can iput the scale factor
# for division, choose continuous columns for the operation and finally choose an option of
# either appending data to the current data set, or to create a child dataset.
#--------------------------------------------------------------------------------

from script.algorithm import *
from script.view import *
from script.dataset import *
from script.omega import createComponent, showDialog
from com.strandgenomics.cube.dataset import DatasetUtil
from java.lang import Float
from javax.swing import *
import string

#Prepares a list of continuous column names and categorical column
#  names in a given data set.
def getNameColumns(dset):
  col_Names=[]
  catCol_Names=[]
  for i in dset:
    col_Names.append(i.getName())
    if i.categorical!=1:
       catCol_Names.append(i.getName())
  return col_Names, catCol_Names




# In the data set 'dset' whose column names are in the list 'allColNames',
#   sum all the rows in a column whose name is same as 'refColName'.
def sumTheColumn(dset, allColNames, refColName):
    for i in range(len(allColNames)):
    	if allColNames[i]==refColName:
	    add=DatasetUtil.getSum(dset,i)
    return add




# Opens a dialog box 
def openDialogBox1(namesColumn):   
	p=createComponent(type="enum",id="name",description="Choose a reference column", options=namesColumn)
	res=showDialog(p)
  	return res



# Dialog box for selecting many columns.
def openDialogBox2(currentSum, dset):        
	text="sum of the requested column = "+str(currentSum)
	t=JTextArea(text)
	t.setBackground(JLabel().getBackground())
	p1=createComponent(type="ui",id="help",description="Run Message",component=t)
	p2=createComponent(type="string",id="num",description="Type the mean  value") 
	p3=createComponent(type="columnlist", id="chosenColumns", columnType="continuous",description="Multiple Column Chooser- Continuous columns", dataset=dset)
	p4=createComponent(type="Radio", id="name", description="Select a Function", options=["Append to Current Dataset","Create Child Dataset"])
	panel= createComponent(type="group", id="alltogether", description="Group",components=[p1,p2,p3,p4])
	result=showDialog(panel)
	exceptThrow=0
	if result!=None:
		try:	
			userSum = Float(p2.getValue()).floatValue()
		except:
			script.omega.error("Illegal entry: Non-zero float value expected for reference mean")
			exceptThrow=1
	return p2.getValue(), p3.getValue(), p4.getValue(), exceptThrow
	


# Multiplies each row of a set of columns with the coefficient "coeff".
# 'dset' is the data set in the node 'nod'. The list 'lis' has the column 
# numbers of chosen columns for this normalization. The resulting new columns can 
# either be appended to current dataset or can be put in a child data set.
def columnNormalize(lis, coeff, actionStr, dset, nod):
        lis=script.coercion.to_py(lis)
	rowInd=[i for i in range(dset.getRowCount())]
	colInd=[i for i in lis]
	if actionStr=="Create Child Dataset":
		cname=nod.addChildDatasetNode(name="Normalized", rowIndices=rowInd, columnIndices=colInd, setActive=1).getName()
		script.view.Table().show()
	for i in lis:
		tempCol=[]
		for j in range(dset.getRowCount()):
			tempCol.append(dset[i][j]*coeff)
                name="Normalised "+ str(d[i].getName())
		newCol=createFloatColumn(name, tempCol)
                if actionStr=="Append to Current Dataset":
			dset.addColumn(newCol)
                elif actionStr=="Create Child Dataset":
			d2=nod.getChildNode(cname).getDataset()
			d2.addColumn(newCol)
		      	
	return 1


def openDialogBox3(mstring, numCol):
	if mstring=="Append to Current Dataset":
		text=str(numCol)+" column(s) appended to the current data set"
	elif mstring=="Create Child Dataset":
		text="Creating Child dataset adding "+str(numCol)+" new columns"
	t=JTextArea(text)
	t.setBackground(JLabel().getBackground())
	p=createComponent(type="ui",id="help",description="Run 	Message",component=t)
	result=showDialog(p)
	return result
    

# Main script starts here.

#get current data set
node=script.project.getActiveDatasetNode()
d=node.getDataset()
 
# Get the column names--categorical and all column names.
[allColumnNames,catColumnNames]=getNameColumns(d)

# Get reference column name from dialog box
referenceColumnName=openDialogBox1(catColumnNames)

if referenceColumnName != None:

	# Sum the rows of reference column
	sumReferenceColumn = sumTheColumn(d,allColumnNames,referenceColumnName)

	# Get names of desired columns for normalization
	[userNumber, columnList, actionString, exception]=openDialogBox2(sumReferenceColumn,d)

	# Calculate the coefficient. Here, 'userNumber' is from dialog box.
	if exception==0:
		try:
			coefficient = sumReferenceColumn/float(userNumber)
			r = columnNormalize(columnList, coefficient, actionString, d, node)
		except:
			if columnList.getSize()==0:
				script.omega.error("No column selected")
			elif float(userNumber)==0.0:
				script.omega.error("The reference mean value is zero. Cannot get Coefficient")
	

	#Message box for information
	if exception==0 and columnList.getSize()>0 and float(userNumber)!=0.0:
		res=openDialogBox3(actionString, len(script.coercion.to_py(columnList)))

