package utils

import "math"

// Series is a container for a series of data
type Series []Coordinate

// Coordinate holds the data in a series
type Coordinate struct {
	X, Y float64
}

// GetLinearResult 生成线性方程式
func GetLinearResult(s []Coordinate) (gradient, intercept float64) {
	if len(s) <= 1 {
		return
	}

	// Placeholder for the math to be done
	var sum [5]float64

	// Loop over data keeping index in place
	i := 0
	for ; i < len(s); i++ {
		sum[0] += s[i].X
		sum[1] += s[i].Y
		sum[2] += s[i].X * s[i].X
		sum[3] += s[i].X * s[i].Y
		sum[4] += s[i].Y * s[i].Y
	}

	// Find gradient and intercept
	f := float64(i)
	gradient = (f*sum[3] - sum[0]*sum[1]) / (f*sum[2] - sum[0]*sum[0])
	intercept = (sum[1] / f) - (gradient * sum[0] / f)

	//fmt.Println("gradient:", gradient, ";intercept:", intercept)
	// Create the new regression series
	//for j := 0; j < len(s); j++ {
	//	regressions = append(regressions, Coordinate{
	//		X: s[j].X,
	//		Y: s[j].X*gradient + intercept,
	//	})
	//}

	return
}

// CalculateCorrelationByIntArr 相关性计算
// 计算步骤
// 1.分别计算两个序列的平均值Mx和My
// 2.分别计算两个序列的标准偏差SDx和SDy	=> √{1/(n-1)*SUM[(Xi-Mx)²]}
// 3.计算相关系数	=> SUM[(Xi-Mx)*(Yi-My)]/[(N-1)(SDx*SDy)]
func CalculateCorrelationByIntArr(xArr, yArr []float64) (ratio float64) {
	// 序列元素数要一致
	xLen := float64(len(xArr))
	yLen := float64(len(yArr))
	if xLen == 0 || xLen != yLen {
		return
	}

	// 计算Mx和My
	var Xa, Ya float64
	for i := range xArr {
		Xa += xArr[i]
	}
	Mx := Xa / xLen
	for i := range yArr {
		Ya += yArr[i]
	}
	My := Ya / yLen

	// 计算标准偏差SDx和SDy
	var Xb, Yb, SDx, SDy float64
	for i := range xArr {
		Xb += (xArr[i] - Mx) * (xArr[i] - Mx)
	}
	SDx = math.Sqrt(1 / (xLen - 1) * Xb)
	for i := range yArr {
		Yb += (yArr[i] - My) * (yArr[i] - My)
	}
	SDy = math.Sqrt(1 / (yLen - 1) * Yb)

	// 计算相关系数
	var Nume, Deno float64
	for i := 0; i < int(xLen); i++ {
		Nume += (xArr[i] - Mx) * (yArr[i] - My)
	}
	Deno = (xLen - 1) * (SDx * SDy)
	ratio = Nume / Deno
	if math.IsNaN(ratio) {
		ratio = 0
	}
	return
}
