Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion bin/mule
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,12 @@ MULE pack runtime executable
Use 'mule --help' for more information
======================================''', formatter_class=argparse.RawTextHelpFormatter)

parser.add_argument("pack", choices = ['acq','proc','tests','ana'], help = '''The pack implemented:
parser.add_argument("pack", choices = ['acq','proc','tests','ana', 'vis'], help = '''The pack implemented:
acq - Acquisition of data using wavedump 1
proc - Processing of data
tests - Testing directory (IGNORE)
ana - Analysing data
vis - Visualise data
''')
parser.add_argument("config", help = 'The config file provided to the pack, this differs based on which pack youre using')
# acquire arguments
Expand Down
9 changes: 9 additions & 0 deletions packs/configs/vis_wd1_1channel.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[required]

visualise = 'waveform' # only 'waveform' as in single waveform so far
file_path = '../packs/tests/data/one_channel_WD1.h5'
vis_params = {
'baseline_sub' : 'median',
'sidebands' : ((100, 300), (2900, 3100)),
'negative' : False}

30 changes: 30 additions & 0 deletions packs/vis/vis.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import os
import sys
import traceback

from packs.core.io import read_config_file
from packs.core.core_utils import check_test
from packs.vis.visualise_utils import visualise_waveform
Comment on lines +5 to +7

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Super nitpicky, but try and align imports :)


def vis(config_file):
print("Starting the visualisation pack...")

# checks if test, if so ends run
if check_test(config_file):
return

# take full path
full_path = os.path.expandvars(config_file)

conf_dict = read_config_file(full_path)
# check the method implemented, currently just process
try:
match conf_dict.pop('visualise'):
case 'waveform':
visualise_waveform(**conf_dict)
case other:
raise RuntimeError(f"process {other} not currently implemented.")
except KeyError as e:
print(f"\nError in the configuration file, incorrect or missing argument: {e} \n")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are these cases (RunTimeError & KeyError) covered by a test?

I wrote some general ones for this sort of behaviour, but please double check :)

traceback.print_exc()
sys.exit(2)
Comment on lines +29 to +30

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can do something nicer with the handing, as they're duplicated across all differing packs. Might be an interesting job for @Tedsmith100 👀

110 changes: 110 additions & 0 deletions packs/vis/visualise_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import tkinter as tk
from tkinter import ttk

from packs.core.io import load_evt_info, load_rwf_info
from packs.proc.calibration_utils import subtract_baseline, collect_sidebands
Comment on lines +1 to +10

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Likewise try to align imports.

I find the inclusion of tk as shorthand for tkinter and the separate import of ttk a bit messy. I'm unsure of a nicer method right now other than using tk.ttk.___ every time you want to use that part of the library, which I think is also a bit ugly. Up to you on this front.


def visualise_waveform(file_path : str,
vis_params : dict):
"""
Launch an interactive Tkinter GUI for browsing raw waveforms from a file.

Parameters
----------
file_path : str
Path to the data file. Used to load event/waveform info.
vis_params : dict
Visualisation options:
- 'negative' (bool) – invert the waveform amplitude.
- 'baseline_sub' (str) – method for determining baseline, 'median' or 'mean'
Comment on lines +22 to +24

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The config and code also uses sidebands which aren't mentioned here.

"""
# supporting functions
# ---------------------------------------------------------------------------------
def plot_waveform(wf_num : int):
"""Clear the axes and draw waveform wf_num with baseline subtraction applied."""

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Functions within functions also should follow the standard documentation template :)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Extending on from that, I dislike the way these functions are defined internally referring to variables that are provided implicitly later in the function.

For example, wf_rwf is provided later in the external function (visualise_waveform()) but is not known of at this point, so for debugging this becomes annoying. The ax object that the whole function refers to is not generated or passed through as a function, which makes things confusing in the same way.

I've done something similar, but the linearity of the code needs to be retained. For example, this has been done in the writer(), but that has the function defined after the relevant variables are produced.

I'd recommend separating these functions (plot_waveform(), on_entry(), on_slider()) into visualise_utils.py so that they are all self-contained, and then require the relevant variables to be passed into them to function. That way, all used variables are required to be explicit, and it is consequently harder to miss any coding magic in the future.

ax.clear()
single_wf = wf_rwf['rwf'][wf_num]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What happens if the indexing here doesn't work as expected? There should be a try/catch/except case here, and a test that ensures the output for a faulty input doesn't produce a unintelligible error.

if vis_params['negative']:
single_wf = -single_wf

