dataFileName =  "/home/rusconi/devel/dataForMzml/db/frederic.halgand/171002_Myo_60-only-top-tic.db";
exportFileBaseName = "/tmp/171002_Myo_60-"

var zArray = [ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 , 17, 18, 19, 20, 21, 22 ];

// var theorMzArray = [ 3399.25, 2831.2, 2425.88, 2122.24, 1886.13, 1697.38, 1542.98, 1414.32, 1305.53, 1212.25, 1131.5, 1060.47, 998.1478, 942.8202, 893.2273, 848.6094, 808.3911, 771.4585 ];

// This new list because the 1060.47 m/z ratio is observed at 1060.77. This is
// the only peak that seems to be out of theoretical range.
var mzArray = [ 3399.25, 2831.2, 2425.88, 2122.24, 1886.13, 1697.38, 1542.98, 1414.32, 1305.53, 1212.25, 1131.5, 1060.47 + 0.3, 998.1478, 942.8202, 893.2273, 848.6094, 808.3911, 771.4585 ];

//var omegaRefArray = [ -1, -1, -1, -1, -1, -1, 2942, 3044, 3136, 3143, 3230, 3313, 3384, 3489, 3570, 3682, 3792, 3815 ];

// We need to use this, because the m/z data for the highest charged ions are
// unusable (m/z and dt). To eliminate these values, we set them to -1 here.
var omegaRefArray = [ -1, -1, -1, -1, -1, -1, 2942, 3044, 3136, 3143, 3230, 3313, 3384, -1, -1, -1, -1, -1 ];

var dataArray = [ ];

for(var iter = 0; iter < zArray.length; ++iter)
{
	var newObject = { "z" : zArray[iter], 
		"mz" : mzArray[iter], 
		"omegaRef" : omegaRefArray[iter],
		"dt" : -1,
		"dtPrime" : -1,
		"omegaPrime" : -1,
		"dtPrimePrime" : -1
	};

	dataArray.push(newObject);
}

//for(var iter = 0; iter < dataArray.length; ++iter)
//{

//print("z: " + dataArray[iter]["z"] + "\n" +
//"\tm/z: " + dataArray[iter]["mz"] + "\n" +
//"\tomegaRef: " + dataArray[iter]["omegaRef"]);
//}

var fwhm = 0.7;
var halfFwhm = fwhm/2;
var coeffLowMz = 1.41;
var coeffUpMz = 1.57;
var gasN2Mr = 28 // N_2
var myoglobinMr =16952;
var reducedMass = (myoglobinMr*gasN2Mr)/(myoglobinMr+gasN2Mr);

print("Reduced mass: " + reducedMass);

//////////////////// function linearRegression(xArray, yArray)
//////////////////// function linearRegression(xArray, yArray)
function linearRegression(xArray, yArray)
{
	var lr = {};
	var n = yArray.length;
	var sum_x = 0;
	var sum_y = 0;
	var sum_xy = 0;
	var sum_xx = 0;
	var sum_yy = 0;

	for(var i = 0; i < yArray.length; i++)
	{
		sum_x += xArray[i];
		sum_y += yArray[i];
		sum_xy += (xArray[i] * yArray[i]);
		sum_xx += (xArray[i] * xArray[i]);
		sum_yy += (yArray[i] * yArray[i]);
	} 

	lr['slope'] = (n * sum_xy - sum_x * sum_y) / (n*sum_xx - sum_x * sum_x);
	lr['intercept'] = (sum_y - lr.slope * sum_x)/n;
	lr['r2'] = Math.pow((n*sum_xy - sum_x*sum_y)/Math.sqrt((n*sum_xx-sum_x*sum_x)*(n*sum_yy-sum_y*sum_y)),2);

	return lr;
}


//////////////////// function sleep(milliseconds)
//////////////////// function sleep(milliseconds)
function sleep(milliseconds)
{
	var before = Date.now();

	for (var i = 0; i < 1e7; i++) 
	{
		var now = Date.now();

		if ((now - before) >= milliseconds)
		{
			break;
		}
		// Oddly enough, printing nothing is required; omitting the else statement
		// make the wait too short.
		else
			print("");
	}
}


//////////////////// function mostIntenseX(trace)
//////////////////// function mostIntenseX(trace)
function mostIntenseX(trace)
{
	if(Trace.prototype.isPrototypeOf(trace) == false)
		return;

	var greatestY = 0;
	var x = 0;

	for(var iter = 0; iter < trace.length; ++iter)
	{
		var dp = trace[iter];
		//print("Datapoint: " + dp.key + "/" + dp.val);

		if(dp.val > greatestY)
		{
			greatestY = dp.val;
			x = dp.key;
		}
	}

	//print("Returning x value: " + x);

	return x;
}

//////////////////// function dtPrimeCalc(dt, mz, coeff)
//////////////////// function dtPrimeCalc(dt, mz, coeff)
function dtPrimeCalc(dt, mz, coeff)
{
	var dtPrime = dt - (coeff * (Math.sqrt(mz)/1000));

	//print("for dt: " + dt + ", dtPrime: " + dtPrime);

	return dtPrime;
}


mainWindow.jsOpenMassSpectrometryFile(dataFileName);

ticChromPlotWidget0.jsIntegrateToMz(9.17,9.7);

var lnTdPrimeArray = [ ];
var lnOmegaPrimeArray = [ ];

print("Starting computation of dt', omega', ln(dt'), ln(omega')");

