├── LICENSE ├── Readme.md ├── dbscan └── dbscan.go ├── dsp.go ├── dwt ├── dwt.go └── dwt_test.go ├── go.mod ├── go.sum ├── peaks └── peaks.go ├── ppeaks └── ppeaks.go └── wavread.go /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | # Package godsp 2 | 3 | Package godsp is a Go package developed to support some basic signal processing functions using the discrete wavelet transform (DWT). 4 | 5 | ## Packages 6 | 7 | - **godsp**: General functions on vectors or sets of vectors. 8 | - **godsp/dbscan**: Implementation of DBSCAN (https://en.wikipedia.org/wiki/DBSCAN) to cluster histogram bins. 9 | - **godsp/peaks**: Efficient peak detection for time series 10 | - **godsp/ppeaks**: Peak detection on the basis of persistent homology: 11 | [https://www.sthu.org/blog/13-perstopology-peakdetection/index.html](https://www.sthu.org/blog/13-perstopology-peakdetection/index.html). 12 | - **godsp/dwt**: Lifting implementation of the discrete wavelet transform using the Daubechies 4 wavelet. See: 13 | 14 | Ripples in Mathematics. The Discrete Wavelet Transform. 15 | A. Jensen and A. la Cour-Harbo 16 | Springer 2001 17 | Section 3.4 18 | 19 | ## Installation 20 | 21 | $ go get github.com/goccmack/godsp 22 | -------------------------------------------------------------------------------- /dbscan/dbscan.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 Marius Ackerman 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | /* 16 | Package dbscan implements the DBSCAN clustering algorithm 17 | (https://en.wikipedia.org/wiki/DBSCAN) 18 | */ 19 | package dbscan 20 | 21 | import ( 22 | "bytes" 23 | "fmt" 24 | "sort" 25 | 26 | "github.com/goccmack/goutil/ioutil" 27 | ) 28 | 29 | const ( 30 | noise = -1 31 | undefined = 0 32 | ) 33 | 34 | type Cluster struct { 35 | Min, Max int 36 | } 37 | 38 | /* 39 | Histogram clusters the bins of a histogram `h`. 40 | */ 41 | func Histogram(h []int, eps, minPts int) []*Cluster { 42 | clusters := make([]int, len(h)) 43 | C := 0 /* Cluster counter */ 44 | for p := range h { 45 | if h[p] <= 0 { 46 | continue 47 | } 48 | if clusters[p] != undefined { /* Previously processed in inner loop */ 49 | continue 50 | } 51 | N, S := getNeighbours(h, p, eps) /* Find neighbors */ 52 | if len(N) < minPts { /* Density check */ 53 | clusters[p] = noise /* Label as noise */ 54 | continue 55 | } 56 | C = C + 1 /* next cluster label */ 57 | clusters[p] = C /* Label initial point */ 58 | for _, q := range S { /* Process every seed point */ 59 | if clusters[q] == noise { /* Change noise to border point */ 60 | clusters[q] = C 61 | } 62 | if clusters[q] != undefined { /* Previously processed */ 63 | continue 64 | } 65 | clusters[q] = C /* Label neighbor */ 66 | N, _ := getNeighbours(h, q, eps) /* Find neighbors */ 67 | if len(N) >= minPts { /* Density check */ 68 | for _, n := range N { /* Add new neighbors to seed set */ 69 | S = append(S, n) 70 | } 71 | } 72 | } 73 | } 74 | return getClusters(clusters) 75 | } 76 | 77 | func getClusters(cs []int) (clusters []*Cluster) { 78 | cmap := make(map[int]*Cluster) 79 | for i, c := range cs { 80 | if c > 0 { 81 | if cluster, exist := cmap[c]; exist { 82 | if i < cluster.Min { 83 | cluster.Min = i 84 | } 85 | if i > cluster.Max { 86 | cluster.Max = i 87 | } 88 | } else { 89 | cmap[c] = &Cluster{ 90 | Min: i, 91 | Max: i, 92 | } 93 | } 94 | } 95 | } 96 | for _, c := range cmap { 97 | clusters = append(clusters, c) 98 | } 99 | sort.Slice(clusters, 100 | func(i, j int) bool { return clusters[i].Min < clusters[j].Min }) 101 | return 102 | } 103 | 104 | /* 105 | getNeighbours returns the set of neighbours of `point`, which is an index in `h`. 106 | `neighbours` exclude `point`. 107 | */ 108 | func getNeighbours(h []int, point, eps int) (neighbours, nbMinPoint []int) { 109 | from := point - eps 110 | if from < 0 { 111 | from = 0 112 | } 113 | to := point + eps 114 | if to > len(h) { 115 | to = len(h) 116 | } 117 | for i := from; i < to; i++ { 118 | if h[i] > 0 { 119 | neighbours = append(neighbours, i) 120 | if i != point { 121 | nbMinPoint = append(nbMinPoint, i) 122 | } 123 | } 124 | } 125 | return 126 | } 127 | 128 | /* 129 | WriteClusters writes the set of clusters `cs` to file `fname`. 130 | */ 131 | func WriteClusters(cs []*Cluster, fname string) { 132 | buf := new(bytes.Buffer) 133 | for i, c := range cs { 134 | fmt.Fprintf(buf, "%d, %d %d\n", i, c.Min, c.Max) 135 | } 136 | ioutil.WriteFile(fname, buf.Bytes()) 137 | } 138 | -------------------------------------------------------------------------------- /dsp.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2019 Marius Ackerman 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | */ 15 | 16 | /* 17 | Package dsp has a set of digital signal processing functions that are primarily 18 | designed to support the discrete wavelet transform 19 | ("https://github.com/goccmack/dsp/dwt") 20 | */ 21 | package godsp 22 | 23 | import ( 24 | "bufio" 25 | "bytes" 26 | "fmt" 27 | "io/ioutil" 28 | "math" 29 | "strconv" 30 | "strings" 31 | 32 | myioutil "github.com/goccmack/goutil/ioutil" 33 | ) 34 | 35 | // Abs returns |x| 36 | func Abs(x []float64) []float64 { 37 | x1 := make([]float64, len(x)) 38 | for i, f := range x { 39 | x1[i] = math.Abs(f) 40 | } 41 | return x1 42 | } 43 | 44 | // AbsInt returns |x| 45 | func AbsInt(x []int) []int { 46 | x1 := make([]int, len(x)) 47 | for i, e := range x { 48 | if e < 0 { 49 | x1[i] = -e 50 | } else { 51 | x1[i] = e 52 | } 53 | } 54 | return x1 55 | } 56 | 57 | // AbsAll returns Abs(x) for every x in X 58 | func AbsAll(X [][]float64) [][]float64 { 59 | x1 := make([][]float64, len(X)) 60 | for i, x := range X { 61 | x1[i] = Abs(x) 62 | } 63 | return x1 64 | } 65 | 66 | /* 67 | Average returns Sum(x)/len(x). 68 | */ 69 | func Average(x []float64) float64 { 70 | return Sum(x) / float64(len(x)) 71 | } 72 | 73 | /* 74 | DivS returns x/s where x is a vector and s a scalar. 75 | */ 76 | func DivS(x []float64, s float64) []float64 { 77 | y := make([]float64, len(x)) 78 | for i := range x { 79 | y[i] = x[i] / s 80 | } 81 | return y 82 | } 83 | 84 | /* 85 | DownSampleAll returns DownSample(x, len(x)/min(len(xs))) for all x in xs 86 | */ 87 | func DownSampleAll(xs [][]float64) [][]float64 { 88 | N := len(xs[0]) 89 | for _, x := range xs { 90 | if len(x) < N { 91 | N = len(x) 92 | } 93 | } 94 | ys := make([][]float64, len(xs)) 95 | for i, x := range xs { 96 | ys[i] = DownSample(x, len(x)/N) 97 | } 98 | return ys 99 | } 100 | 101 | /* 102 | DownSample returns x downsampled by n 103 | Function panics if len(x) is not an integer multiple of n. 104 | */ 105 | func DownSample(x []float64, n int) []float64 { 106 | if len(x)%n != 0 { 107 | panic(fmt.Sprintf("len(x) (%d) is not an integer multiple of n (%d)", len(x), n)) 108 | } 109 | 110 | x1 := make([]float64, len(x)/n) 111 | for i, j := 0, 0; j < len(x1); i, j = i+n, j+1 { 112 | x1[j] = x[i] 113 | } 114 | return x1 115 | } 116 | 117 | // FindMax returns the value and index of the first element of x equal to the maximum value in x. 118 | func FindMax(x []float64) (value float64, index int) { 119 | value, index = x[0], 0 120 | for i := 1; i < len(x)-1; i++ { 121 | if x[i] > value { 122 | value, index = x[i], i 123 | } 124 | } 125 | return 126 | } 127 | 128 | // FindMax* returns the value and index of the first element of x equal to the maximum value in x. 129 | func FindMaxI(x []int) (value int, index int) { 130 | value, index = x[0], 0 131 | for i := 1; i < len(x)-1; i++ { 132 | if x[i] > value { 133 | value, index = x[i], i 134 | } 135 | } 136 | return 137 | } 138 | 139 | // FindMin returns the value and index of the first element of x equal to the minimum value in x. 140 | func FindMin(x []float64) (value float64, index int) { 141 | value, index = x[0], 0 142 | for i := 1; i < len(x)-1; i++ { 143 | if x[i] < value { 144 | value, index = x[i], i 145 | } 146 | } 147 | return 148 | } 149 | 150 | /* 151 | Float32ToFloat64 returns a copy of x with type []float64 152 | */ 153 | func Float32ToFloat64(x []float32) []float64 { 154 | y := make([]float64, len(x)) 155 | for i, f := range x { 156 | y[i] = float64(f) 157 | } 158 | return y 159 | } 160 | 161 | func IsPowerOf2(x int) bool { 162 | return (x != 0) && ((x & (x - 1)) == 0) 163 | } 164 | 165 | /* 166 | LoadFloats reads a text file containing one float per line. 167 | */ 168 | func LoadFloats(fname string) []float64 { 169 | data, err := ioutil.ReadFile(fname) 170 | if err != nil { 171 | panic(err) 172 | } 173 | rdr := bufio.NewReader(bytes.NewBuffer(data)) 174 | x := make([]float64, 0, 1024) 175 | for s, err := rdr.ReadString('\n'); err == nil; s, err = rdr.ReadString('\n') { 176 | f, err := strconv.ParseFloat(strings.TrimSuffix(s, "\n"), 64) 177 | if err != nil { 178 | panic(err) 179 | } 180 | x = append(x, f) 181 | } 182 | return x 183 | } 184 | 185 | // Log2 returns the integer log base 2 of n. 186 | // E.g.: log2(12) ~ 3.6. Log2 returns 3 187 | func Log2(n int) int { 188 | return int(math.Log2(float64(n))) 189 | } 190 | 191 | /* 192 | LowpassFilterAll returns LowpassFilter(x) for all x in xs. 193 | */ 194 | func LowpassFilterAll(xs [][]float64, alpha float64) [][]float64 { 195 | ys := make([][]float64, len(xs)) 196 | for i, x := range xs { 197 | ys[i] = LowpassFilter(x, alpha) 198 | } 199 | return ys 200 | } 201 | 202 | /* 203 | LowpassFilter returns x filtered by alpha 204 | */ 205 | func LowpassFilter(x []float64, alpha float64) []float64 { 206 | y := make([]float64, len(x)) 207 | y[0] = alpha * x[0] 208 | for i := 1; i < len(x); i++ { 209 | y[i] = y[i-1] + alpha*(x[i]-y[i-1]) 210 | } 211 | return y 212 | } 213 | 214 | // Max returns the maximum value of the elements of x 215 | func Max(x []float64) float64 { 216 | max := x[0] 217 | for _, f := range x { 218 | if f > max { 219 | max = f 220 | } 221 | } 222 | return max 223 | } 224 | 225 | // MaxInt returns the maximum value of the elements of x 226 | func MaxInt(x []int) int { 227 | max := x[0] 228 | for _, f := range x { 229 | if f > max { 230 | max = f 231 | } 232 | } 233 | return max 234 | } 235 | 236 | /* 237 | MovAvg returns the moving average for each x[i], given by sum(x[i-w:i+w])/(2w) 238 | */ 239 | func MovAvg(x []float64, w int) []float64 { 240 | y := make([]float64, len(x)) 241 | for i := w; i < len(x)-w; i++ { 242 | y[i] = Sum(x[i-w:i+w]) / float64(2*w) 243 | } 244 | return y 245 | } 246 | 247 | /* 248 | Multiplex returns on vector with the element of vs interleaved 249 | */ 250 | func Multiplex(channels [][]float64) []float64 { 251 | numChans := len(channels) 252 | chanLen := len(channels[0]) 253 | buf := make([]float64, numChans*chanLen) 254 | for i := 0; i < chanLen; i++ { 255 | k := i * numChans 256 | for j := 0; j < numChans; j++ { 257 | buf[k+j] = channels[j][i] 258 | } 259 | } 260 | return buf 261 | } 262 | 263 | // Normalise returns x/max(x) 264 | func Normalise(x []float64) []float64 { 265 | x1 := make([]float64, len(x)) 266 | sum := Max(x) 267 | for i, f := range x { 268 | x1[i] = f / sum 269 | } 270 | return x1 271 | } 272 | 273 | // Normalise returns x/max(x) for all x in xs 274 | func NormaliseAll(xs [][]float64) [][]float64 { 275 | x1 := make([][]float64, len(xs)) 276 | for i, x := range xs { 277 | x1[i] = Normalise(x) 278 | } 279 | return x1 280 | } 281 | 282 | // Pow2 returns 2^x. 283 | // The function panics if x < 0 284 | func Pow2(x int) int { 285 | if x < 0 { 286 | panic(fmt.Sprintf("X = %d", x)) 287 | } 288 | pw := 1 289 | for i := 1; i <= x; i++ { 290 | pw *= 2 291 | } 292 | return pw 293 | } 294 | 295 | // Range returns an interger range 0:1:n-1 296 | func Range(n int) []int { 297 | rng := make([]int, n) 298 | for i := range rng { 299 | rng[i] = i 300 | } 301 | return rng 302 | } 303 | 304 | /* 305 | RemoveAvgAllZ removes the average of all vectors x in xs. The minimum value 306 | of any x[i] is 0. 307 | */ 308 | func RemoveAvgAllZ(xs [][]float64) [][]float64 { 309 | xs1 := make([][]float64, len(xs)) 310 | for i, x := range xs { 311 | xs1[i] = RemoveAvg(x) 312 | } 313 | return xs1 314 | } 315 | 316 | // RemoveAvgZ returns x[i] = x[i]-sum(x)/len(x) or 0 if x[i]-sum(x)/len(x) < 0 317 | func RemoveAvg(x []float64) []float64 { 318 | x1 := make([]float64, len(x)) 319 | avg := Sum(x) / float64(len(x)) 320 | for i, f := range x { 321 | x1[i] = f - avg 322 | if x1[i] < 0 { 323 | x1[i] = 0 324 | } 325 | } 326 | return x1 327 | } 328 | 329 | // Smooth smoothts x: x[i] = sum(x[i-wdw:i+wdw])/(2*wdw) 330 | func Smooth(x []float64, wdw int) { 331 | for i := 0; i < wdw; i++ { 332 | x[i] = 0 333 | } 334 | for i := wdw; i < len(x)-wdw; i++ { 335 | x[i] = Sum(x[i-wdw:i+wdw]) / float64((2 * wdw)) 336 | } 337 | } 338 | 339 | /* 340 | Sub returns x - y. The function panics if len(x) != len(y). 341 | */ 342 | func Sub(x, y []float64) []float64 { 343 | if len(x) != len(y) { 344 | panic("len(x) != len(y)") 345 | } 346 | x1 := make([]float64, len(x)) 347 | for i := range x { 348 | x1[i] = x[i] - y[i] 349 | } 350 | return x1 351 | } 352 | 353 | // Sum returns the sum of the elements of the vector x 354 | func Sum(x []float64) float64 { 355 | sum := 0.0 356 | for _, f := range x { 357 | sum += f 358 | } 359 | return sum 360 | } 361 | 362 | // SumVectors returns the sum of the vectors in X. 363 | // The function panics if all vectors don't have the same length 364 | func SumVectors(X [][]float64) []float64 { 365 | N := len(X[0]) 366 | for i, x := range X { 367 | if len(x) != N { 368 | panic(fmt.Sprintf("N=%d but len(X[%d]=%d", N, i, len(x))) 369 | } 370 | } 371 | sum := make([]float64, N) 372 | for i := 0; i < N; i++ { 373 | for j := range X { 374 | sum[i] += X[j][i] 375 | } 376 | } 377 | return sum 378 | } 379 | 380 | func ToFloat(x []int) []float64 { 381 | y := make([]float64, len(x)) 382 | for i, e := range x { 383 | y[i] = float64(e) / float64(math.MaxInt64) 384 | } 385 | return y 386 | } 387 | 388 | /* 389 | ToInt returns y * math.MaxInt64. 390 | The range of x is [-1.0,1.0]. 391 | The function panics if bitsPerSample is not one of 8,16,32. 392 | */ 393 | func ToInt(x []float64, bitsPerSample int) []int { 394 | y := make([]int, len(x)) 395 | if bitsPerSample != 8 && bitsPerSample != 16 && bitsPerSample != 32 { 396 | panic(fmt.Sprintf("Invalid bitsPerSample %d", bitsPerSample)) 397 | } 398 | max := float64(int(1)<= 0 && i < len(x)-wdw { 413 | slp = slope(x[i : i+wdw]) 414 | i += step 415 | } 416 | _, maxI = FindMax(x[from:i]) 417 | maxI += from 418 | slopeEnd = i 419 | return 420 | } 421 | 422 | func findLocalMin(x []float64, from, wdw, step int) (minI, slopeEnd int) { 423 | i, slp := from+wdw, 0 424 | for slp <= 0 && i < len(x)-wdw { 425 | slp = slope(x[i : i+wdw]) 426 | i += step 427 | } 428 | _, minI = FindMin(x[from:i]) 429 | minI += from 430 | slopeEnd = i 431 | return 432 | } 433 | 434 | func findNon0Slope(x []float64, from, wdw int) (slp, end int) { 435 | for i := from; i < len(x)-wdw; i++ { 436 | slp := slope(x[i : i+wdw]) 437 | if slp != 0 { 438 | return slp, i 439 | } 440 | } 441 | return 0, len(x) 442 | } 443 | 444 | // slope returns +1, 0, -1 445 | func slope(x []float64) int { 446 | end := len(x) - 1 447 | if x[0] < x[end] { 448 | return -1 449 | } 450 | if x[0] == x[end] { 451 | return 0 452 | } 453 | return 1 454 | } 455 | 456 | func ivecContain(x []int, v int) bool { 457 | for _, v1 := range x { 458 | if v1 == v { 459 | return true 460 | } 461 | } 462 | return false 463 | } 464 | 465 | // WriteAllDataFile writes each xs[i] in xs to a test file `fname_i.txt` 466 | func WriteAllDataFile(xs [][]float64, fname string) { 467 | for i, xs := range xs { 468 | WriteDataFile(xs, fmt.Sprintf("%s_%d", fname, i)) 469 | } 470 | } 471 | 472 | // WriteDataFile writes x to a text file `fname.txt` 473 | func WriteDataFile(x []float64, fname string) { 474 | buf := new(bytes.Buffer) 475 | for _, f := range x { 476 | fmt.Fprintf(buf, "%f\n", f) 477 | } 478 | if err := myioutil.WriteFile(fname+".txt", buf.Bytes()); err != nil { 479 | panic(err) 480 | } 481 | } 482 | 483 | // WriteIntDataFile writes x to a text file `fname.txt` 484 | func WriteIntDataFile(x []int, fname string) { 485 | buf := new(bytes.Buffer) 486 | for _, f := range x { 487 | fmt.Fprintf(buf, "%d\n", f) 488 | } 489 | if err := myioutil.WriteFile(fname+".txt", buf.Bytes()); err != nil { 490 | panic(err) 491 | } 492 | } 493 | 494 | /* 495 | WriteIntMatrixDataFile writes an integer matrix to a text file `fname.csv` 496 | */ 497 | func WriteIntMatrixDataFile(x [][]int, fname string) { 498 | buf := new(bytes.Buffer) 499 | for _, row := range x { 500 | for i, col := range row { 501 | if i > 0 { 502 | fmt.Fprint(buf, ",") 503 | } 504 | fmt.Fprintf(buf, "%d", col) 505 | } 506 | fmt.Fprintln(buf) 507 | } 508 | if err := myioutil.WriteFile(fname+".csv", buf.Bytes()); err != nil { 509 | panic(err) 510 | } 511 | } 512 | 513 | /* 514 | Xcorr returns the cross correlation of x with y for maxDelay. 515 | */ 516 | func Xcorr(x, y []float64, maxDelay int) (corr []float64) { 517 | N := len(x) 518 | corr = make([]float64, maxDelay) 519 | for k := 0; k < maxDelay; k++ { 520 | for n := 0; n < N-k; n++ { 521 | corr[k] += x[n] * y[n+k] 522 | } 523 | corr[k] /= float64(N) 524 | } 525 | return 526 | } 527 | -------------------------------------------------------------------------------- /dwt/dwt.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 Marius Ackerman 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | /* 16 | Package DWT has functions supporting the Discrete Wavelet Transform. 17 | */ 18 | package dwt 19 | 20 | import ( 21 | "math" 22 | 23 | "github.com/goccmack/godsp" 24 | ) 25 | 26 | type Transform struct { 27 | st []float64 28 | level int 29 | sections []*transformSection 30 | } 31 | 32 | type transformSection struct { 33 | start int 34 | size int 35 | } 36 | 37 | // Daubechies4 returns the DWT with Daubechies 4 coeficients to level. 38 | func Daubechies4(s []float64, level int) *Transform { 39 | t := &Transform{ 40 | st: make([]float64, len(s)), 41 | level: level, 42 | sections: getTransformSections(len(s), level), 43 | } 44 | copy(t.st, s) 45 | for _, section := range t.sections { 46 | scaleSize := section.size 47 | for l := level; l > 0; l-- { 48 | max := section.start + scaleSize 49 | split(t.st[section.start:max]) 50 | daubechies4(t.st[section.start:max]) 51 | scaleSize /= 2 52 | } 53 | } 54 | 55 | return t 56 | } 57 | 58 | /* 59 | Return the series of length 2^k stages of the DWT 60 | */ 61 | func getTransformSections(N, level int) (sections []*transformSection) { 62 | for start := 0; N-start >= 64*godsp.Pow2(level); { 63 | size := int(godsp.Pow2(godsp.Log2(N - start))) 64 | section := &transformSection{ 65 | start: start, 66 | size: size, 67 | } 68 | sections = append(sections, section) 69 | start += size 70 | } 71 | return 72 | } 73 | 74 | /* 75 | GetFrameSize returns the size of DWT frame required for the transform 76 | */ 77 | // func GetFrameSize(s []float64) int { 78 | // logLen := math.Log2(float64(len(s))) 79 | // logLenInt := int(math.Ceil(logLen)) 80 | 81 | // return godsp.Pow2(logLenInt) 82 | // } 83 | 84 | /* 85 | Split s into even and odd elements, 86 | where the even elements are in the first half 87 | of the vector and the odd elements are in the 88 | second half. 89 | */ 90 | func split(s []float64) { 91 | half := len(s) / 2 92 | odd := make([]float64, half) 93 | for i := 1; i < len(s); i += 2 { 94 | odd[i/2] = s[i] 95 | } 96 | for i := 2; i < len(s); i += 2 { 97 | s[i/2] = s[i] 98 | } 99 | for i, v := range odd { 100 | s[half+i] = v 101 | } 102 | } 103 | 104 | /* 105 | After: Ripples section 3.4 106 | */ 107 | func daubechies4(s []float64) { 108 | half := len(s) / 2 109 | 110 | // Update 1: 111 | for n := 0; n < half; n++ { 112 | s[n] = s[n] + math.Sqrt(3)*s[half+n] 113 | } 114 | 115 | // Predict: 116 | s[half] = s[half] - 117 | (math.Sqrt(3)/4)*s[0] - 118 | ((math.Sqrt(3)-2)/4)*s[half-1] 119 | for n := 1; n < half; n++ { 120 | s[half+n] = s[half+n] - 121 | (math.Sqrt(3)/4)*s[n] - 122 | ((math.Sqrt(3)-2)/4)*s[n-1] 123 | } 124 | 125 | // Update 2: 126 | for n := 0; n < half-1; n++ { 127 | s[n] = s[n] - s[half+n+1] 128 | } 129 | s[half-1] = s[half-1] - s[half] 130 | 131 | // Normalise: 132 | for n := 0; n < half; n++ { 133 | s[n] = ((math.Sqrt(3) - 1) / math.Sqrt(2)) * s[n] 134 | s[n+half] = ((math.Sqrt(3) + 1) / math.Sqrt(2)) * s[n+half] 135 | } 136 | } 137 | 138 | // GetCoefficients returns the coefficients of all transform levels 139 | func (t *Transform) GetCoefficients() [][]float64 { 140 | cfs := make([][]float64, t.level) 141 | for _, s := range t.sections { 142 | scfs := t.getSectionCoefficients(s) 143 | for i, c := range scfs { 144 | cfs[i] = append(cfs[i], c...) 145 | } 146 | } 147 | return cfs 148 | } 149 | 150 | // GetDownSampledCoefficients returns the coefficients of all the levels downsampled to 151 | // the length of the deepest level of the transform. 152 | func (t *Transform) GetDownSampledCoefficients() [][]float64 { 153 | dscfs := make([][]float64, t.level) 154 | for _, s := range t.sections { 155 | cfs := t.getSectionCoefficients(s) 156 | for i, cf := range cfs { 157 | if i < t.level-1 { 158 | dscfs[i] = append(dscfs[i], 159 | godsp.DownSample(cf, godsp.Pow2(t.level-(i+1)))...) 160 | } 161 | } 162 | } 163 | return dscfs 164 | } 165 | 166 | /* 167 | GetDecomposition returns the vector containing the DWT decomposion 168 | */ 169 | func (t *Transform) GetDecomposition() []float64 { 170 | return t.st 171 | } 172 | 173 | // GetCoefficients returns the coefficients of all transform levels 174 | func (t *Transform) getSectionCoefficients(s *transformSection) [][]float64 { 175 | cfs := make([][]float64, t.level) 176 | half := s.size / 2 177 | for l := 1; l <= t.level; l++ { 178 | cfs[l-1] = t.st[s.start+half : s.start+2*half] 179 | half /= 2 180 | } 181 | return cfs 182 | } 183 | -------------------------------------------------------------------------------- /dwt/dwt_test.go: -------------------------------------------------------------------------------- 1 | package dwt 2 | 3 | import ( 4 | "math" 5 | "testing" 6 | ) 7 | 8 | func Test1(t *testing.T) { 9 | N := 1_315_840 10 | sections := getTransformSections(N, 4) 11 | sum := 0 12 | for _, s := range sections { 13 | sum += s.size 14 | } 15 | if sum != N { 16 | t.Errorf("Sum = %d, difference=%f", sum, math.Abs(float64(sum-N))) 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/goccmack/godsp 2 | 3 | go 1.13 4 | 5 | require ( 6 | github.com/go-audio/audio v1.0.0 7 | github.com/goccmack/goutil v0.4.0 8 | github.com/mjibson/go-dsp v0.0.0-20180508042940-11479a337f12 9 | github.com/youpy/go-riff v0.0.0-20131220112943-557d78c11efb // indirect 10 | github.com/youpy/go-wav v0.0.0-20160223082350-b63a9887d320 11 | ) 12 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/ajstarks/svgo v0.0.0-20180226025133-644b8db467af/go.mod h1:K08gAheRH3/J6wwsYMMT4xOr94bZjxIelGM0+d/wbFw= 2 | github.com/fogleman/gg v1.2.1-0.20190220221249-0403632d5b90/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k= 3 | github.com/go-audio/audio v1.0.0 h1:zS9vebldgbQqktK4H0lUqWrG8P0NxCJVqcj7ZpNnwd4= 4 | github.com/go-audio/audio v1.0.0/go.mod h1:6uAu0+H2lHkwdGsAY+j2wHPNPpPoeg5AaEFh9FlA+Zs= 5 | github.com/goccmack/goutil v0.4.0 h1:or+SequGBcQp7Rf5q719HlOxtEGueaXEenDbc3pANgk= 6 | github.com/goccmack/goutil v0.4.0/go.mod h1:dPBoKv07AeI2DGYE3ECrSLOLpGaBIBGCUCGKHclOPyU= 7 | github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= 8 | github.com/golang/geo v0.0.0-20190916061304-5b978397cfec/go.mod h1:QZ0nwyI2jOfgRAoBvP+ab5aRr7c9x7lhGEJrKvBwjWI= 9 | github.com/jung-kurt/gofpdf v1.0.3-0.20190309125859-24315acbbda5/go.mod h1:7Id9E/uU8ce6rXgefFLlgrJj/GYY22cpxn+r32jIOes= 10 | github.com/mjibson/go-dsp v0.0.0-20180508042940-11479a337f12 h1:dd7vnTDfjtwCETZDrRe+GPYNLA1jBtbZeyfyE8eZCyk= 11 | github.com/mjibson/go-dsp v0.0.0-20180508042940-11479a337f12/go.mod h1:i/KKcxEWEO8Yyl11DYafRPKOPVYTrhxiTRigjtEEXZU= 12 | github.com/youpy/go-riff v0.0.0-20131220112943-557d78c11efb h1:RDh7U5Di6o7fblIBe7rVi9KnrcOXUbLwvvLLdP2InSI= 13 | github.com/youpy/go-riff v0.0.0-20131220112943-557d78c11efb/go.mod h1:83nxdDV4Z9RzrTut9losK7ve4hUnxUR8ASSz4BsKXwQ= 14 | github.com/youpy/go-wav v0.0.0-20160223082350-b63a9887d320 h1:YuM+QcBOD3fVTF1p5upTKvfAn+CaI1Tsh2s0dxdEzhI= 15 | github.com/youpy/go-wav v0.0.0-20160223082350-b63a9887d320/go.mod h1:Zf+Ju+8Ofy5zx/YWWArfcGnl5FAsWumLq/uHeRGgL60= 16 | golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= 17 | golang.org/x/exp v0.0.0-20180807140117-3d87b88a115f/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= 18 | golang.org/x/exp v0.0.0-20190125153040-c74c464bbbf2/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= 19 | golang.org/x/image v0.0.0-20180708004352-c73c2afc3b81/go.mod h1:ux5Hcp/YLpHSI86hEcLt0YII63i6oz57MZXIpbrjZUs= 20 | golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 21 | golang.org/x/tools v0.0.0-20190206041539-40960b6deb8e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 22 | gonum.org/v1/gonum v0.0.0-20180816165407-929014505bf4/go.mod h1:Y+Yx5eoAFn32cQvJDxZx5Dpnq+c3wtXuadVZAcxbbBo= 23 | gonum.org/v1/gonum v0.6.2/go.mod h1:9mxDZsDKxgMAuccQkewq682L+0eCu4dCN2yonUJTCLU= 24 | gonum.org/v1/netlib v0.0.0-20190313105609-8cb42192e0e0/go.mod h1:wa6Ws7BG/ESfp6dHfk7C6KdzKA7wR7u/rKwOGE66zvw= 25 | gonum.org/v1/plot v0.0.0-20190515093506-e2840ee46a6b/go.mod h1:Wt8AAjI+ypCyYX3nZBvf6cAIx93T+c/OS2HFAYskSZc= 26 | rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= 27 | -------------------------------------------------------------------------------- /peaks/peaks.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 Marius Ackerman 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | /* 16 | Package peaks finds the maxima in a vector. It works by lowering a horizontal line 17 | across the signal, revealing peaks as it proceeds. Peaks that are closer to 18 | each other than a minimum separation distance are merged to the left (lower index). 19 | */ 20 | package peaks 21 | 22 | import ( 23 | "math" 24 | "sort" 25 | 26 | "github.com/goccmack/godsp" 27 | ) 28 | 29 | const ( 30 | empty = -1 31 | ) 32 | 33 | /* 34 | Get returns a slice containing the indices of the peaks in x. 35 | sep is the minimum distance between 2 peaks. Peaks closer to each other than 36 | sep are merged to the lower index. 37 | */ 38 | func Get(x []float64, sep int) []int { 39 | pks := []int{} 40 | for i := range x { 41 | if isMax(i, i-sep, i+sep, x) { 42 | pks = append(pks, i) 43 | } 44 | } 45 | return pks 46 | } 47 | 48 | func getMaxIndex(x []float64) int { 49 | i, max := 0, math.Inf(-1) 50 | for j, y := range x { 51 | if y > max { 52 | i, max = j, y 53 | } 54 | } 55 | if max > 0 { 56 | return i 57 | } 58 | return -1 59 | } 60 | 61 | func isMax(i, min, max int, x []float64) bool { 62 | if min < 0 { 63 | min = 0 64 | } 65 | if max > len(x) { 66 | max = len(x) 67 | } 68 | for j := min; j < i; j++ { 69 | if x[j] >= x[i] { 70 | return false 71 | } 72 | } 73 | for j := i + 1; j < max; j++ { 74 | if x[j] > x[i] { 75 | return false 76 | } 77 | } 78 | return true 79 | } 80 | 81 | func getWindow(i, sep int, x []float64) (min, max int) { 82 | min, max = i-sep, i+sep 83 | if min < 0 { 84 | min = 0 85 | } 86 | if max > len(x) { 87 | max = len(x) 88 | } 89 | return 90 | } 91 | 92 | // func Get(x []float64, sep int) []int { 93 | // si := getSortedIndices(x) 94 | // pks := getEmptyPeaks(len(x)) 95 | // for _, xi := range si { 96 | // if pks[xi] == empty { 97 | // markNeighbours(xi, sep, pks) 98 | // } 99 | // } 100 | // uniquePeaks := make([]int, 0, len(x)/(2*sep)) 101 | // for i, xi := range pks { 102 | // if i == xi { 103 | // uniquePeaks = append(uniquePeaks, xi) 104 | // } 105 | // } 106 | // return uniquePeaks 107 | // } 108 | 109 | func getEmptyPeaks(n int) []int { 110 | epks := make([]int, n) 111 | for i := range epks { 112 | epks[i] = empty 113 | } 114 | return epks 115 | } 116 | 117 | func getSortedIndices(x []float64) []int { 118 | idx := godsp.Range(len(x)) 119 | sort.SliceStable(idx, func(i, j int) bool { return x[i] > x[j] }) 120 | return idx 121 | } 122 | 123 | func markNeighbours(xi, sep int, pks []int) { 124 | min := xi - sep 125 | if min < 0 { 126 | min = 0 127 | } 128 | max := xi + sep 129 | if max > len(pks) { 130 | max = len(pks) 131 | } 132 | for i := min; i < max; i++ { 133 | pks[i] = xi 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /ppeaks/ppeaks.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 Marius Ackerman 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | /* 16 | Package ppeaks detects the peaks in a time series by means of persistent homology: 17 | https://www.sthu.org/blog/13-perstopology-peakdetection/index.html. 18 | */ 19 | package ppeaks 20 | 21 | import ( 22 | "math" 23 | "sort" 24 | 25 | "github.com/goccmack/godsp" 26 | ) 27 | 28 | const none = -1 29 | 30 | type Peak struct { 31 | born, died, left, right int 32 | } 33 | 34 | func newPeak(startIdx int) *Peak { 35 | return &Peak{ 36 | born: startIdx, 37 | left: startIdx, 38 | right: startIdx, 39 | died: none, 40 | } 41 | } 42 | 43 | type Peaks struct { 44 | peaks []*Peak 45 | seq []float64 46 | } 47 | 48 | func (p *Peak) getPersistence(seq []float64) float64 { 49 | if p.died == none { 50 | return math.Inf(1) 51 | } 52 | return seq[p.born] - seq[p.died] 53 | } 54 | 55 | /* 56 | GetPeaksInt finds the peaks in an integer time series. 57 | Peaks are returnend in increasing order of their indices. 58 | */ 59 | func GetPeaksInt(seq []int) *Peaks { 60 | seq1 := godsp.ToFloat(seq) 61 | return GetPeaks(seq1) 62 | } 63 | 64 | /* 65 | GetPeaks returns the peaks in a floating point time series. 66 | Peaks are returnend in increasing order of their indices. 67 | */ 68 | func GetPeaks(seq []float64) *Peaks { 69 | peaks := make([]*Peak, 0, 1024) 70 | // Maps indices to peaks 71 | idxtopeak := make([]int, len(seq)) 72 | for i := range idxtopeak { 73 | idxtopeak[i] = none 74 | } 75 | // Sequence indices sorted by values 76 | indices := godsp.Range(len(seq)) 77 | sort.SliceStable(indices, func(i, j int) bool { return seq[indices[i]] > seq[indices[j]] }) 78 | // Process each sample in descending order 79 | for _, idx := range indices { 80 | lftdone := (idx > 0 && idxtopeak[idx-1] != none) 81 | rgtdone := (idx < len(seq)-1 && idxtopeak[idx+1] != none) 82 | il := none 83 | if lftdone { 84 | il = idxtopeak[idx-1] 85 | } 86 | ir := none 87 | if rgtdone { 88 | ir = idxtopeak[idx+1] 89 | } 90 | 91 | // New peak born 92 | if !lftdone && !rgtdone { 93 | peaks = append(peaks, newPeak(idx)) 94 | idxtopeak[idx] = len(peaks) - 1 95 | } 96 | 97 | // Directly merge to next peak left 98 | if lftdone && !rgtdone { 99 | peaks[il].right++ 100 | idxtopeak[idx] = il 101 | } 102 | 103 | // Directly merge to next peak right 104 | if !lftdone && rgtdone { 105 | peaks[ir].left-- 106 | idxtopeak[idx] = ir 107 | } 108 | 109 | // Merge left and right peaks 110 | if lftdone && rgtdone { 111 | // Left was born earlier: merge right to left 112 | if seq[peaks[il].born] > seq[peaks[ir].born] { 113 | peaks[ir].died = idx 114 | peaks[il].right = peaks[ir].right 115 | idxtopeak[peaks[il].right], idxtopeak[idx] = il, il 116 | } else { 117 | peaks[il].died = idx 118 | peaks[ir].left = peaks[il].left 119 | idxtopeak[peaks[ir].left], idxtopeak[idx] = ir, ir 120 | } 121 | } 122 | } 123 | 124 | sort.SliceStable(peaks, func(i, j int) bool { return peaks[i].born < peaks[j].born }) 125 | 126 | return &Peaks{ 127 | peaks: peaks, 128 | seq: seq, 129 | } 130 | } 131 | 132 | /* 133 | GetIndices returns the indices in the original time series `seq` of the peaks with 134 | persistence/max(persitence of seq) >= `fracOfMaxPersistence` 135 | */ 136 | func (pks *Peaks) GetIndices(fracOfMaxPersistence float64) []int { 137 | indices := make([]int, 0, len(pks.peaks)) 138 | _, maxPersistence := pks.MinMaxPersistence() 139 | for _, pk := range pks.peaks { 140 | if pk.getPersistence(pks.seq)/maxPersistence >= fracOfMaxPersistence { 141 | indices = append(indices, pk.born) 142 | } 143 | } 144 | return indices 145 | } 146 | 147 | /* 148 | Max returns the index in the original time series `seq` of the peak with the 149 | highest y-value. See GetIndices for fracOfMaxPersistence. 150 | */ 151 | func (pks *Peaks) Max(fracOfMaxPersistence float64) int { 152 | idxs := pks.GetIndices(fracOfMaxPersistence) 153 | biggest, val := -1, math.Inf(-1) 154 | for _, pk := range idxs { 155 | if pks.seq[pk] > val { 156 | biggest, val = pk, pks.seq[pk] 157 | } 158 | } 159 | return biggest 160 | } 161 | 162 | /* 163 | MinMaxPersistence returns the minimum and maximum persistence of the peaks in `seq`. 164 | */ 165 | func (pks *Peaks) MinMaxPersistence() (min, max float64) { 166 | max, min = math.Inf(-1), math.Inf(1) 167 | for _, pk := range pks.peaks { 168 | prs := pk.getPersistence(pks.seq) 169 | if prs > max && prs < math.Inf(1) { 170 | max = prs 171 | } 172 | if prs < min { 173 | min = prs 174 | } 175 | } 176 | return 177 | } 178 | -------------------------------------------------------------------------------- /wavread.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 Marius Ackerman 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package godsp 16 | 17 | import ( 18 | "bytes" 19 | "io/ioutil" 20 | 21 | "github.com/mjibson/go-dsp/wav" 22 | ) 23 | 24 | /* 25 | ReadWavFile returns the demultiplexed channels of a wav file, and the sample rate in Hz. 26 | */ 27 | func ReadWavFile(wavName string) (channels [][]float64, sampleRate, bitsPerSample int) { 28 | buf, err := ioutil.ReadFile(wavName) 29 | if err != nil { 30 | panic(err) 31 | } 32 | rdr, err := wav.New(bytes.NewBuffer(buf)) 33 | if err != nil { 34 | panic(err) 35 | } 36 | numSamples, numChannels := rdr.Samples, int(rdr.NumChannels) 37 | sampleRate = int(rdr.SampleRate) 38 | bitsPerSample = int(rdr.Header.BitsPerSample) 39 | channels = make([][]float64, numChannels) 40 | chanLen := numSamples / numChannels 41 | for i := range channels { 42 | channels[i] = make([]float64, chanLen) 43 | } 44 | samples, err := rdr.ReadFloats(rdr.Samples) 45 | if err != nil { 46 | panic(err) 47 | } 48 | for i, j := 0, 0; i < len(samples); { 49 | for _, ch := range channels { 50 | ch[j] = float64(samples[i]) 51 | i++ 52 | } 53 | j++ 54 | } 55 | return 56 | } 57 | --------------------------------------------------------------------------------