sideband_values = collect_sidebands(single_wf, time, vis_params)
single_wf = single_wf - subtract_baseline(sideband_values, sub_type = vis_params['baseline_sub'])
ax.plot(time, single_wf,
marker='.', markerfacecolor='blue', linestyle='-', markersize=0.1, linewidth=0.1)
ax.set_title(f'CH0 Waveform #{wf_num}') # one channel case for now
ax.set_xlabel('Time (ns)')
ax.set_ylabel('ADC or mV')
canvas.draw()

def on_entry(event : tk.Event | None = None):
"""Check and apply the waveform index, fixing the diagram to the valid range."""

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keep the documentation in the same style as normal functions :)

try:
val = int(entry_var.get())
val = max(0, min(val, max_wf))
entry_var.set(val)
slider_var.set(val)
plot_waveform(val)
except ValueError:
pass
Comment on lines +46 to +53

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pretty nice bit of code, I'd try and write a test that forces the ValueError, and checks that val does get set to 0 and the max_wf value if you give it some weird inputs.

For example, currently inputting strings doesn't do anything which isn't bad behaviour at all, but you may want to sanitise the inputs so people can't do anything malicious/stupid.


def on_slider(value : str | None = None):
"""Command for ttk.Scale. Sync the entry box to the slider position and redraw the selected waveform."""

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

likewise, make the comment a match the formatting :)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changed this to
ax.plot(time, single_wf, marker='.', markerfacecolor='blue', linestyle='-', markersize=0.1, linewidth=0.1)

val = slider_var.get()
entry_var.set(str(val))
plot_waveform(val)
# ---------------------------------------------------------------------------------

filename = (file_path.rsplit('.')[1]).rsplit('/')[0]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I bet I do the same thing somewhere, but there should be a more intelligent method for extracting the file name I think. This can be brushed into a new issue and applied universally at a later point.


# load event + waveform info
wf_evt = load_evt_info(file_path)
samples = int(wf_evt.loc[0].samples)
#sampling_period = float(wf_evt.loc[0].sampling_period)
sampling_period = 1
wf_rwf = load_rwf_info(file_path, samples)
Comment on lines +65 to +69

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning here generally, these functions aren't guaranteed to work with the h5 files in the future, as I'm trying to deprecate them for their lazy counterparts.

It may not be the wisest idea to load in a full h5 file to read one or two waveforms (which these functions do). I'd recommend adapting these to use the reader() methods of newer versions of MULE if possible.

print(f'file: {file_path}\nsamples: {samples}\nsampling_period: {sampling_period}')
max_wf = len(wf_rwf['rwf']) - 1
time = np.linspace(0,samples * sampling_period, num = samples)

# init GUI
root = tk.Tk()
root.title(f"Waveform Viewer — {filename}")

# generate plot
fig, ax = plt.subplots(layout='constrained', figsize=(8, 4))
canvas = FigureCanvasTkAgg(fig, master=root)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you may want your comments to be a bit more explicit here, this binds your matplotlib drawing space to the Tk() object root defined above.

canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

likewise, this line modifies your new Tk() object and allows whatever goes into it to fill the whole frame and expand with it as you adjust its size. This isn't obvious from the code alone, so may be worth commenting on.


# controls frame
ctrl = ttk.Frame(root, padding=8)
ctrl.pack(fill=tk.X)
Comment on lines +82 to +85

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Likewise, it would be worth commenting here on what this is doing, its taking control of the root frame and adding padding below it for a controller section.


ttk.Label(ctrl, text="Waveform #").pack(side=tk.LEFT)

# number entry
entry_var = tk.StringVar(value="0")

# controls entry
entry = ttk.Entry(ctrl, textvariable=entry_var, width=7)
entry.pack(side=tk.LEFT, padx=4)
entry.bind("<Return>", on_entry)
entry.bind("<FocusOut>", on_entry)
Comment on lines +95 to +96

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Likewise, I'd explain what the controls do here. Allows for adjustment of waveform via the editable number in the GUI


# slider
slider_var = tk.IntVar(value=0)

# controls slider
slider = ttk.Scale(ctrl, from_=0, to=max_wf, orient=tk.HORIZONTAL,
variable=slider_var, command=on_slider, length=400)
slider.pack(side=tk.LEFT, padx=8, fill=tk.X, expand=True)

ttk.Label(ctrl, text=f"(0 – {max_wf})").pack(side=tk.LEFT)

# draw initial waveform
plot_waveform(0)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should probably be a try/except here. I'd create a test for an incorrect file input (you want a specific error to be returned), or a h5 file with the correct path/group/node but the input doesn't work as expected.

root.mainloop()
Loading