summaryrefslogtreecommitdiff
path: root/bin/msp430-etv
blob: 597ddfb57a754ddff28e4747741244568530790f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
#!/usr/bin/env python3
# vim:tabstop=4 softtabstop=4 shiftwidth=4 textwidth=160 smarttab expandtab colorcolumn=160
#
# Copyright (C) 2020 Daniel Friesel
#
# SPDX-License-Identifier: GPL-2.0-or-later

"""msp430-etv - MSP430 EnergyTrace Visualizer

DESCRIPTION

msp430-etv takes energy measurements from an MSP430 Launchpad or similar device
using MSP430 EnergyTrace technology. Measurements can be taken directly (by
specifying <measurement duration> in seconds) or loaded from a logfile using
--load <file>. Data can be plotted or aggregated on stdout.

This program is not affiliated with Texas Instruments. Use at your own risk.

DEPENDENCIES

For data measurements (i.e., any invocation not using --load),
energytrace-util <https://ess.cs.uos.de/git/df/energytrace-util>
must be available in $PATH and libmsp430.so must be located in the
LD library search path (e.g. LD_LIBRARY_PATH=../MSP430Flasher).

OPTIONS
"""

import argparse
from bisect import bisect_left
import itertools
import json
import numpy as np
import os
from shutil import which
import subprocess
import sys
import tempfile
import time

matplotlib_theme = "fast"


