1 // Copyright (C) The Lightning Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
13 "github.com/kshedden/statmodel/glm"
14 "github.com/kshedden/statmodel/statmodel"
15 "gonum.org/v1/gonum/stat"
16 "gonum.org/v1/gonum/stat/distuv"
19 var glmConfig = &glm.Config{
20 Family: glm.NewFamily(glm.BinomialFamily),
23 Log: log.New(io.Discard, "", 0),
26 func normalize(a []float64) {
27 mean, std := stat.MeanStdDev(a, nil)
29 a[i] = (x - mean) / std
33 // Logistic regression.
35 // onehot is the observed outcome, in same order as sampleInfo, but
36 // shorter because it only has entries for samples with
38 func pvalueGLM(sampleInfo []sampleInfo, onehot []bool, nPCA int) (p float64) {
39 pcaNames := make([]string, 0, nPCA)
40 data := make([][]statmodel.Dtype, 0, nPCA)
41 for pca := 0; pca < nPCA; pca++ {
42 series := make([]statmodel.Dtype, 0, len(sampleInfo))
43 for _, si := range sampleInfo {
45 series = append(series, si.pcaComponents[pca])
49 data = append(data, series)
50 pcaNames = append(pcaNames, fmt.Sprintf("pca%d", pca))
53 variant := make([]statmodel.Dtype, 0, len(sampleInfo))
54 outcome := make([]statmodel.Dtype, 0, len(sampleInfo))
55 constants := make([]statmodel.Dtype, 0, len(sampleInfo))
57 for _, si := range sampleInfo {
60 variant = append(variant, 1)
62 variant = append(variant, 0)
65 outcome = append(outcome, 1)
67 outcome = append(outcome, 0)
69 constants = append(constants, 1)
73 data = append(data, variant, outcome, constants)
74 dataset := statmodel.NewDataset(data, append(pcaNames, "variant", "outcome", "constants"))
78 // typically "matrix singular or near-singular with condition number +Inf"
82 model, err := glm.NewGLM(dataset, "outcome", append([]string{"constants"}, pcaNames...), glmConfig)
86 resultCov := model.Fit()
87 logCov := resultCov.LogLike()
88 model, err = glm.NewGLM(dataset, "outcome", append([]string{"constants", "variant"}, pcaNames...), glmConfig)
92 resultComp := model.Fit()
93 logComp := resultComp.LogLike()
94 dist := distuv.ChiSquared{K: 1}
95 return dist.Survival(-2 * (logCov - logComp))