{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Installing Dependencies\n",
    "---\n",
    "The python libraries needed in order to run the notebook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install sinabs\n",
    "%pip install tonic\n",
    "%pip install tqdm\n",
    "%pip install ipywidgets\n",
    "%pip install matplotlib\n",
    "%pip install daiedge-vlab\n",
    "%pip install numpy==1.26.4\n",
    "\n",
    "import sys\n",
    "print(sys.version)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We import everything needed, setup the names of the exported files in advance and create the directory for the exported files\n",
    "\n",
    "The names can be changed but the file extension must remain correct (see comments '#')\n",
    "\n",
    "Finally, there is a flag to set if you want to go through the training part of the model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Main python libraries\n",
    "import io, os\n",
    "from pathlib import Path\n",
    "from collections import defaultdict, Counter\n",
    "# Dependencies\n",
    "from tqdm.notebook import tqdm\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import pickle\n",
    "import torch\n",
    "from torch import nn\n",
    "from torch.optim import SGD\n",
    "from torch.nn import CrossEntropyLoss\n",
    "from torch.utils.data import DataLoader, Subset\n",
    "from tonic.transforms import ToFrame\n",
    "from tonic.datasets.nmnist import NMNIST\n",
    "from daiedge_vlab import dAIEdgeVLabAPI\n",
    "# Model Specific\n",
    "import samna\n",
    "from sinabs.from_torch import from_model\n",
    "\n",
    "# Main directories\n",
    "ROOT_DIR = \".\"\n",
    "EXPORT_DIR = os.path.join(ROOT_DIR, \"saves\")\n",
    "\n",
    "MODEL_FILENAME = \"vlab_nmnist.pth\" # Must end with '.pth'\n",
    "DATASET_FILENAME = \"NMNIST_DVS.pkl\" # Must end with '.pkl'\n",
    "WEIGHTS_FILENAME = \"cnn_weights.pt\" # Must end with '.pt'\n",
    "# Saving paths\n",
    "MODEL_SAVE_PATH = os.path.join(EXPORT_DIR, MODEL_FILENAME)\n",
    "DATASET_SAVE_PATH = os.path.join(EXPORT_DIR, DATASET_FILENAME)\n",
    "\n",
    "# Create export folder\n",
    "os.makedirs(EXPORT_DIR, exist_ok=True)\n",
    "\n",
    "RUN_TRAINING = False"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# <u><i>CNN model/dataset</u></i>\n",
    "## Creating the CNN architecture\n",
    "It is recommended to define the layers explicitly, since the Spikial Neural Network (SNN) conversion cannot be done on certain types of layers.\n",
    "\n",
    "It should follow following architecture :\n",
    "Conv -> ReLU (-> Pooling)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define a CNN model\n",
    "cnn = nn.Sequential(\n",
    "    # [2,34,34] -> [8, 17 ,17]\n",
    "    nn.Conv2d(in_channels=2, out_channels=8, kernel_size=(3,3), padding=(1,1), bias=False),\n",
    "    nn.ReLU(),\n",
    "    nn.AvgPool2d(2,2),\n",
    "    # [8,17,17] -> [16,8,8]\n",
    "    nn.Conv2d(in_channels=8, out_channels=16, kernel_size=(3,3), padding=(1,1), bias=False),\n",
    "    nn.ReLU(),\n",
    "    nn.AvgPool2d(2,2),\n",
    "    # [16 * 8 * 8] -> [16,4,4]\n",
    "    nn.Conv2d(in_channels=16, out_channels=16, kernel_size=(3,3), padding=(1,1), stride=(2,2), bias=False),\n",
    "    nn.ReLU(),\n",
    "    # [16*4*4] -> [10]\n",
    "    nn.Flatten(),\n",
    "    nn.Linear(16*4*4, 10, bias=False),\n",
    "    nn.ReLU()\n",
    ")\n",
    "INPUT_SHAPE = [2, 34, 34]\n",
    "\n",
    "for layer in cnn.modules():\n",
    "    if isinstance(layer, (nn.Conv2d, nn.Linear)):\n",
    "        nn.init.xavier_normal_(layer.weight.data)\n",
    "\n",
    "if not RUN_TRAINING:\n",
    "    # Weights must be placed in the same directory as this notebook\n",
    "    weights_path = Path.cwd().resolve() / WEIGHTS_FILENAME\n",
    "    # Loading the weights directly, training was already done beforehand to save time\n",
    "    cnn.load_state_dict(torch.load(weights_path, map_location='cpu'))\n",
    "    # Converting the CNN architecture to a Spikial Neural Network (SNN)\n",
    "    snn = from_model(cnn, batch_size=4).spiking_model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"Training\"></a>\n",
    "\n",
    "# <u><i>Training</u></i>\n",
    "## Create the classic dataset\n",
    "In this example, we use the NMNIST dataset (2x34x34), a variation on the MNIST dataset used specifically for Neuromorphic models. It differs from the original MNIST dataset which is 1x28x28, because the data needs to be slightly moving to activate the neurons, therefore using 2 channels and 34x34\n",
    "\n",
    "Here, the python library Tonic, allows the convertion to a classic representation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "if RUN_TRAINING:\n",
    "    # define a transform that accumulate the events into a single frame image\n",
    "    to_frame = ToFrame(sensor_size=NMNIST.sensor_size, n_time_bins=1)\n",
    "\n",
    "    cnn_train_dataset = NMNIST(save_to=ROOT_DIR, train=True, transform=to_frame)\n",
    "    cnn_test_dataset = NMNIST(save_to=ROOT_DIR, train=False, transform=to_frame)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Train CNN model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "if RUN_TRAINING:\n",
    "    epochs = 3\n",
    "    lr = 1e-3\n",
    "    batch_size = 4\n",
    "    num_worker = 4\n",
    "    shuffle = True\n",
    "\n",
    "    cnn_train_dataloader = DataLoader(cnn_train_dataset, batch_size=batch_size, num_workers=num_worker, drop_last=True, shuffle=shuffle)\n",
    "    cnn_test_dataloader = DataLoader(cnn_test_dataset, batch_size=batch_size, num_workers=num_worker, drop_last=True, shuffle=shuffle)\n",
    "\n",
    "    optimizer = SGD(params=cnn.parameters(), lr=lr)\n",
    "    criterion = CrossEntropyLoss()\n",
    "\n",
    "    for e in range(epochs):\n",
    "        # Training\n",
    "        train_p_bar = tqdm(cnn_train_dataloader)\n",
    "        for data, label in train_p_bar:\n",
    "\n",
    "            data = data.squeeze(dim=1).to(dtype=torch.float)\n",
    "            \n",
    "            optimizer.zero_grad()\n",
    "            output = cnn(data)\n",
    "            loss = criterion(output, label)\n",
    "\n",
    "            loss.backward()\n",
    "            optimizer.step()\n",
    "\n",
    "            train_p_bar.set_description(f\"Epoch {e} - Traning loss: {round(loss.item(), 4)}\")\n",
    "            \n",
    "        # Validation\n",
    "        correct_predictions = []\n",
    "        with torch.no_grad():\n",
    "            test_p_bar = tqdm(cnn_test_dataloader)\n",
    "            for data, label in test_p_bar:\n",
    "                data = data.squeeze(dim=1).to(dtype= torch.float)\n",
    "                \n",
    "                output = cnn(data)\n",
    "                pred = output.argmax(dim = 1, keepdim=True)\n",
    "                correct_predictions.append(pred.eq(label.view_as(pred)))\n",
    "                test_p_bar.set_description(f\"Epoch {e} - Testing model\")\n",
    "\n",
    "            correct_predictions = torch.cat(correct_predictions)\n",
    "            print(f\"Epoch {e} - accuracy: {correct_predictions.sum().item()/(len(correct_predictions))*100} %\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# <u><i>SNN model</u></i>\n",
    "## Convert CNN model to SNN model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "if RUN_TRAINING:\n",
    "    snn = from_model(model=cnn, batch_size=batch_size).spiking_model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# <u><i>VLab Specific</u></i>\n",
    "## Create the VLab dataset\n",
    "To be able to perform a benchmark on the Speck DevKit, the dataset has to be transformed into a list of events.\n",
    "That is where the samna library comes into place"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "snn_test_dataset = NMNIST(save_to=ROOT_DIR, train=False)\n",
    "subset_indices = list(range(0,len(snn_test_dataset), 100)) # Take every 100th sample\n",
    "snn_test_dataset = Subset(snn_test_dataset, subset_indices)\n",
    "\n",
    "dataset_event_stream = []\n",
    "for events, label in snn_test_dataset:\n",
    "    image_event_stream = []\n",
    "    for ev in events:\n",
    "        dvs_ev = samna.speck2f.event.DvsEvent()\n",
    "        dvs_ev.x = ev['x']\n",
    "        dvs_ev.y = ev['y']\n",
    "        dvs_ev.timestamp = ev['t'] - events['t'][0]\n",
    "        dvs_ev.p = ev['p']\n",
    "        image_event_stream.append(dvs_ev)\n",
    "    dataset_event_stream.append([image_event_stream, label])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Export model & event dataset\n",
    "Once the model and dataset are ready, we can export them to be sent to the VLab for benchmarking\n",
    "\n",
    "### Model\n",
    "The SNN gets exported as a pytorch '.pth' file\n",
    "\n",
    "### Dataset\n",
    "We use pickle to save the dataset as a compact format '.pkl'\n",
    "\n",
    "### Parameters\n",
    "Inside the VLab, the SNN will get converted into a SpecksimNetwork. For this, we need the model's input shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "torch.save(snn, MODEL_SAVE_PATH)\n",
    "\n",
    "with open(DATASET_SAVE_PATH, \"wb\") as f:\n",
    "    pickle.dump(dataset_event_stream, f)\n",
    "    \n",
    "parameters = {\n",
    "    \"input_shape\" : INPUT_SHAPE\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Launch VLab benchmark\n",
    "In our case, the testing dataset contains enough values for 100 inferences, but only do 50.\n",
    "\n",
    "Of course, if the benchmark needed to be done on every single value, then the inference_number parameter can be changed"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "api = dAIEdgeVLabAPI(\"setup.yaml\")\n",
    "\n",
    "benchmark_id = api.startBenchmark(\n",
    "    target = \"speck2fdevkit\",\n",
    "    runtime = \"speck\",\n",
    "    model_path = MODEL_SAVE_PATH,\n",
    "    dataset = DATASET_SAVE_PATH,\n",
    "    parameters = parameters,\n",
    "    inference_number = 50\n",
    ")\n",
    "\n",
    "print(benchmark_id)\n",
    "result = api.waitBenchmarkResult(benchmark_id)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# <u><i>Results</u></i>\n",
    "## Get the results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "report = result[\"report\"]\n",
    "\n",
    "if report is None:\n",
    "    print(result[\"error_log\"])\n",
    "    print(result[\"user_log\"])\n",
    "    raise RuntimeError(\"Something went wrong while benchmarking model\")\n",
    "\n",
    "chip_layers_ordering = report[\"chip_layers_ordering\"]\n",
    "print(f\"Chip layers ordering: {chip_layers_ordering}\")\n",
    "\n",
    "raw_bytes = result[\"raw_output\"]\n",
    "buffer = io.BytesIO(raw_bytes)\n",
    "data = np.load(buffer, allow_pickle=True)\n",
    "\n",
    "spiking_activity = data['spiking_activity']\n",
    "power_monitoring = data['power_monitoring']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model Information"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model_size = report[\"model_size\"]/1e3 # Originaly in Bytes\n",
    "param_count = report[\"nb_parameters_model\"]\n",
    "accuracy = report[\"accuracy\"]\n",
    "power_cons_mW = report[\"power_consumption\"]*1e3 # Originaly in Watts\n",
    "power_cons_uW = power_cons_mW*1e3\n",
    "\n",
    "print(f\"Model Size: {model_size:.3f} KB\")\n",
    "print(f\"Parameter Count: {param_count}\")\n",
    "print(f\"Power Consumed: {power_cons_mW:.3f}mW ({power_cons_uW:.3f}uW)\")\n",
    "print(f\"Model Accuracy: {accuracy*100}%\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Spiking Activity Analysis through time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n_time_steps = 100\n",
    "inference_to_analyse = 0\n",
    "\n",
    "print(f\"Number of inferences: {len(spiking_activity)}\")\n",
    "print(f\"Inference analysed: {inference_to_analyse}\")\n",
    "\n",
    "monitored_events = spiking_activity[inference_to_analyse]\n",
    "print(f\"Total number of events for the inference: {len(monitored_events)}\")\n",
    "\n",
    "# Extract timestamps and layers\n",
    "timestamps = [e.timestamp for e in monitored_events]\n",
    "layers = [e.layer for e in monitored_events]\n",
    "\n",
    "# Get min and max timestamp\n",
    "min_t, max_t = min(timestamps), max(timestamps)\n",
    "print(f\"first value at {min_t}\")\n",
    "\n",
    "# Create 100 bins equally spaced\n",
    "bins = np.linspace(min_t, max_t, n_time_steps+1)  # 101 edges = 100 bins\n",
    "bin_centers = (bins[:-1] + bins[1:]) / 2  # for x-axis\n",
    "\n",
    "# Unique layers\n",
    "unique_layers = sorted(set(layers))\n",
    "\n",
    "# Count spikes per bin per layer\n",
    "counts = np.zeros((len(unique_layers), len(bins)-1), dtype=int)\n",
    "layer_to_idx = {layer: i for i, layer in enumerate(unique_layers)}\n",
    "\n",
    "for e in monitored_events:\n",
    "    bin_idx = np.searchsorted(bins, e.timestamp, side=\"right\") - 1\n",
    "    if 0 <= bin_idx < len(bins)-1:\n",
    "        counts[layer_to_idx[e.layer], bin_idx] += 1\n",
    "\n",
    "# Plot stacked bar chart\n",
    "bottom = np.zeros(len(bins)-1)\n",
    "\n",
    "plt.figure(figsize=(12, 6))\n",
    "for i, layer in enumerate(unique_layers):\n",
    "    plt.bar(bin_centers, counts[i],\n",
    "            bottom=bottom,\n",
    "            width=(bins[1] - bins[0]),  # bar width = bin size\n",
    "            align=\"center\",\n",
    "            label=f\"Layer {layer}\")\n",
    "    bottom += counts[i]\n",
    "\n",
    "plt.title(\"Spike activity per layer (stacked)\")\n",
    "plt.xlabel(\"Time [us]\")\n",
    "plt.xticks(ticks=np.arange(start=0, stop=max_t+1, step=round(max_t//6, -4)))\n",
    "plt.ylabel(\"Spike count\")\n",
    "plt.legend(loc='upper left')\n",
    "plt.axis([0, max_t, 0, 1.1 * bottom.max()])\n",
    "plt.tight_layout()\n",
    "plt.savefig(fname=\"spiking_activity_bar\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Spiking Activity Analysis through coodinates"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from matplotlib.ticker import MaxNLocator\n",
    "\n",
    "save_folder = ROOT_DIR\n",
    "image_name = \"heatmaps_layer_\"\n",
    "\n",
    "print(f\"Number of inferences: {len(spiking_activity)}\")\n",
    "print(f\"Inference analysed: {inference_to_analyse}\")\n",
    "\n",
    "events = spiking_activity[inference_to_analyse]\n",
    "print(f\"Total number of events for the inference: {len(events)}\")\n",
    "\n",
    "event_per_layer_count = Counter(event.layer for event in events)\n",
    "layers_concerned = list(event_per_layer_count.keys())\n",
    "print(f\"Layers concerned: {layers_concerned}\")\n",
    "print(f\"Number of events per layers: {dict(event_per_layer_count)}\")\n",
    "\n",
    "# iterate through every layer in the inference\n",
    "for layer_number in layers_concerned:\n",
    "    # obtain all spiking events / nb of features for current layer\n",
    "    layer_events = [event for event in events if event.layer == layer_number]\n",
    "    num_features = max(e.feature for e in layer_events) + 1\n",
    "\n",
    "    # get the highest value of x/y of feature maps\n",
    "    # used to size up the feature maps' grids\n",
    "    all_xs = [e.x for e in layer_events]\n",
    "    all_ys = [e.y for e in layer_events]\n",
    "    global_max_x = max(all_xs) if all_xs else 0\n",
    "    global_max_y = max(all_ys) if all_ys else 0\n",
    "    # actual values for grids\n",
    "    grid_height = global_max_y + 1\n",
    "    grid_width = global_max_x + 1\n",
    "\n",
    "    # iterate once through every feature map to get the highest value of activations\n",
    "    # useful to set the colorbar values (same max value for colorbar for every feature in the layer)\n",
    "    heatmaps = []\n",
    "    for feature in range(num_features):\n",
    "        filtered = [e for e in layer_events if e.feature == feature]\n",
    "\n",
    "        heatmap = np.zeros((grid_height, grid_width), dtype=int)\n",
    "        for e in filtered:\n",
    "            heatmap[e.y, e.x] += 1\n",
    "        heatmaps.append(heatmap)\n",
    "\n",
    "    # If zero activations in the feature set max to 1 (error handling)\n",
    "    global_max = max(hm.max() for hm in heatmaps) if heatmaps else 1\n",
    "    if global_max == 0:\n",
    "        global_max = 1\n",
    "\n",
    "    # Setup subplots\n",
    "    cols = min(num_features, 4)\n",
    "    rows = int(np.ceil(num_features / cols))\n",
    "    fig, axes = plt.subplots(rows, cols, figsize=(4*cols, 4*rows))\n",
    "    axes = np.atleast_2d(axes)\n",
    "\n",
    "    # Build every subplot\n",
    "    for feature in range(num_features):\n",
    "        heatmap = heatmaps[feature]\n",
    "        h, w = heatmap.shape\n",
    "        \n",
    "        ax = axes[feature // cols, feature % cols]\n",
    "        im = ax.imshow(heatmap, cmap='hot', origin='lower', vmin=0, vmax=global_max)\n",
    "        ax.set_title(f\"Feature {feature}\")\n",
    "        ax.set_xlabel(\"X\")\n",
    "        ax.set_ylabel(\"Y\")\n",
    "        # MaxNLocator is used to only show integer indexes\n",
    "        ax.xaxis.set_major_locator(MaxNLocator(integer=True, min_n_ticks=1, nbins=5))\n",
    "        ax.yaxis.set_major_locator(MaxNLocator(integer=True, min_n_ticks=1, nbins=5))\n",
    "\n",
    "        # Only show integers on the colorbar (since activations are only integers)\n",
    "        cbar = fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04)\n",
    "        cbar.locator = MaxNLocator(integer=True)\n",
    "        cbar.update_ticks()\n",
    "\n",
    "    # Delete unused / unbuilt grids\n",
    "    for f in range(num_features, rows*cols):\n",
    "        fig.delaxes(axes[f // cols, f % cols])\n",
    "\n",
    "    # Saving the image file to folder\n",
    "    plt.suptitle(f\"Spike Heatmaps - Layer {layer_number}\")\n",
    "    plt.tight_layout()\n",
    "    plt.savefig(f\"{save_folder}/{image_name}{layer_number}.png\", dpi=300)\n",
    "    plt.close()\n",
    "\n",
    "    print(f\"Saved heatmaps as {image_name}{layer_number}.png\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Power Consumption Analysis"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ['s_a', 'p_m']\n",
    "# Either on par with spiking_activity or power measurements\n",
    "GRAPH_AXIS = 'p_m'\n",
    "\n",
    "measurements = power_monitoring[inference_to_analyse]\n",
    "\n",
    "# Channel names\n",
    "p_track_name = [\"io\", \"ram\", \"logic\", \"pixel digital\", \"pixel analog\"]\n",
    "\n",
    "# Group data by channel\n",
    "data_by_channel = defaultdict(lambda: {\"timestamps\": [], \"values\": []})\n",
    "\n",
    "# Splitting measurements into their own channel's list\n",
    "for m in measurements:\n",
    "    data_by_channel[m.channel][\"timestamps\"].append(m.timestamp/1e6)\n",
    "    data_by_channel[m.channel][\"values\"].append(m.value*1e3)\n",
    "\n",
    "# Creation of a new figure\n",
    "plt.figure(num=\"Power Consumption\", figsize=(16, 6))\n",
    "\n",
    "# plotting measurements into graph\n",
    "# If unrecognised name, falling back to channel N\n",
    "for channel, data in data_by_channel.items():\n",
    "    label = p_track_name[channel] if channel < len(p_track_name) else f\"Channel {channel}\"\n",
    "    plt.plot(data[\"timestamps\"], data[\"values\"], label=label)\n",
    "\n",
    "# Obtaining max values for limiting graph lengths\n",
    "max_value = max([v for d in data_by_channel.values() for v in d[\"values\"]])\n",
    "max_timestamp = max([t for d in data_by_channel.values() for t in d[\"timestamps\"]])\n",
    "\n",
    "# Drawing the graph\n",
    "plt.title(f\"Idle Power: {power_cons_mW:.3f} mW\")\n",
    "plt.xlabel(\"time [s]\")\n",
    "plt.xticks(ticks=np.arange(start=0, stop=max_timestamp, step=0.05))\n",
    "plt.ylabel(\"power [mW]\")\n",
    "plt.axhline(y=power_cons_mW, linestyle='--', color='k')\n",
    "plt.legend(loc=\"upper right\", fontsize=10)\n",
    "\n",
    "if GRAPH_AXIS == 'p_m':\n",
    "    plt.axis([0, max_timestamp, 0, 1.1*max_value]) # On par with power measurements\n",
    "elif GRAPH_AXIS == 's_a':\n",
    "    plt.axis([0, max_t/1e6, 0, 1.1*max_value]) # On par with spiking activity (us to s)\n",
    "else:\n",
    "    raise ValueError(\"GRAPH_AXIS value not valid\")\n",
    "\n",
    "plt.grid(True)\n",
    "plt.tight_layout()\n",
    "plt.savefig(f\"power_consumption.png\", dpi=300)\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv (3.12.3)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