for(var iter = 0; iter < dataArray.length; ++iter)
{
	// We only work on the m/z peaks that are known to be usable. The ones that
	// are not usable have been marked -1 in the corresponding omegaRef slot.

	if(dataArray[iter]["omegaRef"] == -1)
		continue;

	var mz = dataArray[iter]["mz"];

	var start = mz - halfFwhm;
	var end = mz + halfFwhm;

	massSpecPlotWidget0.jsIntegrateToDt(start,end);

	print("Done the integration to dt.");
	print("Now exporting the dt spectrum to filename.");

	lastDriftSpecPlotWidget.exportPlotToFile(exportFileBaseName + 
		"-dtIntegration-" + 
		start + 
		"-" + 
		end + 
		".txt");

	var trace = new Trace();
	trace.initialize(lastDriftSpecPlotWidget.keys(), 
		lastDriftSpecPlotWidget.values());

	// At this point, find the dt value for which the Y intensity is the greatest
	// of all the drift spectrum.

	var dtValue = mostIntenseX(trace);

	//print("For x:" + chargeArray[iter] +
	//", dt value: " + dtValue);

	dataArray[iter]["dt"] = dtValue;

	if(dataArray[iter]["omegaRef"] == -1)
		continue;

	dataArray[iter]["dtPrime"] = dtPrimeCalc(dataArray[iter]["dt"], 
		dataArray[iter]["mz"], coeffUpMz);

	dataArray[iter]["omegaPrime"] = dataArray[iter]["omegaRef"] /
		(dataArray[iter]["z"] * Math.sqrt(1/(1/dataArray[iter]["mz"] + 
			1/gasN2Mr)));

	var lnTdPrime = Math.log(dataArray[iter]["dtPrime"]);
	lnTdPrimeArray.push(lnTdPrime);

	var lnOmegaPrime = Math.log(dataArray[iter]["omegaPrime"]);
	lnOmegaPrimeArray.push(lnOmegaPrime);

	//print("z: " + dataArray[iter]["z"] + "\n" +
	//"\tm/z: " + dataArray[iter]["mz"] + "\n" +
	//"\tomegaRef: " + dataArray[iter]["omegaRef"] +
	//"\tdt: " + dataArray[iter]["dt"] +
	//"\tdt': " + dataArray[iter]["dtPrime"] +
	//"\tomega': " + dataArray[iter]["omegaPrime"]);
}


// Now plot ln(td') = f(omegaPrime)

print("Plot of ln(td') = f(ln(omega')");
for(var iter = 0; iter < lnTdPrimeArray.length; ++iter)
{
	print(lnOmegaPrimeArray[iter] + "," + lnTdPrimeArray[iter]);
}

var regDataLnTdPrimeVsLnOmegaPrime = 
	linearRegression(lnOmegaPrimeArray, lnTdPrimeArray);

print("Linear regression data ln(dt') = f(ln(omega')):\n" +
"\tslope: "+ regDataLnTdPrimeVsLnOmegaPrime["slope"] + "\n" + 
	"\tintercept: " + regDataLnTdPrimeVsLnOmegaPrime ["intercept"] + "\n" +
	"\tr2: " + regDataLnTdPrimeVsLnOmegaPrime ["r2"] + "\n");

// At this point, we need to calculate the tdPrimePrime values:

var dtPrimePrimeArray = [ ];
var usedOmegaRefArray = [ ];

for(var iter = 0; iter < dataArray.length; ++iter)
{
	// Remember that there are some points that we cannot handle.

	if(dataArray[iter]["omegaRef"] == -1)
		continue;

	dataArray[iter]["dtPrimePrime"] = 
		Math.pow(dataArray[iter]["dtPrime"], 
			regDataLnTdPrimeVsLnOmegaPrime["slope"]) * 
		(dataArray[iter]["z"] / Math.sqrt(reducedMass));

	usedOmegaRefArray.push(dataArray[iter]["omegaRef"]);
	dtPrimePrimeArray.push(dataArray[iter]["dtPrimePrime"]);

	print("z: " + dataArray[iter]["z"] + "\n" +
		"\tm/z: " + dataArray[iter]["mz"] + "\n" +
		"\tomegaRef: " + dataArray[iter]["omegaRef"] +
		"\tdt: " + dataArray[iter]["dt"] +
		"\tdt': " + dataArray[iter]["dtPrime"] +
		"\tomega': " + dataArray[iter]["omegaPrime"] + 
		"\tdt'': " + dataArray[iter]["dtPrimePrime"]); 

	//print("the power is " +
		//Math.pow(dataArray[iter]["dtPrime"], 
			//regDataLnTdPrimeVsLnOmegaPrime["slope"]));

	//print("the z/sqrt(mu) is " +
		//(dataArray[iter]["z"] / Math.sqrt(reducedMass)));

	//print("the '' is " +
		//Math.pow(dataArray[iter]["dtPrime"], 
			//regDataLnTdPrimeVsLnOmegaPrime["slope"]) * 
		//(dataArray[iter]["z"] / Math.sqrt(reducedMass)));
}

print("Plot of dt'' = f(omegaRef)");

for(var iter = 0; iter < dtPrimePrimeArray.length; ++iter)
{
	print(usedOmegaRefArray[iter] + "," + dtPrimePrimeArray[iter]);
}

var regDataTdPrimePrimeVsOmegaRef = 
	linearRegression(usedOmegaRefArray, dtPrimePrimeArray);

print("Linear regression data dt'' = f(omega):\n" +
"\tslope: "+ regDataTdPrimePrimeVsOmegaRef["slope"] + "\n" + 
	"\tintercept: " + regDataTdPrimePrimeVsOmegaRef ["intercept"] + "\n" +
	"\tr2: " + regDataTdPrimePrimeVsOmegaRef ["r2"] + "\n");



