Merge branch '19566-glm'
[lightning.git] / chisquare.go
1 // Copyright (C) The Lightning Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package lightning
6
7 import (
8         "gonum.org/v1/gonum/stat/distuv"
9 )
10
11 var chisquared = distuv.ChiSquared{K: 1}
12
13 func pvalue(x, y []bool) float64 {
14         var (
15                 obs, exp [2]float64
16                 sum      float64
17                 sz       = float64(len(y))
18         )
19         for i, yi := range y {
20                 if x[i] {
21                         if yi {
22                                 obs[0]++
23                         } else {
24                                 obs[1]++
25                         }
26                 }
27                 if yi {
28                         exp[0]++
29                 } else {
30                         exp[1]++
31                 }
32         }
33         if exp[0] == 0 || exp[1] == 0 || obs[0]+obs[1] == 0 {
34                 return 1
35         }
36         exp[0] = (obs[0] + obs[1]) * exp[0] / sz
37         exp[1] = (obs[0] + obs[1]) * exp[1] / sz
38         for i := range exp {
39                 d := obs[i] - exp[i]
40                 sum += d * d / exp[i]
41         }
42         return chisquared.Survival(sum)
43 }