calculate.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. package utils
  2. import (
  3. "fmt"
  4. "github.com/gonum/stat"
  5. "github.com/shopspring/decimal"
  6. "math"
  7. "strings"
  8. )
  9. // Series is a container for a series of data
  10. type Series []Coordinate
  11. // Coordinate holds the data in a series
  12. type Coordinate struct {
  13. X, Y float64
  14. }
  15. // GetLinearResult 生成线性方程式
  16. func GetLinearResult(s []Coordinate) (gradient, intercept float64) {
  17. if len(s) <= 1 {
  18. return
  19. }
  20. // Placeholder for the math to be done
  21. var sum [5]float64
  22. // Loop over data keeping index in place
  23. i := 0
  24. for ; i < len(s); i++ {
  25. sum[0] += s[i].X
  26. sum[1] += s[i].Y
  27. sum[2] += s[i].X * s[i].X
  28. sum[3] += s[i].X * s[i].Y
  29. sum[4] += s[i].Y * s[i].Y
  30. }
  31. // Find gradient and intercept
  32. f := float64(i)
  33. gradient = (f*sum[3] - sum[0]*sum[1]) / (f*sum[2] - sum[0]*sum[0])
  34. intercept = (sum[1] / f) - (gradient * sum[0] / f)
  35. //fmt.Println("gradient:", gradient, ";intercept:", intercept)
  36. // Create the new regression series
  37. //for j := 0; j < len(s); j++ {
  38. // regressions = append(regressions, Coordinate{
  39. // X: s[j].X,
  40. // Y: s[j].X*gradient + intercept,
  41. // })
  42. //}
  43. return
  44. }
  45. // CalculateCorrelationByIntArr 相关性计算
  46. // 计算步骤
  47. // 1.分别计算两个序列的平均值Mx和My
  48. // 2.分别计算两个序列的标准偏差SDx和SDy => √{1/(n-1)*SUM[(Xi-Mx)²]}
  49. // 3.计算相关系数 => SUM[(Xi-Mx)*(Yi-My)]/[(N-1)(SDx*SDy)]
  50. func CalculateCorrelationByIntArr(xArr, yArr []float64) (ratio float64) {
  51. // 序列元素数要一致
  52. xLen := float64(len(xArr))
  53. yLen := float64(len(yArr))
  54. if xLen == 0 || xLen != yLen {
  55. return
  56. }
  57. // 计算Mx和My
  58. var Xa, Ya float64
  59. for i := range xArr {
  60. Xa += xArr[i]
  61. }
  62. Mx := Xa / xLen
  63. for i := range yArr {
  64. Ya += yArr[i]
  65. }
  66. My := Ya / yLen
  67. // 计算标准偏差SDx和SDy
  68. var Xb, Yb, SDx, SDy float64
  69. for i := range xArr {
  70. Xb += (xArr[i] - Mx) * (xArr[i] - Mx)
  71. }
  72. SDx = math.Sqrt(1 / (xLen - 1) * Xb)
  73. for i := range yArr {
  74. Yb += (yArr[i] - My) * (yArr[i] - My)
  75. }
  76. SDy = math.Sqrt(1 / (yLen - 1) * Yb)
  77. // 计算相关系数
  78. var Nume, Deno float64
  79. for i := 0; i < int(xLen); i++ {
  80. Nume += (xArr[i] - Mx) * (yArr[i] - My)
  81. }
  82. Deno = (xLen - 1) * (SDx * SDy)
  83. ratio = Nume / Deno
  84. if math.IsNaN(ratio) {
  85. ratio = 0
  86. }
  87. return
  88. }
  89. // ComputeCorrelation 通过一组数据获取相关系数R
  90. // 计算步骤
  91. // 1.分别计算两个序列的平均值Mx和My
  92. // 2.分别计算两个序列的标准偏差SDx和SDy => √{1/(n-1)*SUM[(Xi-Mx)²]}
  93. // 3.计算相关系数 => SUM[(Xi-Mx)*(Yi-My)]/[(N-1)(SDx*SDy)]
  94. func ComputeCorrelation(sList []Coordinate) (r float64) {
  95. var xBar, yBar float64
  96. lenSList := len(sList)
  97. // 必须两组数据及两组以上的数据才能计算
  98. if lenSList < 2 {
  99. return
  100. }
  101. decimalX := decimal.NewFromFloat(0)
  102. decimalY := decimal.NewFromFloat(0)
  103. // 计算两组数据X、Y的平均值
  104. for _, coordinate := range sList {
  105. decimalX = decimalX.Add(decimal.NewFromFloat(coordinate.X))
  106. decimalY = decimalY.Add(decimal.NewFromFloat(coordinate.Y))
  107. }
  108. xBar, _ = decimalX.Div(decimal.NewFromInt(int64(lenSList))).Round(4).Float64()
  109. yBar, _ = decimalY.Div(decimal.NewFromInt(int64(lenSList))).Round(4).Float64()
  110. //fmt.Println(xBar)
  111. //fmt.Println(yBar)
  112. varXDeci := decimal.NewFromFloat(0)
  113. varYDeci := decimal.NewFromFloat(0)
  114. ssrDeci := decimal.NewFromFloat(0)
  115. for _, coordinate := range sList {
  116. // 分别计算X、Y的实际数据与平均值的差值
  117. diffXXbarDeci := decimal.NewFromFloat(coordinate.X).Sub(decimal.NewFromFloat(xBar))
  118. diffYYbarDeci := decimal.NewFromFloat(coordinate.Y).Sub(decimal.NewFromFloat(yBar))
  119. ssrDeci = ssrDeci.Add(diffXXbarDeci.Mul(diffYYbarDeci))
  120. //fmt.Println("i:", i, ";diffXXbar:", diffXXbarDeci.String(), ";diffYYbar:", diffYYbarDeci.String(), ";ssr:", ssrDeci.String())
  121. varXDeci = varXDeci.Add(diffXXbarDeci.Mul(diffXXbarDeci))
  122. varYDeci = varYDeci.Add(diffYYbarDeci.Mul(diffYYbarDeci))
  123. //varY += diffYYbar ** 2
  124. }
  125. //当输入的两个数组完全相同时,计算相关系数会导致除以零的操作,从而产生 NaN(Not a Number)的结果。为了避免这种情况,可以在计算相关系数之前先进行一个判断,如果两个数组的标准差为零,则相关系数应为1
  126. if varXDeci.IsZero() && varYDeci.IsZero() {
  127. r = 1
  128. return
  129. }
  130. sqrtVal, _ := varXDeci.Mul(varYDeci).Round(4).Float64()
  131. //fmt.Println("sqrtVal:", sqrtVal)
  132. sst := math.Sqrt(sqrtVal) // 平方根
  133. //fmt.Println("sst:", sst)
  134. // 如果计算出来的平方根是0,那么就直接返回,因为0不能作为除数
  135. if sst == 0 {
  136. return
  137. }
  138. r, _ = ssrDeci.Div(decimal.NewFromFloat(sst)).Round(4).Float64()
  139. return
  140. }
  141. // CalculationDecisive 通过一组数据获取决定系数R2
  142. func CalculationDecisive(sList []Coordinate) (r2 float64) {
  143. r := ComputeCorrelation(sList)
  144. r2, _ = decimal.NewFromFloat(r).Mul(decimal.NewFromFloat(r)).Round(4).Float64()
  145. return
  146. }
  147. // CalculateStandardDeviation 计算标准差
  148. func CalculateStandardDeviation(data []float64) float64 {
  149. return stat.StdDev(data, nil)
  150. }
  151. func ReplaceFormula(valArr map[string]float64, formulaStr string) string {
  152. funMap := getFormulaMap()
  153. for k, v := range funMap {
  154. formulaStr = strings.Replace(formulaStr, k, v, -1)
  155. }
  156. replaceCount := 0
  157. for tag, val := range valArr {
  158. dvStr := fmt.Sprintf("%v", val)
  159. formulaStr = strings.Replace(formulaStr, tag, dvStr, -1)
  160. replaceCount++
  161. }
  162. for k, v := range funMap {
  163. formulaStr = strings.Replace(formulaStr, v, k, -1)
  164. }
  165. return formulaStr
  166. }
  167. // CellPosition
  168. // @Description: 单元格位置
  169. type CellPosition struct {
  170. Tag string
  171. Row int
  172. Value float64
  173. }
  174. // ReplaceFormulaByCellList
  175. // @Description: 根据单元格列表替换
  176. // @author: Roc
  177. // @datetime2023-11-14 16:16:12
  178. // @param cellList []CellPosition
  179. // @param formulaStr string
  180. // @return string
  181. func ReplaceFormulaByCellList(cellList []CellPosition, formulaStr string) string {
  182. funMap := getFormulaMap()
  183. for k, v := range funMap {
  184. formulaStr = strings.Replace(formulaStr, k, v, -1)
  185. }
  186. replaceCount := 0
  187. for _, cell := range cellList {
  188. dvStr := fmt.Sprintf("%v", cell.Value)
  189. formulaStr = strings.Replace(formulaStr, fmt.Sprint(cell.Tag, cell.Row), dvStr, -1)
  190. replaceCount++
  191. }
  192. for k, v := range funMap {
  193. formulaStr = strings.Replace(formulaStr, v, k, -1)
  194. }
  195. return formulaStr
  196. }
  197. func ReplaceFormulaByTagMap(valTagMap map[string]int, formulaStr string) string {
  198. funMap := getFormulaMap()
  199. for k, v := range funMap {
  200. formulaStr = strings.Replace(formulaStr, k, v, -1)
  201. }
  202. replaceCount := 0
  203. for tag, val := range valTagMap {
  204. dvStr := fmt.Sprintf("%v", val)
  205. formulaStr = strings.Replace(formulaStr, tag, dvStr, -1)
  206. replaceCount++
  207. }
  208. for k, v := range funMap {
  209. formulaStr = strings.Replace(formulaStr, v, k, -1)
  210. }
  211. return formulaStr
  212. }
  213. func getFormulaMap() map[string]string {
  214. funMap := make(map[string]string)
  215. funMap["MAX"] = "[@@]"
  216. funMap["MIN"] = "[@!]"
  217. funMap["ABS"] = "[@#]"
  218. funMap["CEIL"] = "[@$]"
  219. funMap["COS"] = "[@%]"
  220. funMap["FLOOR"] = "[@^]"
  221. funMap["MOD"] = "[@&]"
  222. funMap["POW"] = "[@*]"
  223. funMap["ROUND"] = "[@(]"
  224. return funMap
  225. }