def running_mean(x: np.ndarray, N: int) -> np.ndarray:
    """
    Compute `N` elements wide running average over `x`.

    :param x: 1-Dimensional NumPy array
    :param N: how many items to average. Should be even for optimal results.
    """

    # to ensure that output.shape == input.shape, we need to insert data
    # at the boundaries
    boundary_array = np.insert(x, 0, np.full((N // 2), x[0]))
    boundary_array = np.append(boundary_array, np.full((N // 2 + N % 2 - 1), x[-1]))

    return np.convolve(boundary_array, np.ones((N,)) / N, mode="valid")


class NpEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        else:
            return super(NpEncoder, self).default(obj)


def PELT_get_changepoints(algo, penalty):
    res = (penalty, algo.predict(pen=penalty))
    return res


class PELT:
    def __init__(self, signal, num_samples=None, stretch=1):
        self.signal = signal
        self.model = "l1"
        self.jump = 1
        self.min_dist = 1
        self.stretch = stretch

        if stretch != 1:
            self.signal = np.interp(
                np.linspace(0, len(signal) - 1, (len(signal) - 1) * stretch + 1),
                np.arange(len(signal)),
                self.signal,
            )

        if num_samples:
            self.ds_factor = len(signal) // num_samples
        else:
            self.ds_factor = 1

        self.jump = self.ds_factor

    def norm_signal(self, signal, scaler=25):
        max_val = max(np.abs(signal))
        normed_signal = np.zeros(shape=len(signal))
        for i, signal_i in enumerate(signal):
            normed_signal[i] = signal_i / max_val
            normed_signal[i] = normed_signal[i] * scaler
        return normed_signal

    def get_changepoints(self):
        # imported here as multiprocessing and ruptures are only used for changepoint detection
        from multiprocessing import Pool
        import ruptures

        algo = ruptures.Pelt(
            model=self.model, jump=self.jump, min_size=self.min_dist
        ).fit(self.norm_signal(self.signal))
        queue = list()
        for i in range(0, 100):
            queue.append((algo, i))
        with Pool() as pool:
            changepoints = pool.starmap(PELT_get_changepoints, queue)

        changepoints_by_penalty = dict()
        for res in changepoints:
            changepoints_by_penalty[res[0]] = res[1]
        num_changepoints = list()
        for i in range(0, 100):
            num_changepoints.append(len(changepoints_by_penalty[i]))

        # Find plateau
        start_index = -1
        end_index = -1
        longest_start = -1
        longest_end = -1
        prev_val = -1
        for i, num_bkpts in enumerate(num_changepoints):
            if num_bkpts != prev_val:
                end_index = i - 1
                if end_index - start_index > longest_end - longest_start:
                    # currently found sequence is the longest found yet
                    longest_start = start_index
                    longest_end = end_index
                start_index = i
            if i == len(num_changepoints) - 1:
                # end sequence with last value
                end_index = i
                # # since it is not guaranteed that this is the end of the plateau, assume the mid
                # # of the plateau was hit.
                # size = end_index - start_index
                # end_index = end_index + size
                # However this is not the clean solution. Better if search interval is widened
                # with range_min and range_max
                if end_index - start_index > longest_end - longest_start:
                    # last found sequence is the longest found yet
                    longest_start = start_index
                    longest_end = end_index
                start_index = i
            prev_val = num_bkpts
        middle_of_plateau = longest_start + (longest_start - longest_start) // 2
        changepoints = np.array(changepoints_by_penalty[middle_of_plateau])

        if len(changepoints) and changepoints[-1] == len(self.signal):
            changepoints = changepoints[:-1]

        if self.stretch != 1:
            changepoints = np.array(
                np.around(changepoints / self.stretch), dtype=np.int
            )

        return changepoints


def measure_data(
    filename,
    duration,
    libmsp430_path=None,
    energytrace_cmd="energytrace",
    live_view=False,
    live_history=10000,
):
    # libmsp430.so must be available
    if libmsp430_path is None:
        libmsp430_path = "/opt/msp430/MSP430Flasher_1.3.20"
    if "LD_LIBRARY_PATH" in os.environ:
        os.environ["LD_LIBRARY_PATH"] += f":{libmsp430_path}"
    else:
        os.environ["LD_LIBRARY_PATH"] = libmsp430_path

    # https://ess.cs.uos.de/git/df/energytrace-util must be available
    if which(energytrace_cmd) is None:
        energytrace_cmd = "{}/var/source/energytrace-util/{}".format(
            os.environ["HOME"], energytrace_cmd
        )

    if filename is not None:
        output_handle = open(filename, "w+")
    else:
        output_handle = tempfile.TemporaryFile("w+")

    if not duration:
        print("Press Ctrl+C to stop measurement")

    if live_view:
        import matplotlib.pyplot as plt

        plt.style.use(matplotlib_theme)
        max_y = 0
        plt.ion()

        timestamps = [0]
        voltages = [0]
        energy_values = [0]
        power_values = [0]

        plt.xlabel("Time [s]")
        plt.ylabel("Power [W]")
        (powerline,) = plt.plot(
            timestamps, power_values, "r-", label="Power [W]", markersize=1
        )
        plt.show()

        last_update = 0
        energytrace = subprocess.Popen(
            [energytrace_cmd, str(duration)],
            stdout=subprocess.PIPE,
            universal_newlines=True,
        )

        try:
            for line in energytrace.stdout:
                output_handle.write(line)

                if line[0] == "#":
                    continue
                timestamp, current, voltage, energy = line.split()
                timestamps.append(float(timestamp) / 1e6)
                voltages.append(float(voltage) / 1e3)
                energy_values.append(float(energy) / 1e9)

                if duration and timestamps[-1] > duration + 5:
                    break

                if energy_values[-1] > energy_values[-2]:
                    power_values.append(
                        (energy_values[-1] - energy_values[-2])
                        / (timestamps[-1] - timestamps[-2])
                    )
                else:
                    power_values.append(np.nan)

                if power_values[-1] > max_y:
                    max_y = power_values[-1]

                if live_history:
                    timestamps = timestamps[-live_history:]
                    voltages = voltages[-live_history:]
                    energy_values = energy_values[-live_history:]
                    power_values = power_values[-live_history:]

                if timestamps[-1] - last_update > 0.1:
                    update_start = time.time()
                    powerline.set_data([timestamps, power_values])
                    plt.xlim([timestamps[0], timestamps[-1]])
                    plt.ylim([0, max_y + 0.1])
                    plt.show()
                    plt.pause(0.01)
                    update_end = time.time()
                    last_update = timestamps[-1] + update_end - update_start
        except KeyboardInterrupt:
            print("Stopping measurement")
            energytrace.send_signal(subprocess.signal.SIGTERM)
    else:
        energytrace = subprocess.Popen(
            [energytrace_cmd, str(duration)],
            stdout=output_handle,
            universal_newlines=True,
        )

        try:
            if duration:
                time.sleep(duration)
            else:
                while True:
                    time.sleep(3600)
        except KeyboardInterrupt:
            print("Stopping measurement")
            energytrace.send_signal(subprocess.signal.SIGTERM)

    energytrace.communicate(timeout=5)

    output_handle.seek(0)
    output = output_handle.read()
    output_handle.close()

    return output


def export_json(filename, data=dict()):
    with open(filename, "w") as f:
        json.dump(data, f, cls=NpEncoder)


def detect_changepoints(timestamps, trace, num_samples):
    pelt = PELT(trace, num_samples=num_samples)
    changepoints = pelt.get_changepoints()
    prev = 0
    ret = list()
    for cp in changepoints:
        cp = cp - 1
        ret.append(
            {
                "interval": [timestamps[prev], timestamps[cp]],
                "mean": np.mean(trace[prev:cp]),
            }
        )
        prev = cp
    return ret


def peak_search(data, lower, upper, direction_function):
    while upper - lower > 1e-6:
        bs_test = np.mean([lower, upper])
        peakcount = itertools.groupby(data, lambda x: x >= bs_test)
        peakcount = filter(lambda x: x[0] == True, peakcount)
        peakcount = sum(1 for i in peakcount)
        direction = direction_function(peakcount, bs_test)
        if direction == 0:
            return bs_test
        elif direction == 1:
            lower = bs_test
        else:
            upper = bs_test
    return None


def peak_search2(data, lower, upper, check_function):
    for power in np.arange(lower, upper, 1e-6):
        peakcount = itertools.groupby(data, lambda x: x >= power)
        peakcount = filter(lambda x: x[0] == True, peakcount)
        peakcount = sum(1 for i in peakcount)
        if check_function(peakcount, power) == 0:
            return power
    return None


def plot_changepoints_vlines(changepoints):
    X = list()
    for cp in changepoints:
        X.append(cp["interval"][1])
    return X


def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter, description=__doc__
    )
    parser.add_argument("--load", metavar="FILE", type=str, help="Load data from FILE")
    parser.add_argument(
        "--save", metavar="FILE", type=str, help="Save measurement data in FILE"
    )
    parser.add_argument(
        "--json-export",
        metavar="FILENAME",
        type=str,
        help="Export analysis results (e.g. changepoints) to JSON file",
    )
    parser.add_argument(
        "--libmsp430-path",
        metavar="DIRECTORY",
        type=str,
        help="Path to directory containing libmsp30.so",
    )
    parser.add_argument(
        "--skip",
        metavar="N",
        type=float,
        default=0,
        help="Skip the first N seconds of data. This is useful to avoid startup code influencing the results of a long-running measurement",
    )
    parser.add_argument(
        "--limit",
        type=float,
        metavar="N",
        help="Limit analysis to the first N seconds of data",
    )
    parser.add_argument(
        "--pelt",
        metavar="FREQ",
        type=int,
        help="Perform changepoint detection with FREQ Hz",
    )
    parser.add_argument(
        "--threshold",
        metavar="WATTS",
        type=str,
        help="Partition data into points with mean power >= WATTS and points with mean power < WATTS, and print some statistics. higher power is handled as peaks, whereas low-power measurements constitute the baseline. If WATTS is 'mean', the mean power of all measurements will be used",
    )
    parser.add_argument(
        "--threshold-peakcount",
        metavar="NUM",
        type=int,
        help="Automatically determine a threshold so that there are exactly NUM peaks. A peaks is a group of consecutive measurements with mean power >= threshold. WARNING: In general, there is more than one threshold value leading to exactly NUM peaks. If the difference between baseline and peak power is sufficiently high, this option should do what you mean[tm]",
    )
    parser.add_argument(
        "--plot",
        metavar="UNIT",
        choices=["U", "I", "P", "P/U"],
        help="Plot voltage / current / power over time",
    )
    parser.add_argument(
        "--stat",
        action="store_true",
        help="Print mean voltage, current, and power as well as total energy consumption",
    )
    parser.add_argument(
        "--histogram",
        metavar="N",
        type=int,
        help="Draw histograms of reported energy values per measurement interval (i.e., the differences between each pair of consecutive total energy readings), measurement interval duration, and mean power values per measurement interval (calculated from energy difference and duration). Each histogram uses N buckets",
    )
    parser.add_argument(
        "--with-hardware-states",
        action="store_true",
        help="Log CPU and peripheral states as well as energy readings. Requires EnergyTrace++ support. Reduces the sample rate to about 1 kHz.",
    )
    parser.add_argument(
        "--live-view",
        action="store_true",
        help="Plot live voltage/current data while the measurement is running. May cause lost samples at the end of the measurement.",
    )
    parser.add_argument(
        "--live-history",
        type=int,
        metavar="N",
        default=10000,
        help="Show up to N past samples in the live view. Less history → lower live view overhead → higher update rate. Set to 0 for unlimited history.",
    )
    parser.add_argument(
        "duration", type=int, nargs="?", help="Measurement duration in seconds"
    )

    args = parser.parse_args()

    if args.load is None and args.duration is None:
        print("Either --load or duration must be specified", file=sys.stderr)
        sys.exit(1)

    if args.threshold is not None and args.threshold != "mean":
        args.threshold = float(args.threshold)

    if args.load:
        if args.load.endswith(".xz"):
            import lzma

            with lzma.open(args.load, "rt") as f:
                log_data = f.read()
        else:
            with open(args.load, "r") as f:
                log_data = f.read()
    elif args.with_hardware_states:
        log_data = measure_data(
            args.save,
            args.duration,
            libmsp430_path=args.libmsp430_path,
            energytrace_cmd="energytracepp",
            live_view=args.live_view,
            live_history=args.live_history,
        )
    else:
        log_data = measure_data(
            args.save,
            args.duration,
            libmsp430_path=args.libmsp430_path,
            live_view=args.live_view,
            live_history=args.live_history,
        )

    lines = log_data.split("\n")
    data_count = sum(map(lambda x: len(x) > 0 and x[0] != "#", lines))
    data_lines = filter(lambda x: len(x) > 0 and x[0] != "#", lines)

    data = np.empty((data_count, 4))
    annotations = [None for i in range(data_count)]
    skip_offset = 0
    limit_index = data_count

    energy_overflow_count = 0
    prev_total_energy = 0
    for i, line in enumerate(data_lines):
        fields = line.split(" ")
        if len(fields) == 4:
            timestamp, current, voltage, total_energy = map(int, fields)
        elif len(fields) == 5:
            annotations[i] = fields[0]
            timestamp, current, voltage, total_energy = map(int, fields[1:])
        else:
            raise RuntimeError('cannot parse line "{}"'.format(line))
        if total_energy < 0 and prev_total_energy > 0:
            energy_overflow_count += 1
        prev_total_energy = total_energy
        total_energy += energy_overflow_count * (2 ** 32)

        if args.skip is not None and timestamp * 1e-6 < args.skip:
            skip_offset = i + 1
            continue

        if args.limit is not None and timestamp * 1e-6 > args.limit:
            limit_index = i - 1
            break

        data[i] = [timestamp, current, voltage, total_energy]

    data = data[skip_offset:limit_index]
    annotations = annotations[skip_offset:limit_index]

    m_duration_us = data[-1, 0] - data[0, 0]
    m_energy_nj = data[-1, 3] - data[0, 3]

    print(
        "{:d} measurements in {:.2f} s = {:.0f} Hz sample rate".format(
            len(data), m_duration_us * 1e-6, len(data) / (m_duration_us * 1e-6)
        )
    )

    print("Reported energy: E = {:f} J".format(m_energy_nj * 1e-9))

    # nJ / us = mW -> (nJ * 1e-9) / (us * 1e-6) = W
    # Do not use power = data[:, 1] * data[:, 2] * 1e-12 here: nA values provided by the EnergyTrace library in data[:, 1] are heavily filtered and mostly
    # useless for visualization and calculation. They often do not agree with the nJ values in data[:, 3].
    power = ((data[1:, 3] - data[:-1, 3]) * 1e-9) / (
        (data[1:, 0] - data[:-1, 0]) * 1e-6
    )

    if args.threshold_peakcount:
        bs_mean = np.mean(power)

        # Finding the correct threshold is tricky. If #peaks < peakcont, our
        # current threshold may be too low (extreme case: a single peaks
        # containing all measurements), but it may also be too high (extreme
        # case: a single peak containing just one data point). Similarly,
        # #peaks > peakcount may be due to baseline noise causing lots of
        # small peaks, or due to peak noise (if the threshold is already rather
        # high).
        # For now, we first try a simple binary search:
        # The threshold is probably somewhere around the mean, so if
        # #peaks != peakcount and threshold < mean, we go up, and if
        # #peaks != peakcount and threshold >= mean, we go down.
        # If that doesn't work, we fall back to a linear search in 1 µW steps
        def direction_function(peakcount, power):
            if peakcount == args.threshold - peakcount:
                return 0
            if power < bs_mean:
                return 1
            return -1

        threshold = peak_search(power, np.min(power), np.max(power), direction_function)
        if threshold == None:
            threshold = peak_search2(
                power, np.min(power), np.max(power), direction_function
            )

        if threshold != None:
            print(
                "Threshold set to {:.0f} µW         : {:.9f}".format(
                    threshold * 1e6, threshold
                )
            )
            args.threshold = threshold
        else:
            print("Found no working threshold")

    if args.threshold:
        if args.threshold == "mean":
            args.threshold = np.mean(power)
            print(
                "Threshold set to {:.0f} µW         : {:.9f}".format(
                    args.threshold * 1e6, args.threshold
                )
            )

        baseline_mean = 0
        if np.any(power < args.threshold):
            baseline_mean = np.mean(power[power < args.threshold])
            print(
                "Baseline mean: {:.0f} µW           : {:.9f}".format(
                    baseline_mean * 1e6, baseline_mean
                )
            )
        if np.any(power >= args.threshold):
            print(
                "Peak mean: {:.0f} µW               : {:.9f}".format(
                    np.mean(power[power >= args.threshold]) * 1e6,
                    np.mean(power[power >= args.threshold]),
                )
            )

        peaks = []
        peak_start = -1
        for i, dp in enumerate(power):
            if dp >= args.threshold and peak_start == -1:
                peak_start = i
            elif dp < args.threshold and peak_start != -1:
                peaks.append((peak_start, i))
                peak_start = -1

        total_energy = 0
        delta_energy = 0
        for peak in peaks:
            duration = data[peak[1] - 1, 0] - data[peak[0], 0]
            total_energy += np.mean(power[peak[0] : peak[1]]) * duration
            delta_energy += (
                np.mean(power[peak[0] : peak[1]]) - baseline_mean
            ) * duration
            print(
                "{:.2f}ms peak ({:f} -> {:f})".format(
                    duration * 1000, data[peak[0], 0], data[peak[1] - 1, 0]
                )
            )
            print(
                "    {:f} µJ / mean {:f} µW".format(
                    np.mean(power[peak[0] : peak[1]]) * duration * 1e6,
                    np.mean(power[peak[0] : peak[1]]) * 1e6,
                )
            )
        print(
            "Peak energy mean: {:.0f} µJ         : {:.9f}".format(
                total_energy * 1e6 / len(peaks), total_energy / len(peaks)
            )
        )
        print(
            "Average per-peak energy (delta over baseline): {:.0f} µJ         : {:.9f}".format(
                delta_energy * 1e6 / len(peaks), delta_energy / len(peaks)
            )
        )

    power_from_energy = ((data[1:, 3] - data[:-1, 3]) * 1e-9) / (
        (data[1:, 0] - data[:-1, 0]) * 1e-6
    )
    smooth_power = running_mean(power_from_energy, 10)

    if args.pelt is not None:
        power_changepoints = detect_changepoints(
            data[1:, 0] * 1e-6, power_from_energy, num_samples=args.pelt
        )
        print(f"Found {len(power_changepoints)} changepoints for power")
        current_changepoints = detect_changepoints(
            data[1:, 0] * 1e-6,
            power_from_energy / (data[1:, 2] * 1e-3),
            num_samples=args.pelt,
        )
        print(f"Found {len(current_changepoints)} changepoints for current")

    if args.stat:
        mean_voltage = np.mean(data[:, 2] * 1e-3)
        mean_power = np.mean(power_from_energy)
        current = power_from_energy / (data[1:, 2] * 1e-3)
        mean_current = np.mean(current)
        print(
            "Mean voltage: {:.2f} V       : {:.9f}".format(mean_voltage, mean_voltage)
        )
        print(
            "Mean current: {:.0f} µA       : {:.9f}".format(
                mean_current * 1e6, mean_current
            )
        )
        print(
            "Current prediction error: {:.0f} µA ({:.2f}%)".format(
                np.mean(np.abs(mean_current - current)) * 1e6,
                np.mean(
                    np.abs(mean_current - current)
                    / ((np.abs(current) + np.abs(mean_current)) / 2)
                )
                * 100,
            )
        )
        print(
            "Mean power: {:.0f} µW       : {:.9f}".format(mean_power * 1e6, mean_power)
        )
        print(
            "Total energy: {:f} J       : {:.9f}".format(
                m_energy_nj * 1e-9, m_energy_nj * 1e-9
            )
        )

    if args.stat and args.pelt is not None:
        for i, cp in enumerate(power_changepoints):
            interval = cp["interval"]
            mean = cp["mean"]
            duration = interval[1] - interval[0]
            print(
                f"Changepoint {i:2d}: {interval[0]:7.3f} -> {interval[1]:7.3f} ({duration:6.3f} s, {mean * 1e6:5.0f} µW)"
            )
        if len(power_changepoints):
            interval = (power_changepoints[-1]["interval"][1], data[-1, 0] * 1e-6)
            print(f"Tail          : {interval[0]:7.3f} -> {interval[1]:7.3f}")

    if args.json_export:
        extra_data = dict()
        if args.pelt is not None:
            extra_data["power_changepoints"] = power_changepoints
            extra_data["current_changepoints"] = current_changepoints
        export_json(args.json_export, extra_data)

    if args.plot:
        import matplotlib.pyplot as plt

        plt.style.use(matplotlib_theme)

        if annotations[0]:
            fig, ax = plt.subplots()
            timestamps = data[1:, 0] * 1e-6
            annotationbox = ax.annotate(
                "",
                xy=(0, 0),
                xytext=(20, 20),
                textcoords="offset points",
                bbox=dict(boxstyle="round", fc="w"),
                arrowprops=dict(arrowstyle="->"),
            )
            annotationbox.set_visible(True)

            def hover(event):
                if event.xdata and event.ydata:
                    annotationbox.set_visible(False)
                    annotationbox.xy = (event.xdata, event.ydata)
                    i = bisect_left(timestamps, event.xdata)
                    if i < len(annotations):
                        annotationbox.set_text(annotations[i])
                    annotationbox.get_bbox_patch().set_alpha(0.4)
                    annotationbox.set_visible(True)
                    fig.canvas.draw_idle()

            fig.canvas.mpl_connect("motion_notify_event", hover)

            prev_annotation = "0000000000000000"
            for i, annotation in enumerate(annotations):
                if (
                    annotation != prev_annotation
                    and annotation != "0000000000000000"
                    and prev_annotation != "0000000000000000"
                ):
                    plt.axvline(data[i, 0] * 1e-6, color="green")
                if annotation != "0000000000000000":
                    prev_annotation = annotation

        if args.plot == "U":
            # mV
            (energyhandle,) = plt.plot(
                data[1:, 0] * 1e-6, data[1:, 2] * 1e-3, "b-", label="U", markersize=1
            )
            (meanhandle,) = plt.plot(
                data[1:, 0] * 1e-6,
                running_mean(data[1:, 2], 10) * 1e-3,
                "r-",
                label="mean(U, 10)",
                markersize=1,
            )
            plt.legend(handles=[energyhandle, meanhandle])
            plt.ylabel("Voltage [V]")
        elif args.plot == "I":
            print(
                "Warning: The current reported by energytrace is aggressively smoothed and often inaccurate."
            )
            # nA
            (energyhandle,) = plt.plot(
                data[1:, 0] * 1e-6, data[1:, 1] * 1e-9, "b-", label="I", markersize=1
            )
            (meanhandle,) = plt.plot(
                data[1:, 0] * 1e-6,
                running_mean(data[1:, 1], 10) * 1e-9,
                "r-",
                label="mean(I, 10)",
                markersize=1,
            )
            plt.legend(handles=[energyhandle, meanhandle])
            plt.ylabel("Current [A]")
        elif args.plot == "P/U":
            X = data[1:, 0] * 1e-6
            Y = power_from_energy / (data[1:, 2] * 1e-3)
            (energyhandle,) = plt.plot(
                X,
                Y,
                "b-",
                label="I=ΔE/(Δt·U)",
                markersize=1,
            )
            (meanhandle,) = plt.plot(
                X,
                smooth_power / (data[1:, 2] * 1e-3),
                "r-",
                label="mean(I, 10)",
                markersize=1,
            )
            if args.pelt is not None:
                plt.vlines(
                    plot_changepoints_vlines(current_changepoints),
                    np.min(Y),
                    np.max(Y),
                    "g",
                    label="changepoints(I)",
                )
            plt.legend(handles=[energyhandle, meanhandle])
            plt.ylabel("Current [A]")
        else:
            X = data[1:, 0] * 1e-6
            Y = power_from_energy
            (energyhandle,) = plt.plot(
                X,
                Y,
                "b-",
                label="P=ΔE/Δt",
                markersize=1,
            )
            (meanhandle,) = plt.plot(
                X,
                smooth_power,
                "r-",
                label="mean(P, 10)",
                markersize=1,
            )
            if args.pelt is not None:
                plt.vlines(
                    plot_changepoints_vlines(power_changepoints),
                    np.min(Y),
                    np.max(Y),
                    "g",
                    label="changepoints(I)",
                )
            plt.legend(handles=[energyhandle, meanhandle])
            plt.ylabel("Power [W]")
        plt.xlabel("Time [s]")
        plt.grid(True)
        if args.load:
            plt.title(args.load)

        plt.show()

    if args.histogram:
        import matplotlib.pyplot as plt

        bin_count = args.histogram

        # On an MSP430FR5994 launchpad, energy is measured and reported with a
        # granularity of 200 / 300 / 400 nJ per pulse. Details are unclear.
        plt.title("EnergyTrace Data Analysis")
        plt.xlabel("Reported Energy per Measurement Interval [J]")
        plt.ylabel("Count")
        plt.hist((data[1:, 3] - data[:-1, 3]) * 1e-9, bins=bin_count)
        plt.show()

        # Data is transferred using a URB_BULK endpoint with five samples
        # per USB packet. There's about 1.4ms between consecutive packets
        # and 210 to 270 ms between most consecutive samples. The first sample
        # in a packet typically has a larger delta-t of ~400ms vs the last
        # sample in the previous packet.
        plt.title("EnergyTrace Data Analysis")
        plt.xlabel("Measurement Interval Duration [s]")
        plt.ylabel("Count")
        plt.hist((data[1:, 0] - data[:-1, 0]) * 1e-6, bins=bin_count)
        plt.show()

        plt.title("EnergyTrace Data Analysis")
        plt.xlabel("Mean Power per Measurement Interval [W]")
        plt.ylabel("Count")
        plt.hist(power_from_energy, bins=bin_count)
        plt.show()

        plt.title("Postprocessing via Running average (window size=10)")
        plt.xlabel("Mean Power per Measurement Interval [W]")
        plt.ylabel("Count")
        plt.hist(smooth_power, bins=bin_count)
        plt.show()


if __name__ == "__main__":
    main()