# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0.  If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright 1997 - July 2008 CWI, August 2008 - 2016 MonetDB B.V.

function aggr.covar(e1:bat[:flt], e2:bat[:flt]):flt;
	e0:bat[:flt] := batcalc.*(e1,e2);
	s0:flt := aggr.sum(e0);
	s1:flt := aggr.sum(e1);
	s2:flt := aggr.sum(e2);
	v2:flt := calc.*(s1,s2);
	c := aggr.count(e1);
	n:flt := calc.flt(c);
	v3:flt := calc./(v2,n);
	v1:flt := calc.-(s0,v3);
	v:flt := calc./(v1,n);
	return v;
end aggr.covar;

function aggr.corr(e1:bat[:flt], e2:bat[:flt]):flt;
	cv:flt := aggr.covar(e1,e2);
	sd1 := aggr.stdev(e1);
	sd2 := aggr.stdev(e2);
	sd := calc.*(sd1,sd2);
	r := calc./(cv,sd);
	res := calc.flt(r);
	return res;
end aggr.corr;

function aggr.subcovar(e1:bat[:flt], e2:bat[:flt], g:bat[:oid], e:bat[:any_2], f:bit):bat[:flt];
	e0:bat[:flt] := batcalc.*(e1,e2);
	s0:bat[:flt] := aggr.subsum(e0,g,e,f,true);
	s1:bat[:flt] := aggr.subsum(e1,g,e,f,true);
	s2:bat[:flt] := aggr.subsum(e2,g,e,f,true);
	v2:bat[:flt] := batcalc.*(s1,s2);
	c := aggr.subcount(e1,g,e,f);
	n:bat[:flt] := batcalc.flt(c);
	v3:bat[:flt] := batcalc./(v2,n);
	v1:bat[:flt] := batcalc.-(s0,v3);
	v:bat[:flt] := batcalc./(v1,n);
	return v;
end aggr.subcovar;

function aggr.subcorr(e1:bat[:flt], e2:bat[:flt], g:bat[:oid],e:bat[:any_2], f:bit):bat[:flt];
	cv:bat[:flt] := aggr.subcovar(e1,e2,g,e,f);
	sd1 := aggr.substdevp(e1,g,e,f,true);
	sd2 := aggr.substdevp(e2,g,e,f,true);
	sd := batcalc.*(sd1,sd2);
	sdn := batcalc.==(sd,0:flt);
	sds := batcalc.ifthenelse(sdn,1:dbl,sd);
	r := batcalc./(cv,sds);
	res := batcalc.flt(r);
	return res;
end aggr.subcorr;
