├── LICENSE ├── README.md ├── audioExample.py ├── benchmark.py ├── cwt.py ├── example.png ├── hendrixRiff.wav ├── mortletCWT.png ├── sinExample.py ├── undersampled-wavelet-p1.png └── undersampled-wavelet-p2.png /LICENSE: -------------------------------------------------------------------------------- 1 | ------------------------------------------------------------------------- 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | 7 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 8 | 9 | 1. Definitions. 10 | 11 | "License" shall mean the terms and conditions for use, reproduction, 12 | and distribution as defined by Sections 1 through 9 of this document. 13 | 14 | "Licensor" shall mean the copyright owner or entity authorized by 15 | the copyright owner that is granting the License. 16 | 17 | "Legal Entity" shall mean the union of the acting entity and all 18 | other entities that control, are controlled by, or are under common 19 | control with that entity. For the purposes of this definition, 20 | "control" means (i) the power, direct or indirect, to cause the 21 | direction or management of such entity, whether by contract or 22 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 23 | outstanding shares, or (iii) beneficial ownership of such entity. 24 | 25 | "You" (or "Your") shall mean an individual or Legal Entity 26 | exercising permissions granted by this License. 27 | 28 | "Source" form shall mean the preferred form for making modifications, 29 | including but not limited to software source code, documentation 30 | source, and configuration files. 31 | 32 | "Object" form shall mean any form resulting from mechanical 33 | transformation or translation of a Source form, including but 34 | not limited to compiled object code, generated documentation, 35 | and conversions to other media types. 36 | 37 | "Work" shall mean the work of authorship, whether in Source or 38 | Object form, made available under the License, as indicated by a 39 | copyright notice that is included in or attached to the work 40 | (an example is provided in the Appendix below). 41 | 42 | "Derivative Works" shall mean any work, whether in Source or Object 43 | form, that is based on (or derived from) the Work and for which the 44 | editorial revisions, annotations, elaborations, or other modifications 45 | represent, as a whole, an original work of authorship. For the purposes 46 | of this License, Derivative Works shall not include works that remain 47 | separable from, or merely link (or bind by name) to the interfaces of, 48 | the Work and Derivative Works thereof. 49 | 50 | "Contribution" shall mean any work of authorship, including 51 | the original version of the Work and any modifications or additions 52 | to that Work or Derivative Works thereof, that is intentionally 53 | submitted to Licensor for inclusion in the Work by the copyright owner 54 | or by an individual or Legal Entity authorized to submit on behalf of 55 | the copyright owner. For the purposes of this definition, "submitted" 56 | means any form of electronic, verbal, or written communication sent 57 | to the Licensor or its representatives, including but not limited to 58 | communication on electronic mailing lists, source code control systems, 59 | and issue tracking systems that are managed by, or on behalf of, the 60 | Licensor for the purpose of discussing and improving the Work, but 61 | excluding communication that is conspicuously marked or otherwise 62 | designated in writing by the copyright owner as "Not a Contribution." 63 | 64 | "Contributor" shall mean Licensor and any individual or Legal Entity 65 | on behalf of whom a Contribution has been received by Licensor and 66 | subsequently incorporated within the Work. 67 | 68 | 2. Grant of Copyright License. Subject to the terms and conditions of 69 | this License, each Contributor hereby grants to You a perpetual, 70 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 71 | copyright license to reproduce, prepare Derivative Works of, 72 | publicly display, publicly perform, sublicense, and distribute the 73 | Work and such Derivative Works in Source or Object form. 74 | 75 | 3. Grant of Patent License. Subject to the terms and conditions of 76 | this License, each Contributor hereby grants to You a perpetual, 77 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 78 | (except as stated in this section) patent license to make, have made, 79 | use, offer to sell, sell, import, and otherwise transfer the Work, 80 | where such license applies only to those patent claims licensable 81 | by such Contributor that are necessarily infringed by their 82 | Contribution(s) alone or by combination of their Contribution(s) 83 | with the Work to which such Contribution(s) was submitted. If You 84 | institute patent litigation against any entity (including a 85 | cross-claim or counterclaim in a lawsuit) alleging that the Work 86 | or a Contribution incorporated within the Work constitutes direct 87 | or contributory patent infringement, then any patent licenses 88 | granted to You under this License for that Work shall terminate 89 | as of the date such litigation is filed. 90 | 91 | 4. Redistribution. You may reproduce and distribute copies of the 92 | Work or Derivative Works thereof in any medium, with or without 93 | modifications, and in Source or Object form, provided that You 94 | meet the following conditions: 95 | 96 | (a) You must give any other recipients of the Work or 97 | Derivative Works a copy of this License; and 98 | 99 | (b) You must cause any modified files to carry prominent notices 100 | stating that You changed the files; and 101 | 102 | (c) You must retain, in the Source form of any Derivative Works 103 | that You distribute, all copyright, patent, trademark, and 104 | attribution notices from the Source form of the Work, 105 | excluding those notices that do not pertain to any part of 106 | the Derivative Works; and 107 | 108 | (d) If the Work includes a "NOTICE" text file as part of its 109 | distribution, then any Derivative Works that You distribute must 110 | include a readable copy of the attribution notices contained 111 | within such NOTICE file, excluding those notices that do not 112 | pertain to any part of the Derivative Works, in at least one 113 | of the following places: within a NOTICE text file distributed 114 | as part of the Derivative Works; within the Source form or 115 | documentation, if provided along with the Derivative Works; or, 116 | within a display generated by the Derivative Works, if and 117 | wherever such third-party notices normally appear. The contents 118 | of the NOTICE file are for informational purposes only and 119 | do not modify the License. You may add Your own attribution 120 | notices within Derivative Works that You distribute, alongside 121 | or as an addendum to the NOTICE text from the Work, provided 122 | that such additional attribution notices cannot be construed 123 | as modifying the License. 124 | 125 | You may add Your own copyright statement to Your modifications and 126 | may provide additional or different license terms and conditions 127 | for use, reproduction, or distribution of Your modifications, or 128 | for any such Derivative Works as a whole, provided Your use, 129 | reproduction, and distribution of the Work otherwise complies with 130 | the conditions stated in this License. 131 | 132 | 5. Submission of Contributions. Unless You explicitly state otherwise, 133 | any Contribution intentionally submitted for inclusion in the Work 134 | by You to the Licensor shall be under the terms and conditions of 135 | this License, without any additional terms or conditions. 136 | Notwithstanding the above, nothing herein shall supersede or modify 137 | the terms of any separate license agreement you may have executed 138 | with Licensor regarding such Contributions. 139 | 140 | 6. Trademarks. This License does not grant permission to use the trade 141 | names, trademarks, service marks, or product names of the Licensor, 142 | except as required for reasonable and customary use in describing the 143 | origin of the Work and reproducing the content of the NOTICE file. 144 | 145 | 7. Disclaimer of Warranty. Unless required by applicable law or 146 | agreed to in writing, Licensor provides the Work (and each 147 | Contributor provides its Contributions) on an "AS IS" BASIS, 148 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 149 | implied, including, without limitation, any warranties or conditions 150 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 151 | PARTICULAR PURPOSE. You are solely responsible for determining the 152 | appropriateness of using or redistributing the Work and assume any 153 | risks associated with Your exercise of permissions under this License. 154 | 155 | 8. Limitation of Liability. In no event and under no legal theory, 156 | whether in tort (including negligence), contract, or otherwise, 157 | unless required by applicable law (such as deliberate and grossly 158 | negligent acts) or agreed to in writing, shall any Contributor be 159 | liable to You for damages, including any direct, indirect, special, 160 | incidental, or consequential damages of any character arising as a 161 | result of this License or out of the use or inability to use the 162 | Work (including but not limited to damages for loss of goodwill, 163 | work stoppage, computer failure or malfunction, or any and all 164 | other commercial damages or losses), even if such Contributor 165 | has been advised of the possibility of such damages. 166 | 167 | 9. Accepting Warranty or Additional Liability. While redistributing 168 | the Work or Derivative Works thereof, You may choose to offer, 169 | and charge a fee for, acceptance of support, warranty, indemnity, 170 | or other liability obligations and/or rights consistent with this 171 | License. However, in accepting such obligations, You may act only 172 | on Your own behalf and on Your sole responsibility, not on behalf 173 | of any other Contributor, and only if You agree to indemnify, 174 | defend, and hold each Contributor harmless for any liability 175 | incurred by, or claims asserted against, such Contributor by reason 176 | of your accepting any such warranty or additional liability. 177 | 178 | END OF TERMS AND CONDITIONS -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | _if you are interested in becoming a collaborator let me know by creating an issue or gmail me nickgeoca_ 2 | # Tensorflow CWT 3 | This implements a 1-D Continuous Wavelet Transform (CWT) in tensorflow. The benefit is that it runs parallel on GPUs. 4 | 5 | The following wavelets are available: 6 | * Ricker wavelet - cwtRicker 7 | * Mortlet wavelet - cwtMortlet 8 | 9 | ## Benchmarks 10 | Regarding CWT performance of Tensorflow vs Pywavelet, Pywavelet is about 13 times faster. However, this is a CPU only benchmark without using performance extensions, like AVX, on Tensorflow. 11 | 12 | | Col1 | Col2 | Result | Notes | 13 | | ------------- |:-------------:| -----:| --- | 14 | | Tensorflow CWT (GPU) | Tensorflow CWT (CPU) | GPU ~8x faster | old i5 vs GTX 750 TI ~1,400 GFLOPS | 15 | | Tensorflow CWT (CPU) | Pywavelet CWT (CPU) | Pywavelet CWT ~13x faster | Tensorflow w/o AVX extensions, etc | 16 | | Tensorflow CWT (CPU) | Pywavelet DWT (CPU) | Pywavelet DWT ~200,000x faster | Haar wavelet; Tensorflow w/o AVX extensions, etc | 17 | 18 | ### Benchmark times 19 | This can be aquired by running `python benchmark.py` 20 | 21 | * DWT - sampleSize = 10000000 22 | * pywavelet dwt haar: 0.06824707984924316 23 | * pywavelet dwt db2: 0.08141493797302246 24 | * pywavelet dwt db8: 0.14669179916381836 25 | * CWT - sampleSize = 10000; cwtWidth = 256 26 | * pywavelet cwt mortlet: 1.1284675598144531 27 | * tensorflow cwt mortlet: 14.783239364624023 28 | 29 | ## Examples 30 | * [wavExample.py](https://github.com/nickgeoca/cwt-tensorflow/blob/master/wavExample.py). The audio sample rate is scaled down to 8000 samples per second (instead of typical 44100). 31 | 32 | * [sinExample.py](https://github.com/nickgeoca/cwt-tensorflow/blob/master/sinExample.py). It produces the plot below. The wavelet used is shown below (scale=32). 33 | ![](https://github.com/nickgeoca/cwt-tensorflow/blob/master/mortletCWT.png) 34 | 35 | ## Notes 36 | * The wavelet can be undersampled if the scale is too small. An example of this is seen below- the scale was set to 1. 37 | 38 | 39 | ## Dev Notes 40 | * This cwt and scipy's cwt both limit the Ricker wavelet samples to 10x the scale size to improve accuracy. 41 | 42 | ## TODO 43 | * Add this line of code similar to scipy's [cwt](https://github.com/scipy/scipy/blob/63bcdc4eeafa59553c00e44343dbb38380bd9d45/scipy/signal/wavelets.py#L362): samples = min(10*width, len(wav)) 44 | * consier scipy's ability to specify the wavelet scale 45 | ```python 46 | # Scipy's cwt can specify the wavelet scales in detail. This api can't do that. 47 | cwt(wav, signal.ricker, [1,1.5,2,2.5,3]) 48 | # This api is equivilent to calling scipy's cwt as below. 49 | cwt(wav, signal.ricker, range(1,n)) 50 | ``` 51 | * Maybe add 2d verison 52 | -------------------------------------------------------------------------------- /audioExample.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import matplotlib.pyplot as plt 3 | import numpy as np 4 | import scipy.signal as signal 5 | import scipy.io.wavfile as wf 6 | from cwt import cwtMortlet, cwtRicker 7 | 8 | # Create 1-D wave 9 | sampleRate,signal = wf.read('hendrixRiff.wav') 10 | sampleCount = len(signal) 11 | cwtWidth = 64 12 | 13 | # Create tensorflow ops 14 | cwtOp = cwtMortlet(tf.float32, signal, cwtWidth) 15 | 16 | # Run tensorflow 17 | sess = tf.Session() 18 | cwt = sess.run(cwtOp) 19 | sess.close() 20 | 21 | # Plot signal, wavelet, cwt 22 | f, axarr = plt.subplots(2, sharex=True) 23 | 24 | axarr[0].plot(signal) 25 | axarr[0].set_title('Signal') 26 | 27 | axarr[1].imshow(cwt, aspect='auto', interpolation='none') 28 | axarr[1].set_title('CWT') 29 | 30 | f.subplots_adjust(hspace=0.3, left=.1, bottom=.05, top=.95, right=.95) 31 | plt.show() 32 | -------------------------------------------------------------------------------- /benchmark.py: -------------------------------------------------------------------------------- 1 | import pywt 2 | import time 3 | import numpy as np 4 | from cwt import cwtMortlet, cwtRicker, mortletWavelet, rickerWavelet 5 | import tensorflow as tf 6 | 7 | sampleSize = 10000 8 | cwtWidth = 256 9 | signal = np.sin(np.arange(sampleSize) / 20.) 10 | 11 | start = time.time() 12 | a = pywt.dwt(signal, 'haar') 13 | end = time.time() 14 | print('pywt dwt haar: ' + str(end - start)) 15 | 16 | start = time.time() 17 | a = pywt.dwt(signal, 'db2') 18 | end = time.time() 19 | print('pywt dwt db2: ' + str(end - start)) 20 | 21 | start = time.time() 22 | a = pywt.dwt(signal, 'db8') 23 | end = time.time() 24 | print('pywt dwt db8: ' + str(end - start)) 25 | 26 | start = time.time() 27 | coef, freqs=pywt.cwt(signal,np.arange(1,1+cwtWidth),'morl') 28 | end = time.time() 29 | print('pywt cwt mortlet: ' + str(end - start)) 30 | 31 | cwtOp = cwtMortlet(tf.float32, signal, cwtWidth) 32 | sess = tf.Session() 33 | start = time.time() 34 | cwt = sess.run(cwtOp) 35 | end = time.time() 36 | sess.close() 37 | print('tf cwt mortlet: ' + str(end - start)) 38 | 39 | -------------------------------------------------------------------------------- /cwt.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import numpy as np 3 | 4 | # Run the cwtRicker, cwtMortlet 5 | 6 | """ 7 | Continuous Wavelet Transforms 8 | Parameters 9 | ---------- 10 | wav: matrix - float32 - shape (N,) 11 | widthCwt: scalar - int32 12 | 13 | Returns 14 | ------- 15 | output: matrix - float32 - shape (widthCwt, N) 16 | """ 17 | def cwtRicker(tfType, wav, widthCwt): return cwt(tfType, wav, widthCwt, rickerWavelet) 18 | def cwtMortlet(tfType, wav, widthCwt): return cwt(tfType, wav, widthCwt, mortletWavelet) 19 | 20 | # ------------------------------------------------------ 21 | 22 | def cwt(tfType, wav, widthCwt, wavelet): 23 | length = wav.shape[0] 24 | wav = tf.cast(wav, tfType) 25 | wav = tf.reshape(wav, [1,length,1,1]) 26 | 27 | # While loop functions 28 | def body(i, m): 29 | v = conv1DWavelet(tfType, wav, i, wavelet) 30 | v = tf.reshape(v, [length, 1]) 31 | 32 | m = tf.concat([m,v], 1) 33 | 34 | return [1 + i, m] 35 | 36 | def cond_(i, m): 37 | return tf.less_equal(i, widthCwt) 38 | 39 | # Initialize and run while loop 40 | emptyCwtMatrix = tf.zeros([length, 0], tfType) 41 | i = tf.constant(1) 42 | _, result = tf.while_loop( 43 | cond_, 44 | body, 45 | [i, emptyCwtMatrix], 46 | shape_invariants=[i.get_shape(), tf.TensorShape([length, None])], 47 | back_prop=False, 48 | parallel_iterations=1024, 49 | ) 50 | result = tf.transpose(result) 51 | 52 | return result 53 | 54 | # ------------------------------------------------------ 55 | # wavelets 56 | def rickerWavelet(tfType, scale, sampleCount): 57 | def waveEquation(time): 58 | time = cast(time, tfType) 59 | 60 | tSquare = time ** 2. 61 | sigma = 1. 62 | sSquare = sigma ** 2. 63 | 64 | # _1 = 2 / ((3 * a) ** .5 * np.pi ** .25) 65 | _1a = (3. * sigma) ** .5 66 | _1b = np.pi ** .25 67 | _1 = 2. / (_1a * _1b) 68 | 69 | # _2 = 1 - t**2 / a**2 70 | _2 = 1. - tSquare / sSquare 71 | 72 | # _3 = np.exp(-(t**2) / (2 * a ** 2)) 73 | _3a = -1. * tSquare 74 | _3b = 2. * sSquare 75 | _3 = tf.exp(_3a / _3b) 76 | 77 | return _1 * _2 * _3 78 | 79 | return waveletHelper(tfType, scale, sampleCount, waveEquation) 80 | 81 | def mortletWavelet(tfType, scale, sampleCount): 82 | def waveEquation(time): 83 | return tf.exp(-1. * time ** 2. / 2.) * tf.cos(5. * time) # https://www.mathworks.com/help/wavelet/ref/morlet.html 84 | 85 | return waveletHelper(tfType, scale, sampleCount, waveEquation) 86 | 87 | def waveletHelper(tfType, scale, sampleCount, waveEquation): 88 | scale = tf.cast(scale, tfType) 89 | sampleCount = tf.cast(sampleCount, tfType) 90 | unscaledTimes = tf.cast(tf.range(tf.to_int64(sampleCount)), tfType) - (sampleCount - 1.) / 2. 91 | times = unscaledTimes / scale 92 | wav = waveEquation(times) 93 | wav = wav * scale ** -.5 94 | return wav 95 | 96 | # ------------------------------------------------------ 97 | # helpers 98 | def conv1DWavelet(tfType, wav, waveletWidth, waveletEquation): 99 | kernelSamples = waveletWidth * 10 100 | kernel = waveletEquation(tfType, waveletWidth, kernelSamples) 101 | kernel = tf.reverse(kernel, [0]) 102 | kernel = tf.reshape(kernel, tf.stack([kernelSamples,1,1,1])) 103 | 104 | conv = tf.nn.convolution(wav, kernel, 'SAME') 105 | conv = tf.squeeze(tf.squeeze(conv)) 106 | 107 | return conv 108 | 109 | -------------------------------------------------------------------------------- /example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nickgeoca/cwt-tensorflow/0e5fca1c64b473ce3d56e539ed521171e08828c8/example.png -------------------------------------------------------------------------------- /hendrixRiff.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nickgeoca/cwt-tensorflow/0e5fca1c64b473ce3d56e539ed521171e08828c8/hendrixRiff.wav -------------------------------------------------------------------------------- /mortletCWT.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nickgeoca/cwt-tensorflow/0e5fca1c64b473ce3d56e539ed521171e08828c8/mortletCWT.png -------------------------------------------------------------------------------- /sinExample.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import matplotlib.pyplot as plt 3 | import numpy as np 4 | import scipy.signal as signal 5 | from cwt import cwtMortlet, cwtRicker, mortletWavelet, rickerWavelet 6 | 7 | # Create 1-D wave 8 | sampleSize = 1000 9 | cwtWidth = 256 10 | signal = np.sin(np.arange(sampleSize) / 20.) 11 | 12 | # Create tensorflow operations 13 | cwtOp = cwtMortlet(tf.float32, signal, cwtWidth) 14 | waveletOp = mortletWavelet(tf.float32, 32, sampleSize) # Scale value 32. We are using from 1 to 256 (cwtWidth parameter). After scale of 160 it gets less accurate with sampleSize of 1000 15 | 16 | # Run tensorflow 17 | sess = tf.Session() 18 | cwt = sess.run(cwtOp) 19 | wavelet = sess.run(waveletOp) 20 | sess.close() 21 | 22 | # Plot signal, wavelet, cwt 23 | f, axarr = plt.subplots(3, sharex=True) 24 | axarr[0].plot(signal) 25 | axarr[0].set_title('Signal') 26 | 27 | axarr[1].plot(wavelet) 28 | axarr[1].set_title('Wavelet') 29 | 30 | axarr[2].imshow(cwt, aspect='auto', interpolation='nearest') 31 | axarr[2].set_title('CWT') 32 | 33 | f.subplots_adjust(hspace=0.3, left=.1, bottom=.05, top=.95, right=.95) 34 | plt.show() 35 | -------------------------------------------------------------------------------- /undersampled-wavelet-p1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nickgeoca/cwt-tensorflow/0e5fca1c64b473ce3d56e539ed521171e08828c8/undersampled-wavelet-p1.png -------------------------------------------------------------------------------- /undersampled-wavelet-p2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nickgeoca/cwt-tensorflow/0e5fca1c64b473ce3d56e539ed521171e08828c8/undersampled-wavelet-p2.png --------------------------------------------------------------------------------