| 1 | import nixio |
| 2 | import numpy as np |
| 3 | import matplotlib.pyplot as plt |
| 4 | |
| 5 | |
| 6 | def record_data(samples, channels, dt): |
| 7 | data = np.zeros((samples, channels)) |
| 8 | t = np.arange(samples) * dt |
| 9 | for i in range(channels): |
| 10 | phase = i * 2 * np.pi / channels |
| 11 | data[:, i] = np.sin(2 * np.pi * t + phase) + (np.random.randn(samples) * 0.1) |
| 12 | |
| 13 | return data |
| 14 | |
| 15 | |
| 16 | def plot(data_array): |
| 17 | plot_samples = 5000 |
| 18 | channel_count = data_array.shape[1] |
| 19 | |
| 20 | time = data_array.dimensions[0].axis(plot_samples) |
| 21 | dt = data_array.dimensions[0].sampling_interval |
| 22 | labels = data_array.dimensions[1].labels |
| 23 | data = data_array[:plot_samples, :] |
| 24 | |
| 25 | fig = plt.figure(figsize=(5, 2.5)) |
| 26 | for channel in range(channel_count): |
| 27 | axis = fig.add_subplot(channel_count, 1, channel + 1) |
| 28 | axis.plot(time, data[:, channel], label=labels[channel], lw=0.2) |
| 29 | for sp in axis.spines.keys(): |
| 30 | axis.spines[sp].set_visible(False) |
| 31 | axis.set_xticks([]) |
| 32 | axis.set_yticks([]) |
| 33 | axis.set_ylim([-2, 2]) |
| 34 | axis.text(0.0, 0.5, labels[channel], rotation=0, fontsize=8, ha="right", transform=axis.transAxes) |
| 35 | |
| 36 | axis.spines["bottom"].set_visible(True) |
| 37 | axis.set_xticks(np.arange(0, plot_samples * dt + dt, plot_samples / 5 * dt, dtype=int)) |
| 38 | axis.set_xlabel("%s %s" % (data_array.dimensions[0].label, "[%s]" % data_array.dimensions[0].unit if data_array.dimensions[0].unit else "")) |
| 39 | fig.subplots_adjust(left=0.15, bottom=0.175, top=0.975, right=0.975) |
| 40 | plt.show() |
| 41 | |
| 42 | |
| 43 | def main(): |
| 44 | dt = 0.001 |
| 45 | chunk_samples = 1000 |
| 46 | number_of_channels = 10 |
| 47 | number_of_chunks = 100 |
| 48 | |
| 49 | nixfile = nixio.File.open("continuous_recording.nix", nixio.FileMode.Overwrite, compression=nixio.Compression.DeflateNormal) |
| 50 | block = nixfile.create_block("Session 1", "nix.recording_session") |
| 51 | data_array = block.create_data_array("multichannel_data", "nix.sampled.multichannel", dtype=nixio.DataType.Double, |
| 52 | shape=(chunk_samples, number_of_channels), label="voltage", unit="mV") |
| 53 | data_array.append_sampled_dimension(0.001, label="time", unit="s") |
| 54 | data_array.append_set_dimension(labels=["channel %i" % i for i in range(number_of_channels)]) |
| 55 | |
| 56 | chunks_recorded = 0 |
| 57 | while chunks_recorded < number_of_chunks: |
| 58 | data = record_data(chunk_samples, number_of_channels, dt) |
| 59 | if chunks_recorded == 0: |
| 60 | data_array.write_direct(data) |
| 61 | else: |
| 62 | data_array.append(data, axis=0) |
| 63 | chunks_recorded += 1 |
| 64 | print("recorded chunks %i: array shape %s" % (chunks_recorded, str(data_array.shape))) |
| 65 | |
| 66 | plot(data_array) |
| 67 | nixfile.close() |
| 68 | |
| 69 | if __name__ == "__main__": |
| 70 | main() |