|
| 1 | +# The MIT License (MIT) |
| 2 | +# |
| 3 | +# Copyright (c) 2016 Leon Jacobs |
| 4 | +# |
| 5 | +# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 6 | +# of this software and associated documentation files (the "Software"), to deal |
| 7 | +# in the Software without restriction, including without limitation the rights |
| 8 | +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 9 | +# copies of the Software, and to permit persons to whom the Software is |
| 10 | +# furnished to do so, subject to the following conditions: |
| 11 | +# |
| 12 | +# The above copyright notice and this permission notice shall be included in all |
| 13 | +# copies or substantial portions of the Software. |
| 14 | +# |
| 15 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 16 | +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 17 | +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 18 | +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 19 | +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 20 | +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 21 | +# SOFTWARE. |
| 22 | + |
| 23 | +from datetime import datetime |
| 24 | + |
| 25 | +import click |
| 26 | +import numpy |
| 27 | +import peakutils |
| 28 | + |
| 29 | +try: |
| 30 | + import matplotlib.pyplot as plt |
| 31 | + import matplotlib.animation as animation |
| 32 | + |
| 33 | + plotting = True |
| 34 | + |
| 35 | +except RuntimeError: |
| 36 | + plotting = False |
| 37 | + |
| 38 | + |
| 39 | +def _can_plot(): |
| 40 | + if not plotting: |
| 41 | + click.secho('Plotting library was not sucesfully imported.\n' |
| 42 | + 'Ensure your python installation can run `import ' |
| 43 | + 'matplotlib.pyplot` without errors.', fg='red') |
| 44 | + |
| 45 | + return False |
| 46 | + |
| 47 | + return True |
| 48 | + |
| 49 | + |
| 50 | +def generate_wave_graph(source, peaks): |
| 51 | + """ |
| 52 | + Generate a plot from a wave file source. |
| 53 | + Optionally, include peak calculations. |
| 54 | +
|
| 55 | + Source: |
| 56 | + https://github.com/MonsieurV/py-findpeaks/blob/master/tests/vector.py |
| 57 | +
|
| 58 | + :param source: |
| 59 | + :param peaks: |
| 60 | + :return: |
| 61 | + """ |
| 62 | + |
| 63 | + if not _can_plot(): |
| 64 | + return |
| 65 | + |
| 66 | + click.secho('Reading {} frames from source.'.format(source.getnframes()), fg='green') |
| 67 | + click.secho('Preparing plot.', fg='green', dim=True) |
| 68 | + |
| 69 | + # Read the source data |
| 70 | + signal = source.readframes(-1) |
| 71 | + signal = numpy.fromstring(signal, dtype=numpy.int16) |
| 72 | + |
| 73 | + _, ax = plt.subplots(1, 1, figsize=(8, 4)) |
| 74 | + ax.plot(signal, 'b', lw=1) |
| 75 | + |
| 76 | + # If we have to include peak information, calculate that |
| 77 | + if peaks: |
| 78 | + click.secho('Calculating peak information too.', dim=True) |
| 79 | + indexes = peakutils.indexes(signal, thres=0.02 / max(signal), min_dist=100) |
| 80 | + |
| 81 | + if indexes.size: |
| 82 | + label = 'peak' |
| 83 | + label = label + 's' if indexes.size > 1 else label |
| 84 | + ax.plot(indexes, signal[indexes], '+', mfc=None, mec='r', mew=2, ms=8, |
| 85 | + label='%d %s' % (indexes.size, label)) |
| 86 | + ax.legend(loc='best', framealpha=.5, numpoints=1) |
| 87 | + |
| 88 | + # Continue graphing the source information |
| 89 | + ax.set_xlim(-.02 * signal.size, signal.size * 1.02 - 1) |
| 90 | + ymin, ymax = signal[numpy.isfinite(signal)].min(), signal[numpy.isfinite(signal)].max() |
| 91 | + yrange = ymax - ymin if ymax > ymin else 1 |
| 92 | + ax.set_ylim(ymin - 0.1 * yrange, ymax + 0.1 * yrange) |
| 93 | + ax.set_xlabel('Frame #', fontsize=14) |
| 94 | + ax.set_ylabel('Amplitude', fontsize=14) |
| 95 | + |
| 96 | + # Finally, generate the graph |
| 97 | + plt.show() |
| 98 | + |
| 99 | + return |
| 100 | + |
| 101 | + |
| 102 | +def generage_saved_recording_graphs(source, count, series): |
| 103 | + """ |
| 104 | + Plot frames from a recording |
| 105 | +
|
| 106 | + :param source: |
| 107 | + :param count: |
| 108 | + :param series: |
| 109 | + :return: |
| 110 | + """ |
| 111 | + |
| 112 | + if not _can_plot(): |
| 113 | + return |
| 114 | + |
| 115 | + click.secho('Source Information:') |
| 116 | + click.secho('Recording Date: {}'.format(datetime.fromtimestamp(source['date'])), bold=True, fg='green') |
| 117 | + click.secho('Recording Frequency: {}'.format(source['frequency']), bold=True, fg='green') |
| 118 | + click.secho('Recording Baud: {}'.format(source['baud']), bold=True, fg='green') |
| 119 | + click.secho('Recording Framecount: {}'.format(source['framecount']), bold=True, fg='green') |
| 120 | + |
| 121 | + # If we dont have a series to plot, plot the number of frames |
| 122 | + # from the start to count |
| 123 | + if not series: |
| 124 | + data = source['frames'][:count] |
| 125 | + click.secho('Preparing Graph for {} plots...'.format(count)) |
| 126 | + else: |
| 127 | + start, end = series |
| 128 | + data = source['frames'][start:end] |
| 129 | + click.secho('Preparing Graph for {} plots from {} to {}...'.format(len(data), start, end)) |
| 130 | + |
| 131 | + # Place holder to check if we have set the first plot yet |
| 132 | + fp = False |
| 133 | + |
| 134 | + # Start the plot. |
| 135 | + fig = plt.figure(1) |
| 136 | + fig.canvas.set_window_title('Frame Data Comparisons') |
| 137 | + |
| 138 | + # Loop over the frames, plotting them |
| 139 | + for (index,), frame in numpy.ndenumerate(data): |
| 140 | + |
| 141 | + # If it is not the first plot, set it keep note of the |
| 142 | + # axo variable. This is the original plot. |
| 143 | + if not fp: |
| 144 | + |
| 145 | + axo = plt.subplot(len(data), 1, index + 1) |
| 146 | + axo.grid(True) |
| 147 | + axo.set_xlabel('Symbols') |
| 148 | + axo.set_ylabel('Aplitude') |
| 149 | + axo.xaxis.set_label_position('top') |
| 150 | + |
| 151 | + # Flip the first plot variable as this is done |
| 152 | + fp = True |
| 153 | + |
| 154 | + # If we have plotted before, set the new subplot and share |
| 155 | + # the X & Y axis with axo |
| 156 | + else: |
| 157 | + ax = plt.subplot(len(data), 1, index + 1, sharex=axo, sharey=axo) |
| 158 | + ax.grid(True) |
| 159 | + |
| 160 | + # Plot the data |
| 161 | + plt.plot(numpy.frombuffer(buffer=str(frame), dtype=numpy.int16)) |
| 162 | + |
| 163 | + # Show the plot! |
| 164 | + click.secho('Launching the graphs!') |
| 165 | + plt.show() |
0 commit comments