{"cells":[{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","collapsed":true,"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":false},"cell_type":"markdown","source":"# Signal and frequency data animation\n\nThis is a simple script to visualize the acoustic data (or a frequency band) changes over time.\n\n\n*Note: The animation does not work in the static result of the kernel (I replaced it with an animated gif), but you can execute the animations in kernel-editor mode.*\n\n\n-----------------------------------------------------------------------------------"},{"metadata":{"trusted":true},"cell_type":"code","source":"# idx [1..14] of the earthquake you'd like to animate\n# first (0) and last (15) are note full cycles!!!\nEARTHQUAKE = 1\n\n# Datapoints inside the window; Set this lower if you'd like to zoom in.\nWINDOW_SIZE = 150000\n\n# Window step size\nSTEP_SIZE = WINDOW_SIZE // 5\n\n# Refresh interval; lower=faster animation\nREFRESH_INTERVAL = 100","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":false,"trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\nfrom IPython.display import HTML\nfrom scipy import signal\n\nearthquakes = [5656574, 50085878, 104677356, 138772453, 187641820, 218652630, 245829585, 307838917,\n               338276287, 375377848, 419368880, 461811623, 495800225, 528777115, 585568144, 621985673]\n\ntrain_df = pd.read_csv('../input/train.csv', nrows=earthquakes[EARTHQUAKE + 1] - earthquakes[EARTHQUAKE],\n                       skiprows = earthquakes[EARTHQUAKE] + 1,\n                       names=['acoustic_data', 'ttf'],\n                       dtype={'acoustic_data': np.int16, 'time_to_failure': np.float32},)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Acoustic data animation"},{"metadata":{"_kg_hide-input":false,"trusted":true},"cell_type":"code","source":"%matplotlib inline\n\nad = train_df.acoustic_data.values#[::5]\nttf = train_df.ttf.values#[::5]\n\ndef animate(i):\n    line.set_ydata(ad[i*STEP_SIZE:i*STEP_SIZE + WINDOW_SIZE])\n    ax.set_xlabel('TTF {0:.8f}'.format(ttf[i*STEP_SIZE + WINDOW_SIZE]))\n\nfig, ax = plt.subplots(figsize=(9,4))\nax.set(xlim=(0,WINDOW_SIZE), ylim=(-175, 175))\n\nline = ax.plot(train_df.iloc[0:WINDOW_SIZE], lw=1)[0]\nanim = matplotlib.animation.FuncAnimation(fig, animate, frames=(len(ad) - WINDOW_SIZE) // STEP_SIZE,\n                                          interval=REFRESH_INTERVAL, repeat=True)\n\n# You can save the animation\n# anim.save('acoustic_data.gif', writer='imagemagick')\n\n# Show the animation (does not work in kernel)\n# plt.show()\n\n# Remove this plt.close() in your experiment.\nplt.close()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"![SignalAnim](https://i.imgur.com/5ndR48p.gif)"},{"metadata":{},"cell_type":"markdown","source":"## Frequency band animation"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Low, High \"bandpass\" frequencies\nFREQUENCY_BAND = (45000, 55000)","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":false,"trusted":true},"cell_type":"code","source":"%matplotlib inline\n\ndef animate_freqs(i):\n    x = ad[i*STEP_SIZE:i*STEP_SIZE + WINDOW_SIZE]\n    frequencies, power_spectrum = signal.periodogram(x, 4000000, scaling='spectrum')\n    idx = (frequencies >= FREQUENCY_BAND[0]) & (frequencies <= FREQUENCY_BAND[1])\n    line.set_data(frequencies[idx].astype(np.int32), power_spectrum[idx])\n    ax.set_xlabel('TTF {0:.8f}'.format(ttf[i*STEP_SIZE + WINDOW_SIZE]))\n\nfig, ax = plt.subplots(figsize=(9,4))\n\n# !!!! If you don't see anything on the plot, try to adjust the `ylim` argument !!!!\nax.set(xlim=FREQUENCY_BAND, ylim=(0, .005))\nax.set_title(\"{}Hz - {}Hz\".format(FREQUENCY_BAND[0], FREQUENCY_BAND[1]))\n\nfrequencies, power_spectrum = signal.periodogram(ad[0:WINDOW_SIZE], 4000000, scaling='spectrum')      \nidx = (frequencies >= FREQUENCY_BAND[0]) & (frequencies <= FREQUENCY_BAND[1])\nline = ax.plot(frequencies[idx].astype(np.int32), power_spectrum[idx], lw=1)[0]\n\nanim = matplotlib.animation.FuncAnimation(fig, animate_freqs, frames=(len(ad) - WINDOW_SIZE) // STEP_SIZE,\n                                          interval=REFRESH_INTERVAL, repeat=True)\n\n# You can save the animation\n# anim.save('frequency_{}_{}.gif'.format(FREQUENCY_BAND[0], FREQUENCY_BAND[1]), writer='imagemagick')\n\n\n# Show the animation (does not work in kernel)\n# plt.show()\n\n# Remove this plt.close() in your experiment.\nplt.close()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"![FrequencyAnim](https://i.imgur.com/zgdLQa2.gif)"},{"metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true},"cell_type":"code","source":"# This should help to adjust the ylim argument.\nfrequencies, power_spectrum = signal.periodogram(ad[0:WINDOW_SIZE], 4000000, scaling='spectrum')\nidx = (frequencies >= FREQUENCY_BAND[0]) & (frequencies <= FREQUENCY_BAND[1])\npd.Series(power_spectrum[idx]).describe()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Thanks for playing ;) Do not forget to vote!** "},{"metadata":{},"cell_type":"markdown","source":"."}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}