diff --git a/LabGym/__main__.py b/LabGym/__main__.py index 0a806a41..179bf962 100644 --- a/LabGym/__main__.py +++ b/LabGym/__main__.py @@ -103,6 +103,10 @@ def main() -> None: wx.App() mywx.bring_wxapp_to_foreground() + # Establish Windows AppUserModelID / macOS Dock icon before any + # probe dialog or main window is shown (taskbar process identity only). + gui_main.setup_application_icons() + # Perform some pre-op sanity checks and probes of outside resources. probes.probes() diff --git a/LabGym/analyzebehavior.py b/LabGym/analyzebehavior.py index ee81788b..6df6b69c 100644 --- a/LabGym/analyzebehavior.py +++ b/LabGym/analyzebehavior.py @@ -53,10 +53,44 @@ contour_frame, generate_patternimage, generate_patternimage_all, + plot_state_transition_map, ) logger.debug('importing tools (done)') +PROBABILITY_HEATMAP_MISSING_COLOR = 'gray' +PROBABILITY_HEATMAP_MISSING_LEGEND = 'Gray: missing / non-finite' + + +def prepare_probability_heatmap_array(values): + '''Clip finite probabilities for linear 0–1 heat maps; mask non-finite values. + + Does not modify the input array. Finite values are clipped to + [0, 1]. NaN, inf, and -inf are masked rather than converted to + 0 or 1. + ''' + data = np.array(values, dtype=np.float64, copy=True) + finite = np.isfinite(data) + clipped = np.empty_like(data) + clipped[finite] = np.clip(data[finite], 0.0, 1.0) + clipped[~finite] = np.nan + return np.ma.masked_where(~finite, clipped) + + +def probability_heatmap_colormap(): + '''Return an inferno copy with gray for masked / non-finite cells.''' + import matplotlib.pyplot as plt + cmap = plt.get_cmap('inferno').copy() + cmap.set_bad(color=PROBABILITY_HEATMAP_MISSING_COLOR, alpha=1.0) + return cmap + + +def probability_heatmap_norm(): + '''Return a fixed linear 0–1 scale, independent of the plotted data.''' + from matplotlib.colors import Normalize + return Normalize(vmin=0.0, vmax=1.0) + + class AnalyzeAnimal(): def __init__(self): @@ -646,10 +680,171 @@ def categorize_behaviors(self,path_to_categorizer,uncertain=0,min_length=None): self.event_probability[n][i-continued_length:i]=[['NA',-1]]*continued_length continued_length=1 i+=1 + + self.export_probability_matrices(make_heatmap=True) print('Behavioral categorization completed!') self.log.append('Behavioral categorization completed!') + def export_probability_matrices(self, make_heatmap=True, max_frames_for_heatmap=6000): + + import os + import numpy as np + import pandas as pd + import matplotlib.pyplot as plt + from matplotlib.patches import Patch + + os.makedirs(self.results_path, exist_ok=True) + + behavior_names = list(self.all_behavior_parameters.keys()) + T = len(self.all_time) + + for ID in self.event_probability: + P = np.zeros((T, len(behavior_names)), dtype=np.float32) + + for k, behavior_name in enumerate(behavior_names): + probs = self.all_behavior_parameters[behavior_name]['probability'][ID] + P[:, k] = np.array(probs, dtype=np.float32) + + np.save( + os.path.join(self.results_path, f'probability_matrix_ID{ID}.npy'), + P + ) + + df = pd.DataFrame(P, columns=behavior_names) + df.insert(0, 'time_s', np.array(self.all_time)) + df.insert(0, 'frame', np.arange(T)) + df.to_csv( + os.path.join(self.results_path, f'probability_matrix_ID{ID}.csv'), + index=False, + float_format='%.4f' + ) + + if make_heatmap: + P_plot = P + stride = 1 + + if P_plot.shape[0] > max_frames_for_heatmap: + stride = int(np.ceil(P_plot.shape[0] / max_frames_for_heatmap)) + P_plot = P_plot[::stride, :] + + time_plot = np.array(self.all_time)[::stride] + + P_plot = prepare_probability_heatmap_array(P_plot) + P_plot = P_plot.T + + num_behaviors, num_frames = P_plot.shape + + fig_width = max(18, num_frames / 140) + fig_height = max(8, num_behaviors * 0.55) + + fig, ax = plt.subplots(figsize=(fig_width, fig_height), dpi=200) + + im = ax.imshow( + P_plot, + aspect='auto', + interpolation='nearest', + cmap=probability_heatmap_colormap(), + norm=probability_heatmap_norm() + ) + + ax.set_yticks(np.arange(-0.5, num_behaviors, 1), minor=True) + ax.grid( + which='minor', + axis='y', + color='white', + linestyle='-', + linewidth=2.2 + ) + + ax.set_xticks(np.arange(-0.5, num_frames, 1), minor=True) + ax.grid( + which='minor', + axis='x', + color='white', + linestyle='-', + linewidth=0.12, + alpha=0.25 + ) + + ax.tick_params(which='minor', bottom=False, left=False) + + if num_frames <= 50: + xticks = np.arange(num_frames) + else: + step = max(1, num_frames // 20) + xticks = np.arange(0, num_frames, step) + + ax.set_xticks(xticks) + + frame_labels = xticks * stride + time_labels = time_plot[xticks] + + ax.set_xticklabels( + [ + f'{frame}\n{time:.2f}s' + for frame, time in zip(frame_labels, time_labels) + ], + fontsize=9, + rotation=45, + ha='right' + ) + + ax.set_yticks(np.arange(num_behaviors)) + ax.set_yticklabels( + behavior_names, + fontsize=13, + fontweight='bold' + ) + + ax.set_xlabel( + 'Frame / Time (s)' if stride == 1 else f'Frame / Time (s), stride={stride}', + fontsize=14, + fontweight='bold' + ) + + ax.set_ylabel( + 'Behavior', + fontsize=14, + fontweight='bold' + ) + + ax.set_title( + f'Frame-Level Probability Matrix (ID {ID})', + fontsize=16, + fontweight='bold' + ) + + cbar = fig.colorbar(im, ax=ax, pad=0.02) + cbar.set_label( + 'Probability\n'+PROBABILITY_HEATMAP_MISSING_LEGEND, + fontsize=12, + fontweight='bold' + ) + cbar.ax.tick_params(labelsize=10) + ax.legend( + handles=[ + Patch( + facecolor=PROBABILITY_HEATMAP_MISSING_COLOR, + edgecolor='black', + label=PROBABILITY_HEATMAP_MISSING_LEGEND, + ) + ], + loc='upper right', + fontsize=8, + framealpha=0.85, + ) + + plt.tight_layout() + + plt.savefig( + os.path.join(self.results_path, f'probability_heatmap_ID{ID}.png'), + dpi=300, + bbox_inches='tight' + ) + + plt.close(fig) + def annotate_video(self,ID_colors,behavior_to_include,show_legend=True,interact_all=False): @@ -1125,7 +1320,7 @@ def export_results(self,normalize_distance=True,parameter_to_analyze=[]): if self.categorize_behavior: events_df=pd.DataFrame(self.event_probability,index=self.all_time) events_df.to_excel(os.path.join(self.results_path,'all_event_probability.xlsx'),float_format='%.2f',index_label='time/ID') - + all_parameters=[] if self.categorize_behavior: diff --git a/LabGym/analyzebehavior_dt.py b/LabGym/analyzebehavior_dt.py index d0d9ce2e..2b80a94a 100644 --- a/LabGym/analyzebehavior_dt.py +++ b/LabGym/analyzebehavior_dt.py @@ -39,6 +39,13 @@ import torch # Local application/library specific imports. +from .analyzebehavior import ( + PROBABILITY_HEATMAP_MISSING_COLOR, + PROBABILITY_HEATMAP_MISSING_LEGEND, + prepare_probability_heatmap_array, + probability_heatmap_colormap, + probability_heatmap_norm, + ) from .detector import Detector from .tools import ( crop_frame, @@ -48,6 +55,7 @@ generate_patternimage, generate_patternimage_all, generate_patternimage_interact, + plot_state_transition_map, ) @@ -1087,9 +1095,154 @@ def categorize_behaviors(self,path_to_categorizer,uncertain=0,min_length=None): continued_length=1 i+=1 + self.export_probability_matrices_dt() + print('Behavioral categorization completed!') self.log.append('Behavioral categorization completed!') + def export_probability_matrices_dt(self, make_heatmap=True, max_frames_for_heatmap=6000): + + import os + import numpy as np + import pandas as pd + import matplotlib.pyplot as plt + from matplotlib.patches import Patch + + os.makedirs(self.results_path, exist_ok=True) + + time_array = np.array(self.all_time) + T = len(time_array) + + for animal_name in self.event_probability: + + behavior_names = list(self.all_behavior_parameters[animal_name].keys()) + + for ID in self.event_probability[animal_name]: + + P = np.zeros((T, len(behavior_names)), dtype=np.float32) + + for k, behavior_name in enumerate(behavior_names): + probs = self.all_behavior_parameters[animal_name][behavior_name]['probability'][ID] + P[:, k] = np.array(probs, dtype=np.float32) + + np.save( + os.path.join(self.results_path, f'{animal_name}_probability_matrix_ID{ID}.npy'), + P + ) + + df = pd.DataFrame(P, columns=behavior_names) + df.insert(0, 'time_s', time_array) + df.insert(0, 'frame', np.arange(T)) + df.to_csv( + os.path.join(self.results_path, f'{animal_name}_probability_matrix_ID{ID}.csv'), + index=False, + float_format='%.4f' + ) + + if make_heatmap: + P_plot = P + stride = 1 + + if P_plot.shape[0] > max_frames_for_heatmap: + stride = int(np.ceil(P_plot.shape[0] / max_frames_for_heatmap)) + P_plot = P_plot[::stride, :] + + time_plot = time_array[::stride] + + P_plot = prepare_probability_heatmap_array(P_plot) + P_plot = P_plot.T + + num_behaviors, num_frames = P_plot.shape + + fig_width = max(18, num_frames / 140) + fig_height = max(8, num_behaviors * 0.55) + + fig, ax = plt.subplots(figsize=(fig_width, fig_height), dpi=200) + + im = ax.imshow( + P_plot, + aspect='auto', + interpolation='nearest', + cmap=probability_heatmap_colormap(), + norm=probability_heatmap_norm() + ) + + ax.set_yticks(np.arange(-0.5, num_behaviors, 1), minor=True) + ax.grid(which='minor', axis='y', color='white', linestyle='-', linewidth=2.2) + + ax.set_xticks(np.arange(-0.5, num_frames, 1), minor=True) + ax.grid(which='minor', axis='x', color='white', linestyle='-', linewidth=0.12, alpha=0.25) + + ax.tick_params(which='minor', bottom=False, left=False) + + if num_frames <= 50: + xticks = np.arange(num_frames) + else: + step = max(1, num_frames // 20) + xticks = np.arange(0, num_frames, step) + + ax.set_xticks(xticks) + + frame_labels = xticks * stride + time_labels = time_plot[xticks] + + ax.set_xticklabels( + [ + f'{frame}\n{time:.2f}s' + for frame, time in zip(frame_labels, time_labels) + ], + fontsize=9, + rotation=45, + ha='right' + ) + + ax.set_yticks(np.arange(num_behaviors)) + ax.set_yticklabels(behavior_names, fontsize=13, fontweight='bold') + + ax.set_xlabel( + 'Frame / Time (s)' if stride == 1 else f'Frame / Time (s), stride={stride}', + fontsize=14, + fontweight='bold' + ) + + ax.set_ylabel('Behavior', fontsize=14, fontweight='bold') + + ax.set_title( + f'Frame-Level Probability Matrix: {animal_name} ID {ID}', + fontsize=16, + fontweight='bold' + ) + + cbar = fig.colorbar(im, ax=ax, pad=0.02) + cbar.set_label( + 'Probability\n'+PROBABILITY_HEATMAP_MISSING_LEGEND, + fontsize=12, + fontweight='bold', + ) + cbar.ax.tick_params(labelsize=10) + ax.legend( + handles=[ + Patch( + facecolor=PROBABILITY_HEATMAP_MISSING_COLOR, + edgecolor='black', + label=PROBABILITY_HEATMAP_MISSING_LEGEND, + ) + ], + loc='upper right', + fontsize=8, + framealpha=0.85, + ) + + plt.tight_layout() + + plt.savefig( + os.path.join(self.results_path, f'{animal_name}_probability_heatmap_ID{ID}.png'), + dpi=300, + bbox_inches='tight' + ) + + plt.close(fig) + def correct_identity(self,specific_behaviors): diff --git a/LabGym/assets/icons/labgym.icns b/LabGym/assets/icons/labgym.icns index a1f45819..6d16f03a 100644 Binary files a/LabGym/assets/icons/labgym.icns and b/LabGym/assets/icons/labgym.icns differ diff --git a/LabGym/assets/icons/labgym.ico b/LabGym/assets/icons/labgym.ico index b46976ea..7fd62605 100644 Binary files a/LabGym/assets/icons/labgym.ico and b/LabGym/assets/icons/labgym.ico differ diff --git a/LabGym/assets/icons/labgym.png b/LabGym/assets/icons/labgym.png index cfdca7ed..3b4a8a6b 100644 Binary files a/LabGym/assets/icons/labgym.png and b/LabGym/assets/icons/labgym.png differ diff --git a/LabGym/categorizer.py b/LabGym/categorizer.py index 5a0c8124..501a6216 100644 --- a/LabGym/categorizer.py +++ b/LabGym/categorizer.py @@ -33,7 +33,7 @@ from scipy import ndimage from skimage import exposure,transform from skimage.transform import AffineTransform -from sklearn.metrics import classification_report +from sklearn.metrics import classification_report, confusion_matrix from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelBinarizer import tensorflow as tf @@ -223,6 +223,20 @@ def __getitem__(self,idx): +class CategorizerClassMismatchError(Exception): + """Raised when ground-truth folder names do not match Categorizer classes.""" + + def __init__(self, unrecognized_folders, missing_classes): + self.unrecognized_folders = sorted(unrecognized_folders) + self.missing_classes = sorted(missing_classes) + parts = [ + 'Behavior folder names must exactly match the Categorizer classes.', + f'Unrecognized behavior folders: {self.unrecognized_folders}.', + f'Model classes absent from the fixture: {self.missing_classes}.', + ] + super().__init__(' '.join(parts)) + + class Categorizers(): def __init__(self): @@ -1951,6 +1965,7 @@ def test_categorizer(self,groundtruth_path,model_path,result_path=None): animations=deque() pattern_images=deque() labels=deque() + test_files=[] parameters=pd.read_csv(os.path.join(model_path,'model_parameters.txt')) @@ -2018,79 +2033,197 @@ def test_categorizer(self,groundtruth_path,model_path,result_path=None): if len(incorrect_classes)>0: print('Unused behavior names in the Categorizer: '+str(incorrect_classes)) - if len(incorrect_behaviors)==0 and len(incorrect_classes)==0: + if len(incorrect_behaviors)>0 or len(incorrect_classes)>0: + raise CategorizerClassMismatchError(incorrect_behaviors, incorrect_classes) + + for behavior in behaviornames: + + if network!=0: + filenames=[i for i in os.listdir(os.path.join(groundtruth_path,behavior)) if i.endswith('.avi')] + else: + filenames=[i for i in os.listdir(os.path.join(groundtruth_path,behavior)) if i.endswith('.jpg')] + + for i in filenames: - for behavior in behaviornames: + test_files.append(os.path.join(groundtruth_path, behavior, i)) if network!=0: - filenames=[i for i in os.listdir(os.path.join(groundtruth_path,behavior)) if i.endswith('.avi')] - else: - filenames=[i for i in os.listdir(os.path.join(groundtruth_path,behavior)) if i.endswith('.jpg')] - for i in filenames: + path_to_animation=os.path.join(groundtruth_path,behavior,i) - if network!=0: + capture=cv2.VideoCapture(path_to_animation) + animation=deque() + frames=deque(maxlen=length) - path_to_animation=os.path.join(groundtruth_path,behavior,i) + while True: + retval,frame=capture.read() + if frame is None: + break + frames.append(frame) - capture=cv2.VideoCapture(path_to_animation) - animation=deque() - frames=deque(maxlen=length) + capture.release() - while True: - retval,frame=capture.read() - if frame is None: - break - frames.append(frame) + for frame in frames: + frame=np.uint8(exposure.rescale_intensity(frame,out_range=(0,255))) + if channel==1: + frame=cv2.cvtColor(np.uint8(frame),cv2.COLOR_BGR2GRAY) + frame=cv2.resize(frame,(dim_tconv,dim_tconv),interpolation=cv2.INTER_AREA) + frame=img_to_array(frame) + animation.append(frame) - capture.release() + animations.append(np.array(animation)) - for frame in frames: - frame=np.uint8(exposure.rescale_intensity(frame,out_range=(0,255))) - if channel==1: - frame=cv2.cvtColor(np.uint8(frame),cv2.COLOR_BGR2GRAY) - frame=cv2.resize(frame,(dim_tconv,dim_tconv),interpolation=cv2.INTER_AREA) - frame=img_to_array(frame) - animation.append(frame) + if network!=1: - animations.append(np.array(animation)) + path_to_pattern_image=os.path.splitext(os.path.join(groundtruth_path,behavior,i))[0]+'.jpg' + pattern_image=cv2.imread(path_to_pattern_image) + if behavior_mode==3: + if channel==1: + pattern_image=cv2.cvtColor(pattern_image,cv2.COLOR_BGR2GRAY) + pattern_image=cv2.resize(pattern_image,(dim_conv,dim_conv),interpolation=cv2.INTER_AREA) + pattern_images.append(img_to_array(pattern_image)) - if network!=1: + labels.append(classnames.index(behavior)) - path_to_pattern_image=os.path.splitext(os.path.join(groundtruth_path,behavior,i))[0]+'.jpg' - pattern_image=cv2.imread(path_to_pattern_image) - if behavior_mode==3: - if channel==1: - pattern_image=cv2.cvtColor(pattern_image,cv2.COLOR_BGR2GRAY) - pattern_image=cv2.resize(pattern_image,(dim_conv,dim_conv),interpolation=cv2.INTER_AREA) - pattern_images.append(img_to_array(pattern_image)) + if network!=0: + animations=np.array(animations,dtype='float32')/255.0 + pattern_images=np.array(pattern_images,dtype='float32')/255.0 - labels.append(classnames.index(behavior)) + labels=np.array(labels) - if network!=0: - animations=np.array(animations,dtype='float32')/255.0 - pattern_images=np.array(pattern_images,dtype='float32')/255.0 + model=load_model(model_path) - labels=np.array(labels) + from keras.models import Model + multi_model = Model(inputs=model.inputs, outputs=[model.layers[-2].output, model.output]) - model=load_model(model_path) + if network==0: + embeddings, predictions = multi_model.predict(pattern_images,batch_size=32) + elif network==1: + embeddings, predictions = multi_model.predict(animations,batch_size=32) + else: + embeddings, predictions = multi_model.predict([animations,pattern_images],batch_size=32) - if network==0: - predictions=model.predict(pattern_images,batch_size=32) - elif network==1: - predictions=model.predict(animations,batch_size=32) - else: - predictions=model.predict([animations,pattern_images],batch_size=32) - if len(classnames)==2: - predictions=[round(i[0]) for i in predictions] - print(classification_report(labels,predictions,target_names=classnames)) - report=classification_report(labels,predictions,target_names=classnames,output_dict=True) - else: - print(classification_report(labels,predictions.argmax(axis=1),target_names=classnames)) - report=classification_report(labels,predictions.argmax(axis=1),target_names=classnames,output_dict=True) + if len(classnames)==2: + predictions=[round(i[0]) for i in predictions] + flat_predictions = predictions + print(classification_report(labels,predictions,target_names=classnames)) + report=classification_report(labels,predictions,target_names=classnames,output_dict=True) + cm=confusion_matrix(labels,predictions) + else: + flat_predictions = predictions.argmax(axis=1) + print(classification_report(labels,flat_predictions,target_names=classnames)) + report=classification_report(labels,flat_predictions,target_names=classnames,output_dict=True) + cm=confusion_matrix(labels,flat_predictions) + + if result_path is not None: + pd.DataFrame(report).transpose().to_excel(os.path.join(result_path,'testing_reports.xlsx'),float_format='%.2f') + pd.DataFrame(cm, index=classnames, columns=classnames).to_csv(os.path.join(result_path,'confusion_matrix.csv')) - if result_path is not None: - pd.DataFrame(report).transpose().to_excel(os.path.join(result_path,'testing_reports.xlsx'),float_format='%.2f') + example_map = {} + embedding_map = {} + for t_label_idx, p_label_idx, f_path, emb in zip(labels, flat_predictions, test_files, embeddings): + key = (classnames[t_label_idx], classnames[p_label_idx]) + if key not in example_map: + example_map[key] = [] + example_map[key].append(f_path) + embedding_map[f_path] = emb + + print('Testing completed!') + + return report, cm, example_map, embedding_map + + def generate_probability_matrix(self, path_to_video, path_to_model, output_folder, batch_size=32): + """ + Frame-level probability matrix (T x K) using the trained Categorizer. + + Row: frame + Column: behavior class (order from model_parameters.txt) + Cell: softmax probability + + Saves: + - probability_matrix.npy + - probability_matrix.csv + - probability_heatmap.png + """ + + os.makedirs(output_folder, exist_ok=True) + + # --- Load model --- + model = load_model(path_to_model) + + # --- Load parameters (LabGym format) --- + param_path = os.path.join(os.path.dirname(path_to_model), "model_parameters.txt") + params = pd.read_csv(param_path) + + classnames = params["classnames"].dropna().astype(str).tolist() + dim_conv = int(params["dim_conv"].iloc[0]) + channel = int(params["channel"].iloc[0]) + K = len(classnames) + + # --- Read frames --- + capture = cv2.VideoCapture(path_to_video) + frames = [] + + while True: + ret, frame = capture.read() + if frame is None: + break + + if channel == 1: + frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) + + frame = cv2.resize(frame, (dim_conv, dim_conv), interpolation=cv2.INTER_AREA) + frame = frame.astype("float32") / 255.0 + + if channel == 1: + frame = np.expand_dims(frame, axis=-1) + + frames.append(frame) + + capture.release() + + X = np.asarray(frames, dtype=np.float32) + T = X.shape[0] + + if T == 0: + raise ValueError(f"No frames read from video: {path_to_video}") + + # --- Predict probabilities --- + P = model.predict(X, batch_size=batch_size, verbose=1) + + # Binary-sigmoid + if P.ndim== 2 and P.shape[1] == 1 and K == 2: + p1 = P[:, 0] + P = np.stack([1.0 - p1, p1], axis=1) + + if P.shape != (T, K): + raise ValueError(f"Probability matrix shape mismatch: got {P.shape}, expected {(T, K)}") + + # --- Save outputs --- + np.save(os.path.join(output_folder, "probability_matrix.npy"), P) + + df = pd.DataFrame(P, columns=classnames) + df.insert(0, "frame", np.arange(T)) + df.to_csv(os.path.join(output_folder, "probability_matrix.csv"), index=False) + + # --- Heatmap --- + from matplotlib.colors import LogNorm + + plt.figure(figsize=(12, 4)) + plt.imshow( + np.nan_to_num(P_plot, nan=0.0).T, + aspect='auto', + cmap='magma', + norm=LogNorm(vmin=1e-3, vmax=1) + ) + plt.colorbar(label="Probability") + plt.yticks(range(K), classnames) + plt.xlabel("Frame") + plt.ylabel("Behavior") + plt.title("Frame-Level Behavior Probability Heatmap") + plt.tight_layout() + plt.savefig(os.path.join(output_folder, "probability_heatmap.png"), dpi=200) + plt.close() - print('Testing completed!') + return P diff --git a/LabGym/config.py b/LabGym/config.py index d412a8d0..0b478119 100644 --- a/LabGym/config.py +++ b/LabGym/config.py @@ -40,7 +40,10 @@ # tomllib is included in the Python Standard Library since version 3.11 import tomllib # type: ignore except ModuleNotFoundError: - import tomli as tomllib # A lil' TOML parser + try: + import tomli as tomllib # A lil' TOML parser + except ModuleNotFoundError: + tomllib = None # Related third party imports. import yaml # PyYAML, YAML parser and emitter for Python @@ -121,6 +124,8 @@ def get_config_from_configfile(configfile: Path) -> dict: parser = configparser.ConfigParser() result = parser.read(configfile) elif configfile.name.endswith('.toml'): + if tomllib is None: + raise ModuleNotFoundError("TOML support requires Python >= 3.11 or the 'tomli' package. Please install it with: pip install tomli") with open(configfile, 'rb') as f: result = tomllib.load(f) elif configfile.name.endswith('.yaml'): diff --git a/LabGym/gui_analyzer.py b/LabGym/gui_analyzer.py index 7e492186..f14905b1 100644 --- a/LabGym/gui_analyzer.py +++ b/LabGym/gui_analyzer.py @@ -22,6 +22,8 @@ import logging import os from pathlib import Path +from tkinter import dialog +import numpy as np # Log the load of this module (by the module loader, on first import). # Intentionally positioning these statements before other imports, against the @@ -40,7 +42,15 @@ from .analyzebehavior_dt import AnalyzeAnimalDetector from LabGym import config from .minedata import data_mining -from .tools import plot_events, parse_all_events_file, calculate_distances +from .tools import ( + plot_events, + parse_all_events_file, + calculate_distances, + plot_state_transition_map, + stm_session_colors, + stm_default_behavior_color, +) +from .gui_utils import add_info_button, INFO_COLOUR_S3, INFO_COLOUR_S4 class ColorPicker(wx.Dialog): @@ -142,6 +152,7 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S3) module_selectcategorizer=wx.BoxSizer(wx.HORIZONTAL) button_selectcategorizer=wx.Button(panel,label='Select a Categorizer for\nbehavior classification',size=(300,40)) @@ -1134,6 +1145,7 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S4) module_inputfolder=wx.BoxSizer(wx.HORIZONTAL) button_inputfolder=wx.Button(panel,label='Select the folder that contains\nthe LabGym analysis output folders',size=(300,40)) @@ -1309,6 +1321,7 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S4) module_inputfile=wx.BoxSizer(wx.HORIZONTAL) button_inputfile=wx.Button(panel,label='Select the\nall_events.xlsx file',size=(300,40)) @@ -1425,6 +1438,7 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S4) module_inputfolder=wx.BoxSizer(wx.HORIZONTAL) button_inputfolder=wx.Button(panel,label='Select the folder that stores\nLabGym analysis results',size=(300,40)) @@ -1545,3 +1559,659 @@ def calculate_distances(self,event): all_data=pd.concat(all_data,keys=names,names=['File name','ID/parameter']) all_data.drop(all_data.columns[0],axis=1,inplace=True) all_data.to_excel(os.path.join(self.out_path,'all_summary.xlsx'),float_format='%.2f') + + + + + def pick_color(self,event): + + width,height=self.color_panel.GetSize() + center_x=width//2 + center_y=height//2 + radius=min(width,height)//2-10 + + x,y=event.GetPosition() + dx=x-center_x + dy=y-center_y + dist=(dx*dx+dy*dy)**0.5 + + if dist>radius: + return + + hue=(np.arctan2(dy,dx)+np.pi)/(2*np.pi) + sat=dist/radius + val=1.0 + + r,g,b=self.hsv_to_rgb(hue,sat,val) + self.current_color='#{:02x}{:02x}{:02x}'.format(r,g,b) + + self.preview.SetBackgroundColour(self.current_color) + self.preview.Refresh() + + self.text_current.SetLabel( + 'Current behavior: '+str(self.current_behavior) + +' Color: '+str(self.current_color) + ) + + + def apply_one_color(self,event): + + if self.current_behavior is None: + return + + self.behavior_colors[self.current_behavior]=self.current_color + + wx.MessageBox( + 'Applied color for '+str(self.current_behavior)+': '+str(self.current_color), + 'Color applied', + wx.OK|wx.ICON_INFORMATION + ) + + + def hsv_to_rgb(self,h,s,v): + + i=int(h*6) + f=h*6-i + p=v*(1-s) + q=v*(1-f*s) + t=v*(1-(1-f)*s) + i=i%6 + + if i==0: + r,g,b=v,t,p + elif i==1: + r,g,b=q,v,p + elif i==2: + r,g,b=p,v,t + elif i==3: + r,g,b=p,q,v + elif i==4: + r,g,b=t,p,v + else: + r,g,b=v,p,q + + return int(r*255),int(g*255),int(b*255) + + + def get_behavior_colors(self): + + return self.behavior_colors + + +class BehaviorColorDialog(wx.Dialog): + + def __init__(self, parent, behavior_names, behavior_colors): + + super().__init__(parent=parent, title='Set behavior colors', size=(480,320)) + + self.behavior_names = behavior_names + self.behavior_colors = behavior_colors.copy() + + boxsizer = wx.BoxSizer(wx.VERTICAL) + + self.choice_behavior = wx.Choice(self, choices=self.behavior_names) + self.choice_behavior.SetSelection(0) + self.choice_behavior.Bind(wx.EVT_CHOICE, self.on_select_behavior) + + self.color_picker = wx.ColourPickerCtrl(self) + self.color_picker.Bind(wx.EVT_COLOURPICKER_CHANGED, self.on_pick_color) + + self.color_text = wx.TextCtrl(self, size=(160,28)) + self.color_text.Bind(wx.EVT_TEXT, self.on_type_color) + + self.preview = wx.Panel(self, size=(120,35)) + + buttons = wx.BoxSizer(wx.HORIZONTAL) + + button_apply = wx.Button(self, label='Apply color to this behavior') + button_apply.Bind(wx.EVT_BUTTON, self.apply_current_color) + + button_done = wx.Button(self, wx.ID_OK, label='Done') + button_done.Bind(wx.EVT_BUTTON, self.on_done) + button_cancel = wx.Button(self, wx.ID_CANCEL, label='Cancel') + + buttons.Add(button_apply, 0, wx.ALL, 5) + buttons.Add(button_done, 0, wx.ALL, 5) + buttons.Add(button_cancel, 0, wx.ALL, 5) + + boxsizer.Add(wx.StaticText(self, label='Select behavior:'), 0, wx.ALL, 8) + boxsizer.Add(self.choice_behavior, 0, wx.ALL|wx.EXPAND, 8) + + boxsizer.Add(wx.StaticText(self, label='Pick from color wheel or enter hex code:'), 0, wx.ALL, 8) + boxsizer.Add(self.color_picker, 0, wx.ALL|wx.CENTER, 8) + boxsizer.Add(self.color_text, 0, wx.ALL|wx.CENTER, 8) + boxsizer.Add(self.preview, 0, wx.ALL|wx.CENTER, 8) + boxsizer.Add(buttons, 0, wx.ALL|wx.CENTER, 8) + + self.SetSizer(boxsizer) + self.load_behavior_color() + + + def valid_hex(self, color): + + if not isinstance(color, str): + return False + + if len(color) != 7 or color[0] != '#': + return False + + try: + int(color[1:], 16) + return True + except ValueError: + return False + + + def hex_to_rgb(self, color): + + color = color.lstrip('#') + return tuple(int(color[i:i+2], 16) for i in (0,2,4)) + + + def rgb_to_hex(self, color): + + return '#%02x%02x%02x' % ( + color.Red(), + color.Green(), + color.Blue() + ) + + + def current_behavior(self): + + return self.choice_behavior.GetStringSelection() + + + def load_behavior_color(self): + + behavior = self.current_behavior() + color = self.behavior_colors.get(behavior, '#ffffff') + + if not self.valid_hex(color): + color = '#ffffff' + + rgb = self.hex_to_rgb(color) + + self.color_picker.SetColour(wx.Colour(*rgb)) + self.color_text.SetValue(color) + self.preview.SetBackgroundColour(wx.Colour(*rgb)) + self.preview.Refresh() + + + def on_select_behavior(self, event): + + # Preserve the color for the previously active behavior before switching. + self.commit_current_color(show_error=False) + self.load_behavior_color() + + + def on_pick_color(self, event): + + color = self.color_picker.GetColour() + hex_color = self.rgb_to_hex(color) + + self.color_text.SetValue(hex_color) + self.preview.SetBackgroundColour(color) + self.preview.Refresh() + # Live-commit so Done is not dependent on Apply. + behavior = self.current_behavior() + if behavior: + self.behavior_colors[behavior] = hex_color + + + def on_type_color(self, event): + + color = self.color_text.GetValue().strip() + + if self.valid_hex(color): + rgb = self.hex_to_rgb(color) + self.color_picker.SetColour(wx.Colour(*rgb)) + self.preview.SetBackgroundColour(wx.Colour(*rgb)) + self.preview.Refresh() + behavior = self.current_behavior() + if behavior: + self.behavior_colors[behavior] = color + + + def commit_current_color(self, show_error=True): + + behavior = self.current_behavior() + if not behavior: + return True + + color = self.color_text.GetValue().strip() + if not self.valid_hex(color): + if show_error: + wx.MessageBox( + 'Invalid color code. Please enter a hex color like #66ccff.', + 'Invalid color', + wx.OK|wx.ICON_ERROR + ) + return False + + self.behavior_colors[behavior] = color + return True + + + def apply_current_color(self, event): + + if self.commit_current_color(show_error=True): + wx.MessageBox( + 'Color applied to: ' + self.current_behavior(), + 'Applied', + wx.OK|wx.ICON_INFORMATION + ) + + + def on_done(self, event): + '''Done preserves the currently selected color without requiring Apply.''' + if not self.commit_current_color(show_error=True): + return + self.EndModal(wx.ID_OK) + + + def get_colors(self): + + return self.behavior_colors + + +def stm_gui_exclusion_status_label(exclusions): + '''Status text for the STM exclusion row.''' + if not exclusions: + return 'Default: none.' + return 'Excluded: ' + str(list(exclusions)) + '.' + + +def stm_gui_color_status_label(colors_are_custom): + '''Status text for the STM color row.''' + if colors_are_custom: + return 'Custom behavior colors set.' + return 'Default behavior colors.' + + +def stm_gui_apply_exclusion_dialog_result(previous_exclusions, selected_behaviors, accepted): + ''' + Compute exclusion list after the multi-choice dialog closes. + + Cancel/close (accepted=False) preserves previous_exclusions. + ''' + if not accepted: + return list(previous_exclusions) + return list(selected_behaviors) + + +class PanelLv2_StateTransitionMap(wx.Panel): + + ''' + The 'State Transition Map' functional unit (V1 product). + ''' + + def __init__(self, parent): + + super().__init__(parent) + self.notebook = parent + + self.path_to_events = None + self.result_path = None # user-selected parent folder + self.stm_dir = None + + self.behavior_names = [] + self.behavior_to_exclude = [] + self.behavior_colors = {} + self.colors_are_custom = False + + self.display_window() + + + def resolve_stm_dir(self): + '''Return /state_transition_map when an output folder is set.''' + if self.result_path is None: + return None + return os.path.join(self.result_path, 'state_transition_map') + + + def refresh_paths_status(self): + self.stm_dir = self.resolve_stm_dir() + if self.stm_dir is None: + self.text_output.SetLabel('None.') + return + self.text_output.SetLabel( + 'Results folder (regeneration updates existing files here):\n' + + self.stm_dir + ) + + + def refresh_exclude_status(self): + self.text_exclude.SetLabel( + stm_gui_exclusion_status_label(self.behavior_to_exclude) + ) + + + def refresh_color_status(self): + self.text_colors.SetLabel( + stm_gui_color_status_label(self.colors_are_custom) + ) + + + def ensure_session_colors(self): + '''Fill missing behaviors with defaults; keep session custom colors.''' + included = [b for b in self.behavior_names if b not in self.behavior_to_exclude] + if not included: + self.behavior_colors = {} + self.refresh_color_status() + return + self.behavior_colors = stm_session_colors( + included, + existing_colors=self.behavior_colors, + ) + self.refresh_color_status() + + + def reset_input_dependent_state(self): + '''Clear all input-derived STM state (used after parse failure).''' + self.path_to_events = None + self.behavior_names = [] + self.behavior_to_exclude = [] + self.behavior_colors = {} + self.colors_are_custom = False + self.text_input.SetLabel('No valid all_events.xlsx file selected.') + self.refresh_exclude_status() + self.refresh_color_status() + # Output parent may still be set; destination does not depend on input stem. + self.refresh_paths_status() + + + def apply_successful_input_load(self, path, behavior_names): + '''Apply a successfully parsed all_events.xlsx selection.''' + self.path_to_events = path + self.behavior_names = list(behavior_names) + self.behavior_to_exclude = [] + self.behavior_colors = {} + self.colors_are_custom = False + self.text_input.SetLabel('Selected: ' + str(path) + '.') + self.refresh_exclude_status() + self.ensure_session_colors() + self.refresh_paths_status() + + + def apply_exclusion_dialog_result(self, selected_behaviors, accepted): + '''Update exclusions after multi-choice OK/Cancel (Cancel preserves).''' + self.behavior_to_exclude = stm_gui_apply_exclusion_dialog_result( + self.behavior_to_exclude, + selected_behaviors, + accepted, + ) + if accepted: + self.refresh_exclude_status() + self.ensure_session_colors() + + + def apply_color_dialog_result(self, new_colors, accepted): + '''Update session colors after color dialog OK/Cancel (Cancel preserves).''' + if not accepted: + return + self.behavior_colors = dict(new_colors) + self.colors_are_custom = True + self.refresh_color_status() + + + def generate_is_blocked(self): + '''True when Generate cannot run (no valid input and/or no output parent).''' + return self.path_to_events is None or self.result_path is None + + + def display_window(self): + + panel = self + boxsizer = wx.BoxSizer(wx.VERTICAL) + + module_input = wx.BoxSizer(wx.HORIZONTAL) + # Multi-line labels (with \\n) keep the large rectangular LabGym button + # look on macOS; single-line labels render as small native rounded buttons. + button_input = wx.Button( + panel, + label='Select an all_events.xlsx\nfile', + size=(300,40), + ) + button_input.Bind(wx.EVT_BUTTON, self.select_events_file) + self.text_input = wx.StaticText(panel, label='None.', style=wx.ALIGN_LEFT|wx.ST_ELLIPSIZE_END) + module_input.Add(button_input, 0, wx.LEFT|wx.RIGHT|wx.EXPAND, 10) + module_input.Add(self.text_input, 0, wx.LEFT|wx.RIGHT|wx.EXPAND, 10) + + boxsizer.Add(0,10,0) + boxsizer.Add(module_input, 0, wx.LEFT|wx.RIGHT|wx.EXPAND, 10) + boxsizer.Add(0,5,0) + + module_output = wx.BoxSizer(wx.HORIZONTAL) + button_output = wx.Button( + panel, + label='Select a folder to store\nthe state map results', + size=(300,40), + ) + button_output.Bind(wx.EVT_BUTTON, self.select_outpath) + self.text_output = wx.StaticText(panel, label='None.', style=wx.ALIGN_LEFT|wx.ST_ELLIPSIZE_END) + module_output.Add(button_output, 0, wx.LEFT|wx.RIGHT|wx.EXPAND, 10) + module_output.Add(self.text_output, 0, wx.LEFT|wx.RIGHT|wx.EXPAND, 10) + + boxsizer.Add(module_output, 0, wx.LEFT|wx.RIGHT|wx.EXPAND, 10) + boxsizer.Add(0,5,0) + + module_exclude = wx.BoxSizer(wx.HORIZONTAL) + button_exclude = wx.Button( + panel, + label='Select behaviors to\nexclude', + size=(300,40), + ) + button_exclude.Bind(wx.EVT_BUTTON, self.select_exclusions) + self.text_exclude = wx.StaticText(panel, label='Default: none.', style=wx.ALIGN_LEFT|wx.ST_ELLIPSIZE_END) + module_exclude.Add(button_exclude, 0, wx.LEFT|wx.RIGHT|wx.EXPAND, 10) + module_exclude.Add(self.text_exclude, 0, wx.LEFT|wx.RIGHT|wx.EXPAND, 10) + + boxsizer.Add(module_exclude, 0, wx.LEFT|wx.RIGHT|wx.EXPAND, 10) + boxsizer.Add(0,5,0) + + module_colors = wx.BoxSizer(wx.HORIZONTAL) + button_colors = wx.Button( + panel, + label='Set behavior\ncolors', + size=(300,40), + ) + button_colors.Bind(wx.EVT_BUTTON, self.set_behavior_colors) + self.text_colors = wx.StaticText( + panel, + label='Default behavior colors.', + style=wx.ALIGN_LEFT|wx.ST_ELLIPSIZE_END, + ) + module_colors.Add(button_colors, 0, wx.LEFT|wx.RIGHT|wx.EXPAND, 10) + module_colors.Add(self.text_colors, 0, wx.LEFT|wx.RIGHT|wx.EXPAND, 10) + + boxsizer.Add(module_colors, 0, wx.LEFT|wx.RIGHT|wx.EXPAND, 10) + boxsizer.Add(0,5,0) + + # Single-line native rounded button (not the multi-line rectangular action style). + button_generate = wx.Button( + panel, + label='Generate state transition maps', + size=(300,40), + ) + button_generate.Bind(wx.EVT_BUTTON, self.generate_map) + + boxsizer.Add(0,5,0) + boxsizer.Add(button_generate, 0, wx.RIGHT|wx.ALIGN_RIGHT, 90) + boxsizer.Add(0,10,0) + + panel.SetSizer(boxsizer) + self.Centre() + self.Show(True) + + + def select_events_file(self,event): + + wildcard = 'Excel files (*.xlsx;*.xls)|*.xlsx;*.xls' + dialog = wx.FileDialog( + self, + 'Select an all_events.xlsx file', + '', + '', + wildcard, + style=wx.FD_OPEN|wx.FD_FILE_MUST_EXIST + ) + + if dialog.ShowModal() == wx.ID_OK: + + path = dialog.GetPath() + try: + _,_,behavior_names = parse_all_events_file(path) + self.apply_successful_input_load(path, behavior_names) + + except Exception as exc: + wx.MessageBox( + 'Failed to parse the selected file:\n'+str(exc), + 'Error', + wx.OK|wx.ICON_ERROR + ) + self.reset_input_dependent_state() + + dialog.Destroy() + + + def select_outpath(self,event): + + dialog = wx.DirDialog(self,'Select a directory','',style=wx.DD_DEFAULT_STYLE) + + if dialog.ShowModal() == wx.ID_OK: + self.result_path = dialog.GetPath() + self.refresh_paths_status() + + dialog.Destroy() + + + def select_exclusions(self,event): + + if self.path_to_events is None or len(self.behavior_names) == 0: + wx.MessageBox( + 'Please select an all_events.xlsx file first.', + 'Error', + wx.OK|wx.ICON_ERROR + ) + return + + dialog = wx.MultiChoiceDialog( + self, + message=( + 'Select behaviors to exclude from the state transition map.\n' + 'Excluded behaviors are not shown as nodes and break the bout sequence\n' + '(surrounding behaviors are not bridged into a new transition).' + ), + caption='Behaviors to exclude', + choices=self.behavior_names + ) + + accepted = dialog.ShowModal() == wx.ID_OK + selected = [] + if accepted: + selected = [self.behavior_names[i] for i in dialog.GetSelections()] + self.apply_exclusion_dialog_result(selected, accepted) + + dialog.Destroy() + + + def set_behavior_colors(self, event): + + if self.path_to_events is None: + wx.MessageBox( + 'Please select an all_events.xlsx file first.', + 'Error', + wx.OK|wx.ICON_ERROR + ) + return + + behavior_names = [ + b for b in self.behavior_names + if b not in self.behavior_to_exclude + ] + + if len(behavior_names) == 0: + wx.MessageBox( + 'No behaviors available for color setting.', + 'Error', + wx.OK|wx.ICON_ERROR + ) + return + + self.ensure_session_colors() + dialog = BehaviorColorDialog( + self, + behavior_names, + self.behavior_colors + ) + + accepted = dialog.ShowModal() == wx.ID_OK + new_colors = dialog.get_colors() if accepted else None + if accepted: + self.apply_color_dialog_result(new_colors, True) + + dialog.Destroy() + + + def generate_map(self,event): + + if self.generate_is_blocked(): + wx.MessageBox( + 'Please select an input file and an output folder.', + 'Error', + wx.OK|wx.ICON_ERROR + ) + return + + try: + event_probability,_,behavior_names = parse_all_events_file(self.path_to_events) + + behavior_names = [b for b in behavior_names if b not in self.behavior_to_exclude] + + if len(behavior_names) == 0: + wx.MessageBox( + 'No behaviors remain after exclusion.', + 'Error', + wx.OK|wx.ICON_ERROR + ) + return + + stm_dir = self.resolve_stm_dir() + os.makedirs(stm_dir, exist_ok=True) + self.stm_dir = stm_dir + self.refresh_paths_status() + + self.behavior_colors = stm_session_colors( + behavior_names, + existing_colors=self.behavior_colors, + ) + + result = plot_state_transition_map( + stm_dir, + event_probability, + behavior_to_include=behavior_names, + behavior_colors=self.behavior_colors, + input_path=self.path_to_events, + excluded_behaviors=self.behavior_to_exclude, + draw_maps=True, + ) + + if result.get('behavior_colors'): + self.behavior_colors = result['behavior_colors'] + + status = result.get('status', 'error') + message = result.get('message', 'State transition map finished.') + if status == 'success': + wx.MessageBox(message, 'Done', wx.OK|wx.ICON_INFORMATION) + elif status in ('warning_partial', 'warning_no_maps'): + wx.MessageBox(message, 'Warning', wx.OK|wx.ICON_WARNING) + else: + wx.MessageBox(message, 'Error', wx.OK|wx.ICON_ERROR) + + except Exception as e: + wx.MessageBox( + 'Failed to generate state-transition map:\n'+str(e), + 'Error', + wx.OK|wx.ICON_ERROR + ) diff --git a/LabGym/gui_app_icon.py b/LabGym/gui_app_icon.py index 284b2283..eedc9dd6 100644 --- a/LabGym/gui_app_icon.py +++ b/LabGym/gui_app_icon.py @@ -17,11 +17,11 @@ ''' '''GUI application icon module for LabGym. -This module provides cross-platform icon handling functionality for the LabGym -GUI, including support for different icon formats (ICO, ICNS, PNG) and -contexts (normal, small). +This module provides cross-platform icon handling for the LabGym GUI using one +simplified LabGym artwork set (ICO on Windows, PNG elsewhere, ICNS on macOS Dock). ''' # Standard library imports. +import logging import sys from pathlib import Path from importlib.resources import files @@ -36,6 +36,9 @@ from AppKit import NSApplication, NSImage except ImportError: NSApplication = None + NSImage = None + +logger = logging.getLogger(__name__) @lru_cache(maxsize=1) @@ -43,77 +46,98 @@ def _get_icon_paths(): """Get all icon paths once and cache them.""" base_path = files("LabGym") / "assets/icons" return { - 'small_ico': base_path / "labgym_small.ico", - 'main_ico': base_path / "labgym.ico", + 'ico': base_path / "labgym.ico", 'icns': base_path / "labgym.icns", - 'png': base_path / "labgym.png" + 'png': base_path / "labgym.png", } -def get_icon_for_context(context='normal', size=16): - """Get appropriate icon path for given context and size.""" +def get_frame_icon_path(): + """Return the platform-appropriate path for wx frame icons. + + Windows uses the multi-resolution labgym.ico. macOS and other platforms + use the matching labgym.png. + """ icon_paths = _get_icon_paths() if sys.platform.startswith("win"): - # Windows: Use ICO files for better compatibility - if context == 'small' or size <= 24: - return str(icon_paths['small_ico']) if icon_paths['small_ico'].is_file() else str(icon_paths['png']) - else: - return str(icon_paths['main_ico']) if icon_paths['main_ico'].is_file() else str(icon_paths['png']) + if icon_paths['ico'].is_file(): + return str(icon_paths['ico']) + if icon_paths['png'].is_file(): + return str(icon_paths['png']) + return "" - # macOS or fallback - return str(icon_paths['png']) if icon_paths['png'].is_file() else "" + # macOS and non-Windows fallback + if icon_paths['png'].is_file(): + return str(icon_paths['png']) + return "" -def set_frame_icon(frame, context='normal', size=16): - """Set frame icon with proper error handling.""" +def set_frame_icon(frame): + """Set the frame icon from the unified simplified artwork.""" try: - icon_path = get_icon_for_context(context, size) + icon_path = get_frame_icon_path() if not icon_path or not Path(icon_path).is_file(): + logger.warning('Frame icon asset not found') return icon = wx.Icon(icon_path, wx.BITMAP_TYPE_ANY) if icon.IsOk(): frame.SetIcon(icon) + else: + logger.warning('Failed to load frame icon from %s', icon_path) except Exception: - pass + logger.exception('Error setting frame icon') + +def set_windows_app_user_model_id(): + """Establish Windows process/taskbar identity via AppUserModelID. -def set_windows_taskbar_icon(): - """Set the Windows taskbar icon. - Set the Windows taskbar icon using small ICO for better small-size - visibility. + Call this early (before the first visible window) when practical. + This does not embed an executable icon; it only sets runtime process + identity used by the shell for taskbar grouping. """ if not sys.platform.startswith("win"): return try: - # This sets AppUserModelID first - this is crucial for proper taskbar icon association app_id = "umyelab.LabGym" ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(app_id) except Exception: - pass + logger.exception('Failed to set Windows AppUserModelID') + + +# Backward-compatible name used by older call sites. +set_windows_taskbar_icon = set_windows_app_user_model_id def set_macos_dock_icon(): - """Set the Dock icon on macOS. - Set the Dock icon at runtime on macOS (requires optional PyObjC). - """ + """Set the Dock icon on macOS for unbundled runs (optional PyObjC).""" if sys.platform != "darwin" or not NSApplication: return try: - baseIconDir = files("LabGym") - icns = baseIconDir / "assets/icons/labgym.icns" - png = baseIconDir / "assets/icons/labgym.png" + icon_paths = _get_icon_paths() + if icon_paths['icns'].is_file(): + icon_path = str(icon_paths['icns']) + elif icon_paths['png'].is_file(): + icon_path = str(icon_paths['png']) + else: + logger.warning('macOS Dock icon asset not found') + return - icon_path = str(icns if icns.is_file() else png) img = NSImage.alloc().initWithContentsOfFile_(icon_path) if img: NSApplication.sharedApplication().setApplicationIconImage_(img) + else: + logger.warning('Failed to load macOS Dock icon from %s', icon_path) except Exception: - pass + logger.exception('Error setting macOS Dock icon') def setup_application_icons(): - """Set up all application icons for the current platform.""" + """Set up process/Dock icons for the current platform. + + Safe to call more than once. Prefer an early call before the first + visible window so Windows AppUserModelID is established first. + """ + set_windows_app_user_model_id() set_macos_dock_icon() - set_windows_taskbar_icon() diff --git a/LabGym/gui_appearance.py b/LabGym/gui_appearance.py new file mode 100644 index 00000000..d6e64729 --- /dev/null +++ b/LabGym/gui_appearance.py @@ -0,0 +1,98 @@ +''' +Copyright (C) +This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. +This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. +You should have received a copy of the GNU General Public License along with this program. If not, see https://tldrlegal.com/license/gnu-general-public-license-v3-(gpl-3)#fulltext. + +For license issues, please contact: + +Dr. Bing Ye +Life Sciences Institute +University of Michigan +210 Washtenaw Avenue, Room 5403 +Ann Arbor, MI 48109-2216 +USA + +Email: bingye@umich.edu +''' + + +'''Native appearance helpers for LabGym. + +Reports whether the OS / wxPython effective appearance is dark so callers can +pick appearance-dependent values (e.g. colours). Does not implement a custom +theme, Light/Dark/System override, preference persistence, or widget recoloring. +''' + +import wx + + +def _colour_luminance(colour) -> float: + """Return approximate relative luminance of a wx colour (0–255 scale).""" + try: + r, g, b = colour.Red(), colour.Green(), colour.Blue() + except Exception: + try: + r, g, b = colour.Get()[:3] + except Exception: + return 128.0 + # ITU-R BT.601 luma coefficients, full 8-bit channel range. + return 0.299 * r + 0.587 * g + 0.114 * b + + +def _is_dark_from_system_colours() -> bool: + """Infer dark appearance by comparing system window background vs text.""" + bg = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW) + fg = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT) + return _colour_luminance(bg) < _colour_luminance(fg) + + +def is_dark_appearance() -> bool: + """Return True when the effective native wx appearance is dark. + + Detection order: + 1. ``wx.SystemSettings.GetAppearance().IsDark()`` when available. + 2. ``GetAppearance().IsUsingDarkBackground()`` when ``IsDark`` is missing + or raises (older / partial APIs). + 3. System window vs window-text luminance when the appearance API is + unavailable or fails. + 4. Light (``False``) as a final safe default. + """ + get_appearance = getattr(wx.SystemSettings, 'GetAppearance', None) + if callable(get_appearance): + try: + appearance = get_appearance() + except Exception: + appearance = None + + if appearance is not None: + is_dark = getattr(appearance, 'IsDark', None) + if callable(is_dark): + try: + return bool(is_dark()) + except Exception: + pass + + # Fallback / older builds: IsUsingDarkBackground without IsDark. + is_using_dark_bg = getattr(appearance, 'IsUsingDarkBackground', None) + if callable(is_using_dark_bg): + try: + return bool(is_using_dark_bg()) + except Exception: + pass + + try: + return bool(_is_dark_from_system_colours()) + except Exception: + return False + + +def select_for_appearance(light_value, dark_value): + """Return ``dark_value`` under dark native appearance, else ``light_value``. + + Values may be ``wx.Colour`` instances or any other small appearance-dependent + objects; this helper does not inspect or convert them. + """ + if is_dark_appearance(): + return dark_value + return light_value diff --git a/LabGym/gui_categorizer.py b/LabGym/gui_categorizer.py index 8fb85e4e..12d91d2f 100644 --- a/LabGym/gui_categorizer.py +++ b/LabGym/gui_categorizer.py @@ -21,6 +21,10 @@ import json import logging import os +import re +import sys +import subprocess + # from pathlib import Path import shutil @@ -34,18 +38,286 @@ import cv2 import numpy as np import wx +import wx.richtext +import wx.lib.buttons as wxbuttons +import wx.grid +import wx.html # Local application/library specific imports. -logger.debug('importing %s ...', '.analyzebehavior') -from .analyzebehavior import AnalyzeAnimal -logger.debug('importing %s done', '.analyzebehavior') -logger.debug('importing %s ...', '.analyzebehavior_dt') -from .analyzebehavior_dt import AnalyzeAnimalDetector -logger.debug('importing %s done', '.analyzebehavior_dt') -from .categorizer import Categorizers +from .categorizer import Categorizers, CategorizerClassMismatchError from LabGym import config from .tools import sort_examples_from_csv -from .gui_utils import add_or_select_notebook_page +from .gui_utils import ( + add_or_select_notebook_page, + add_info_button, + create_hyperlink, + INFO_COLOUR_S3, + count_prepared_examples, + count_sorted_examples, + counts_enable_diagnostics, +) + + +# Confusion-matrix correct-cell colors: dark -> approved max green #2E7D32. +CM_CORRECT_RGB_MIN = (20, 40, 20) +CM_CORRECT_RGB_MAX = (46, 125, 50) # #2E7D32 + + +def import_generate_examples_analyzer(kind): + """ + Import AnalyzeAnimal ('animal') or AnalyzeAnimalDetector ('detector'). + + Returns the class, or None after logging and a MessageBox when the import + raises ImportError or OSError (for example a missing native library). + Unknown kind values raise ValueError without attempting an import. + """ + if kind not in ('animal', 'detector'): + raise ValueError( + "import_generate_examples_analyzer kind must be 'animal' or 'detector', " + f'got {kind!r}' + ) + try: + if kind == 'animal': + from .analyzebehavior import AnalyzeAnimal + return AnalyzeAnimal + if kind == 'detector': + from .analyzebehavior_dt import AnalyzeAnimalDetector + return AnalyzeAnimalDetector + except (ImportError, OSError): + logger.exception( + 'Failed to import Generate Examples analyzer components (kind=%r)', + kind, + ) + wx.MessageBox( + 'LabGym could not load the analysis components required for this Generate ' + 'Examples workflow. Verify that the LabGym environment and its required ' + 'dependencies are installed correctly, then try again.', + 'Analysis dependency unavailable', + wx.OK | wx.ICON_ERROR, + ) + return None + + +def cm_correct_cell_rgb(accuracy): + """Return RGB for a correct (diagonal) CM cell given row accuracy in [0, 1].""" + accuracy = max(0.0, min(1.0, float(accuracy))) + r0, g0, b0 = CM_CORRECT_RGB_MIN + r1, g1, b1 = CM_CORRECT_RGB_MAX + return ( + int(round(r0 + (r1 - r0) * accuracy)), + int(round(g0 + (g1 - g0) * accuracy)), + int(round(b0 + (b1 - b0) * accuracy)), + ) + + +def triage_assignment_counts(h1_count, h2_count, h3_count): + """Return True when at least one triage hypothesis has an assignment.""" + return (h1_count + h2_count + h3_count) > 0 + + +def reportlab_importable(): + """Return (ok, error_message_or_None) for PDF dependency availability.""" + try: + import reportlab # noqa: F401 + from reportlab.lib.pagesizes import letter # noqa: F401 + from reportlab.platypus import SimpleDocTemplate # noqa: F401 + return True, None + except ImportError as e: + return False, str(e) + + +DIAGNOSTIC_BUTTON_LABELS = ( + 'Overview', + 'Major Confusions', + 'Minor Confusions', + 'Successes', + 'Build Triage Plan', +) + + +def insufficient_support_threshold(total_support): + """Minimum observed support required for automated major/minor ranking.""" + return max(20, float(total_support) * 0.01) + + +def collect_insufficient_support_entries(classnames, report): + """Return low-support class entries, including classes with zero support.""" + total_support = sum( + float(report.get(name, {}).get('support', 0)) for name in classnames + ) + min_support = int(insufficient_support_threshold(total_support)) + entries = [] + for true_class in classnames: + support = float(report.get(true_class, {}).get('support', 0)) + if support < min_support: + entries.append({ + 'class': true_class, + 'support': int(support), + 'min_support': min_support, + }) + return entries + + +def fit_dialog_client_size( + nominal_w, + nominal_h, + work_w, + work_h, + margin=40, + max_frac=0.92, +): + """Clamp a nominal dialog client size to a usable work area.""" + work_w = max(1, int(work_w)) + work_h = max(1, int(work_h)) + margin = max(0, int(margin)) + max_frac = max(0.1, min(1.0, float(max_frac))) + cap_w = min(work_w - 2 * margin, int(work_w * max_frac)) + cap_h = min(work_h - 2 * margin, int(work_h * max_frac)) + cap_w = max(1, cap_w) + cap_h = max(1, cap_h) + return min(int(nominal_w), cap_w), min(int(nominal_h), cap_h) + + +def next_versioned_pdf_path(directory, base='categorizer_diagnostics'): + """Return the next non-overwriting `{base}_vN.pdf` path in directory.""" + pattern = re.compile(r'^' + re.escape(base) + r'_v(\d+)\.pdf$') + max_n = 0 + try: + names = os.listdir(directory) + except OSError: + names = [] + for name in names: + path = os.path.join(directory, name) + if not os.path.isfile(path): + continue + matched = pattern.match(name) + if matched: + max_n = max(max_n, int(matched.group(1))) + return os.path.join(directory, f'{base}_v{max_n + 1}.pdf') + + +_WIN_INVALID_CHARS = set('<>:"|?*') +_WIN_RESERVED = { + 'CON', 'PRN', 'AUX', 'NUL', + *(f'COM{i}' for i in range(1, 10)), + *(f'LPT{i}' for i in range(1, 10)), +} +_TRAILING_TRIAGE_VERSION = re.compile(r'_triage_v\d+$', re.IGNORECASE) + + +def sanitize_triage_package_base(source_name): + """Return a portable basename stem for `_triage_vN` packages.""" + import unicodedata + + text = unicodedata.normalize('NFC', str(source_name or '')) + chars = [] + for ch in text: + category = unicodedata.category(ch) + if category.startswith('C'): + continue + if ch.isalnum() or ch in '-_': + chars.append(ch) + elif ch.isspace() or ch in '/\\' or ch in _WIN_INVALID_CHARS: + chars.append('_') + else: + chars.append('_') + base = ''.join(chars) + while '__' in base: + base = base.replace('__', '_') + base = base.strip(' ._') + base = _TRAILING_TRIAGE_VERSION.sub('', base) + base = base.strip(' ._') + if len(base) > 80: + base = base[:80].rstrip(' ._') + if not base: + base = 'sorted_test_examples' + if base.upper() in _WIN_RESERVED: + base = f'{base}_data' + return base + + +def next_versioned_triage_package_name(parent_dir, source_name): + """Return next `_triage_vN` sibling directory basename.""" + base = sanitize_triage_package_base(source_name) + pattern = re.compile(r'^' + re.escape(base) + r'_triage_v(\d+)$') + max_n = 0 + try: + names = os.listdir(parent_dir) + except OSError: + names = [] + for name in names: + path = os.path.join(parent_dir, name) + if not os.path.isdir(path): + continue + matched = pattern.match(name) + if matched: + max_n = max(max_n, int(matched.group(1))) + return f'{base}_triage_v{max_n + 1}' + + +def validate_triage_package_name(name): + """Return (ok, error_message_or_None) for a user-edited package basename.""" + if name is None: + return False, 'Package name cannot be empty.' + raw = str(name) + if raw.strip() == '': + return False, 'Package name cannot be empty.' + if raw != raw.strip(): + return False, 'Package name cannot start or end with spaces.' + if raw in ('.', '..'): + return False, 'Package name cannot be "." or "..".' + if os.path.isabs(raw) or raw.startswith('~'): + return False, 'Package name must be a folder name, not an absolute path.' + if '/' in raw or '\\' in raw: + return False, 'Package name cannot contain path separators.' + if any(ord(ch) < 32 for ch in raw): + return False, 'Package name cannot contain control characters.' + if any(ch in _WIN_INVALID_CHARS for ch in raw): + return False, 'Package name contains characters that are invalid on Windows.' + if raw.endswith('.') or raw.endswith(' '): + return False, 'Package name cannot end with a period or space.' + stem = raw.split('.')[0].upper() + if stem in _WIN_RESERVED: + return False, f'"{raw}" is a reserved device name on Windows.' + return True, None + + +def collect_h1_filename_collisions(source_root, h1_pairs): + """ + Return sorted collision records for H1 merges against source_root. + + Each record: {'pair': (true, pred), 'filenames': [sorted basenames]} + Also return missing class folders as sorted (kind, class_name) tuples where + kind is 'source' or 'target'. + """ + collisions = [] + missing = [] + seen_pairs = [] + for true_class, pred_class in h1_pairs: + pair = (true_class, pred_class) + if pair in seen_pairs: + continue + seen_pairs.append(pair) + src_dir = os.path.join(source_root, true_class) + tgt_dir = os.path.join(source_root, pred_class) + if not os.path.isdir(src_dir): + missing.append(('source', true_class)) + continue + if not os.path.isdir(tgt_dir): + missing.append(('target', pred_class)) + continue + try: + src_names = set(os.listdir(src_dir)) + tgt_names = set(os.listdir(tgt_dir)) + except OSError: + missing.append(('source', true_class)) + continue + overlap = sorted(src_names & tgt_names) + if overlap: + collisions.append({'pair': pair, 'filenames': overlap}) + collisions.sort(key=lambda rec: (rec['pair'][0], rec['pair'][1])) + missing = sorted(set(missing)) + return collisions, missing class PanelLv2_GenerateExamples(wx.Panel): @@ -100,6 +372,7 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S3) module_specifymode=wx.BoxSizer(wx.HORIZONTAL) button_specifymode=wx.Button(panel,label='Specify the mode of behavior\nexamples to generate',size=(300,40)) @@ -603,6 +876,9 @@ def generate_data(self,event): if self.path_to_detector is None: wx.MessageBox('You need to select a Detector.','Error',wx.OK|wx.ICON_ERROR) else: + AnalyzeAnimalDetector=import_generate_examples_analyzer('detector') + if AnalyzeAnimalDetector is None: + return AAD=AnalyzeAnimalDetector() AAD.analyze_images_individuals(self.path_to_detector,self.path_to_videos,self.result_path,self.animal_kinds,generate=True,imagewidth=self.framewidth,detection_threshold=self.detection_threshold,background_free=self.background_free,black_background=self.black_background) @@ -630,6 +906,15 @@ def generate_data(self,event): if do_nothing is False: + if self.use_detector is False: + AnalyzeAnimal=import_generate_examples_analyzer('animal') + if AnalyzeAnimal is None: + return + else: + AnalyzeAnimalDetector=import_generate_examples_analyzer('detector') + if AnalyzeAnimalDetector is None: + return + for i in self.path_to_videos: filename=os.path.splitext(os.path.basename(i))[0].split('_') @@ -701,6 +986,7 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S3) boxsizer.Add(0,40,0) button_sortexamples=wx.Button(panel,label='Sort Examples (LabGym UI)',size=(300,40)) @@ -715,6 +1001,16 @@ def display_window(self): boxsizer.Add(button_sortexamplescsv,0,wx.ALIGN_CENTER,10) boxsizer.Add(0,30,0) + # Align with the centered 300px button column (same wx.ALIGN_CENTER as buttons above). + boxsizer.Add( + create_hyperlink( + panel, + 'Sorting Behavior Examples using LabGym', + 'https://youtu.be/WDCJ2HdrYJo?si=O6orNTNZiwR1girH', + ), + 0, wx.ALIGN_CENTER, 10) + boxsizer.Add(0, 10, 0) + panel.SetSizer(boxsizer) self.Centre() @@ -756,6 +1052,7 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S3) module_inputfolder=wx.BoxSizer(wx.HORIZONTAL) button_inputfolder=wx.Button(panel,label='Select the folder that stores\nunsorted behavior examples',size=(300,40)) @@ -1001,6 +1298,7 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S3) module_inputexamples=wx.BoxSizer(wx.HORIZONTAL) button_inputexamples=wx.Button(panel,label='Select the folder that stores\nthe unsorted behavior examples',size=(300,40)) @@ -1065,10 +1363,6 @@ def sort_fromcsv(self,event): class PanelLv2_TrainCategorizers(wx.Panel): - ''' - The 'Train Categorizers' functional unit - ''' - def __init__(self, parent): super().__init__(parent) @@ -1112,14 +1406,23 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S3) module_inputexamples=wx.BoxSizer(wx.HORIZONTAL) button_inputexamples=wx.Button(panel,label='Select the folder that stores\nthe sorted behavior examples',size=(300,40)) button_inputexamples.Bind(wx.EVT_BUTTON,self.select_filepath) wx.Button.SetToolTip(button_inputexamples,'This folder should contain all the sorted behavior examples. Each subfolder in this folder should contain behavior examples of a behavior type. The names of the subfolders will be read by LabGym as the behavior names.') + # Right-hand content: path label + compact count button (always present; Enable/Disable only) + inputexamples_right=wx.BoxSizer(wx.VERTICAL) self.text_inputexamples=wx.StaticText(panel,label='None.',style=wx.ALIGN_LEFT|wx.ST_ELLIPSIZE_END) + self.button_view_sorted_counts=wx.Button(panel,label='View Behavior Counts',size=(200,28)) + self.button_view_sorted_counts.Bind(wx.EVT_BUTTON,self.show_sorted_count_popup) + self.button_view_sorted_counts.Disable() + wx.Button.SetToolTip(self.button_view_sorted_counts,'View example counts for each sorted behavior category.') + inputexamples_right.Add(self.text_inputexamples,0,wx.EXPAND) + inputexamples_right.Add(self.button_view_sorted_counts,0,wx.TOP,4) module_inputexamples.Add(button_inputexamples,0,wx.LEFT|wx.RIGHT|wx.EXPAND,10) - module_inputexamples.Add(self.text_inputexamples,0,wx.LEFT|wx.RIGHT|wx.EXPAND,10) + module_inputexamples.Add(inputexamples_right,1,wx.EXPAND|wx.LEFT|wx.RIGHT,10) boxsizer.Add(0,10,0) boxsizer.Add(module_inputexamples,0,wx.LEFT|wx.RIGHT|wx.EXPAND,10) boxsizer.Add(0,5,0) @@ -1175,9 +1478,17 @@ def display_window(self): button_trainingfolder=wx.Button(panel,label='Select the folder that stores\nall the prepared training examples',size=(300,40)) button_trainingfolder.Bind(wx.EVT_BUTTON,self.select_datapath) wx.Button.SetToolTip(button_trainingfolder,'The folder that stores all the prepared behavior examples. If these are previously augmented, this folder should contain a "train" and a "vadilation" subfolder. If body parts are included, the STD value can be found in the filenames of the generated behavior examples with "_stdXX_" where "XX" is the STD value.') + # Right-hand content: path label + compact count button (always present; Enable/Disable only) + trainingfolder_right=wx.BoxSizer(wx.VERTICAL) self.text_trainingfolder=wx.StaticText(panel,label='None',style=wx.ALIGN_LEFT|wx.ST_ELLIPSIZE_END) + self.button_view_counts=wx.Button(panel,label='View Behavior Counts',size=(200,28)) + self.button_view_counts.Bind(wx.EVT_BUTTON,self.show_count_popup) + self.button_view_counts.Disable() + wx.Button.SetToolTip(self.button_view_counts,'View example counts for each prepared training category.') + trainingfolder_right.Add(self.text_trainingfolder,0,wx.EXPAND) + trainingfolder_right.Add(self.button_view_counts,0,wx.TOP,4) module_trainingfolder.Add(button_trainingfolder,0,wx.LEFT|wx.RIGHT|wx.EXPAND,10) - module_trainingfolder.Add(self.text_trainingfolder,0,wx.LEFT|wx.RIGHT|wx.EXPAND,10) + module_trainingfolder.Add(trainingfolder_right,1,wx.EXPAND|wx.LEFT|wx.RIGHT,10) boxsizer.Add(module_trainingfolder,0,wx.LEFT|wx.RIGHT|wx.EXPAND,10) boxsizer.Add(0,5,0) @@ -1213,12 +1524,342 @@ def display_window(self): self.Show(True) + def _count_examples(self,folder_path): + return count_prepared_examples(folder_path) + + + def _update_count_display(self,folder_path): + counts=self._count_examples(folder_path) + if not counts_enable_diagnostics(counts): + self._counts={} + self.button_view_counts.Disable() + return + self._counts=counts + self.button_view_counts.Enable() + + + def _iter_count_rows(self,counts): + '''Yield behavior-name rows matching the 3-items-per-row body layout.''' + names=sorted(counts) + i=0 + while i200: + chunk=names[i:i+2] + yield chunk + i+=len(chunk) + + + def _count_display_lines(self,counts,threshold): + '''Return (count_rows, add_rows) for the body layout at the given threshold.''' + count_rows=0 + add_rows=0 + for row in self._iter_count_rows(counts): + count_rows+=1 + if any(counts[name] SD + values=list(counts.values()) + mean=sum(values)/len(values) + std=(sum((v-mean)**2 for v in values)/len(values))**0.5 + rtc.Clear() + for row in self._iter_count_rows(counts): + for i_item,name in enumerate(row): + count=counts[name] + attr=wx.richtext.RichTextAttr() + attr.SetTextColour(wx.Colour(180,0,0) if count0 and abs(count-mean)>std: + attr.SetBackgroundColour(wx.YELLOW) + rtc.BeginStyle(attr) + rtc.WriteText(f'{name}: {count} examples') + rtc.EndStyle() + if i_item=1 else None + + def _filter_threshold_char(evt): + key=evt.GetKeyCode() + if key in ( + wx.WXK_BACK,wx.WXK_DELETE,wx.WXK_TAB,wx.WXK_LEFT,wx.WXK_RIGHT, + wx.WXK_HOME,wx.WXK_END,wx.WXK_RETURN,wx.WXK_NUMPAD_ENTER, + wx.WXK_NUMPAD_DELETE): + evt.Skip() + return + if wx.WXK_NUMPAD0<=key<=wx.WXK_NUMPAD9: + evt.Skip() + return + if 32<=key<256 and chr(key).isdigit(): + evt.Skip() + return + # ignore non-digit characters + + def on_apply(evt): + t=_parse_threshold() + if t is None: + thr_txt.SetValue(str(popup._applied_threshold)) + return + popup._applied_threshold=t + set_threshold(t) + red_explain.SetLabel(f' Example count is below {t} (minimum threshold)') + self._render_body(rtc_counts,counts,t) + new_h,_=self._counts_area_height(counts,t,max_counts_h) + rtc_counts.SetMinSize((popup_w-2*margin,new_h)) + rtc_counts.SetSize((popup_w-2*margin,new_h)) + outer.Layout() + popup.SetClientSize(popup_w,outer.GetMinSize().height+2) + + thr_txt.Bind(wx.EVT_CHAR,_filter_threshold_char) + thr_txt.Bind(wx.EVT_TEXT_ENTER,on_apply) + btn.Bind(wx.EVT_BUTTON,on_apply) + close_btn.Bind(wx.EVT_BUTTON,lambda evt:popup.Dismiss()) + + ph=popup.GetSize().height + popup.SetPosition(wx.Point(fr.x+(fr.width-popup_w)//2,fr.y+(fr.height-ph)//2)) + popup.Popup() + + + def show_count_popup(self,event): + counts=getattr(self,'_counts',{}) + if not counts_enable_diagnostics(counts): + return + if not hasattr(self,'_count_threshold'): + self._count_threshold=250 + self._show_behavior_count_popup( + 'Prepared Training Examples',counts,self._count_threshold, + lambda t:setattr(self,'_count_threshold',t)) + + + def _count_from_subfolders(self,folder_path): + return count_sorted_examples(folder_path) + + + def _update_sorted_count_display(self,folder_path): + counts=self._count_from_subfolders(folder_path) + if not counts_enable_diagnostics(counts): + self._sorted_counts={} + self.button_view_sorted_counts.Disable() + return + self._sorted_counts=counts + self.button_view_sorted_counts.Enable() + + + def show_sorted_count_popup(self,event): + counts=getattr(self,'_sorted_counts',{}) + if not counts_enable_diagnostics(counts): + return + if not hasattr(self,'_sorted_count_threshold'): + self._sorted_count_threshold=250 + self._show_behavior_count_popup( + 'Sorted Behavior Examples',counts,self._sorted_count_threshold, + lambda t:setattr(self,'_sorted_count_threshold',t)) + + def select_filepath(self,event): dialog=wx.DirDialog(self,'Select a directory','',style=wx.DD_DEFAULT_STYLE) if dialog.ShowModal()==wx.ID_OK: self.file_path=dialog.GetPath() self.text_inputexamples.SetLabel('Path to sorted behavior examples: '+self.file_path+'.') + self._update_sorted_count_display(self.file_path) dialog.Destroy() @@ -1467,6 +2108,9 @@ def select_datapath(self,event): else: self.text_trainingfolder.SetLabel('Pattern images w/o bodyparts in: '+self.data_path+'.') + if self.data_path is not None: + self._update_count_display(self.data_path) + def specify_augmentation(self,event): @@ -1609,14 +2253,13 @@ def __init__(self, parent): super().__init__(parent) self.notebook = parent - # Get all of the values needed from config.get_config(). self.config = config.get_config('models') - self.file_path=None # the folder that stores the ground-truth examples (each subfolder is a behavior category) - self.model_path = self.config['models'] # the 'LabGym/models' folder, which stores all the trained Categorizers + self.file_path=None + self.model_path = self.config['models'] logger.debug('%s: %r', 'self.model_path', self.model_path) - self.path_to_categorizer=None # path to the Categorizer - self.out_path=None # for storing the testing reports + self.path_to_categorizer=None + self.out_path=None self.display_window() @@ -1625,6 +2268,7 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S3) module_selectcategorizer=wx.BoxSizer(wx.HORIZONTAL) button_selectcategorizer=wx.Button(panel,label='Select a Categorizer\nto test',size=(300,40)) @@ -1657,6 +2301,16 @@ def display_window(self): boxsizer.Add(module_report,0,wx.LEFT|wx.RIGHT|wx.EXPAND,10) boxsizer.Add(0,5,0) + module_interactive=wx.BoxSizer(wx.HORIZONTAL) + self.checkbox_open_interactive=wx.CheckBox( + panel, + label='Show interactive results after testing', + ) + self.checkbox_open_interactive.SetValue(True) + module_interactive.Add(self.checkbox_open_interactive,0,wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_VERTICAL,10) + boxsizer.Add(module_interactive,0,wx.LEFT|wx.RIGHT|wx.EXPAND,10) + boxsizer.Add(0,5,0) + testanddelete=wx.BoxSizer(wx.HORIZONTAL) button_test=wx.Button(panel,label='Test the Categorizer',size=(300,40)) button_test.Bind(wx.EVT_BUTTON,self.test_categorizer) @@ -1697,10 +2351,10 @@ def select_categorizer(self,event): dialog1=wx.DirDialog(self,'Select a directory','',style=wx.DD_DEFAULT_STYLE) if dialog1.ShowModal()==wx.ID_OK: self.path_to_categorizer=dialog1.GetPath() + self.text_selectcategorizer.SetLabel('The path to the Categorizer to test is: '+self.path_to_categorizer+'.') else: self.path_to_categorizer=None dialog1.Destroy() - self.text_selectcategorizer.SetLabel('The path to the Categorizer to test is: '+self.path_to_categorizer+'.') else: self.path_to_categorizer=os.path.join(self.model_path,categorizer) self.text_selectcategorizer.SetLabel('Categorizer to test: '+categorizer+'.') @@ -1737,7 +2391,31 @@ def test_categorizer(self,event): wx.MessageBox('No Categorizer selected / path to ground-truth behavior examples.','Error',wx.OK|wx.ICON_ERROR) else: CA=Categorizers() - CA.test_categorizer(self.file_path,self.path_to_categorizer,result_path=self.out_path) + try: + report, cm, example_map, embedding_map = CA.test_categorizer(self.file_path,self.path_to_categorizer,result_path=self.out_path) + except CategorizerClassMismatchError as e: + message = ( + 'Behavior folder names must exactly match the Categorizer classes.\n\n' + f'Unrecognized behavior folders: {e.unrecognized_folders}\n' + f'Model classes absent from the fixture: {e.missing_classes}' + ) + wx.MessageBox(message, 'Class name mismatch', wx.OK|wx.ICON_ERROR) + return + + classnames = [k for k in report.keys() if k not in ['accuracy', 'macro avg', 'weighted avg']] + + if self.checkbox_open_interactive.GetValue(): + dialog = AutomatedDiagnosticsDialog( + self, + report, + cm, + classnames, + example_map, + embedding_map, + source_dataset_root=self.file_path, + ) + dialog.ShowModal() + dialog.Destroy() def remove_categorizer(self,event): @@ -1759,3 +2437,1409 @@ def remove_categorizer(self,event): shutil.rmtree(os.path.join(self.model_path,categorizer)) dialog1.Destroy() dialog.Destroy() + +class AutomatedDiagnosticsDialog(wx.Dialog): + def __init__(self, parent, report, cm, classnames, example_map, embedding_map, source_dataset_root=None): + super().__init__(parent, title="Automated Diagnostics - Test Results", size=(1000, 800), style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER | wx.MAXIMIZE_BOX) + + self.report = report + self.cm = cm + self.classnames = classnames + self.example_map = example_map + self.embedding_map = embedding_map + self.source_dataset_root = source_dataset_root + + self.cm_normalized = self.calculate_normalized_cm(cm) + self.is_normalized = False + + self.init_ui() + + self.Maximize(True) + + def calculate_normalized_cm(self, cm): + norm_cm = [] + for row in cm: + row_sum = sum(row) + if row_sum > 0: + norm_cm.append([round((val / row_sum) * 100, 1) for val in row]) + else: + norm_cm.append([0.0 for _ in row]) + return norm_cm + + def init_ui(self): + sizer = wx.BoxSizer(wx.VERTICAL) + font = wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD) + + header_sizer = wx.BoxSizer(wx.HORIZONTAL) + cm_label = wx.StaticText(self, label="Confusion Matrix:") + cm_label.SetFont(font) + header_sizer.Add(cm_label, 1, wx.ALIGN_CENTER_VERTICAL) + + self.toggle_btn = wx.ToggleButton(self, label="Show Normalized (%)") + self.toggle_btn.Bind(wx.EVT_TOGGLEBUTTON, self.on_toggle_cm) + header_sizer.Add(self.toggle_btn, 0, wx.ALIGN_CENTER_VERTICAL) + + sizer.Add(header_sizer, 0, wx.EXPAND | wx.ALL, 10) + + self.cm_grid = wx.grid.Grid(self) + self.cm_grid.CreateGrid(len(self.classnames), len(self.classnames)) + + for i, name in enumerate(self.classnames): + self.cm_grid.SetRowLabelValue(i, name) + self.cm_grid.SetColLabelValue(i, name) + + self.cm_grid.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.on_cell_click) + + self.cm_grid.SetRowLabelSize(wx.grid.GRID_AUTOSIZE) + self.cm_grid.SetColLabelSize(wx.grid.GRID_AUTOSIZE) + + self.cm_grid.DisableDragRowSize() + self.cm_grid.DisableDragColSize() + + self.update_grid_data() + sizer.Add(self.cm_grid, 1, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) + + bottom_dashboard_sizer = wx.BoxSizer(wx.HORIZONTAL) + + nlp_sizer = wx.BoxSizer(wx.VERTICAL) + + self.synopsis_label = wx.StaticText(self, label="Analyzing model performance...") + self.synopsis_label.SetFont(font) + nlp_sizer.Add(self.synopsis_label, 0, wx.BOTTOM | wx.ALL, 5) + + btn_row_sizer = wx.BoxSizer(wx.HORIZONTAL) + ( + label_overview, + label_major, + label_minor, + label_successes, + label_triage, + ) = DIAGNOSTIC_BUTTON_LABELS + self.btn_help = wx.Button(self, label=label_overview) + self.btn_major = wx.Button(self, label=label_major) + self.btn_minor = wx.Button(self, label=label_minor) + self.btn_successes = wx.Button(self, label=label_successes) + + self.btn_help.Bind(wx.EVT_BUTTON, self.show_help_view) + self.btn_major.Bind(wx.EVT_BUTTON, self.show_major_confusions_view) + self.btn_minor.Bind(wx.EVT_BUTTON, self.show_minor_confusions_view) + self.btn_successes.Bind(wx.EVT_BUTTON, self.show_successes_view) + + btn_row_sizer.Add(self.btn_help, 0, wx.RIGHT, 5) + btn_row_sizer.Add(self.btn_major, 0, wx.RIGHT, 5) + btn_row_sizer.Add(self.btn_minor, 0, wx.RIGHT, 5) + btn_row_sizer.Add(self.btn_successes, 0, 0, 0) + + self.btn_triage = wx.Button(self, label=label_triage) + self.btn_triage.Bind(wx.EVT_BUTTON, self.on_build_triage) + self.btn_triage.SetForegroundColour(wx.Colour(255, 203, 5)) + btn_row_sizer.Add(self.btn_triage, 0, wx.LEFT, 15) + + nlp_sizer.Add(btn_row_sizer, 0, wx.BOTTOM | wx.LEFT, 5) + + sort_sizer = wx.BoxSizer(wx.HORIZONTAL) + self.sort_label = wx.StaticText(self, label="Rank Insights By: ") + sort_sizer.Add(self.sort_label, 0, wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, 5) + + self.sort_dropdown = wx.Choice(self, choices=["Instances", "Proportion"]) + self.sort_dropdown.SetSelection(0) + self.sort_dropdown.Bind(wx.EVT_CHOICE, self.on_sort_changed) + sort_sizer.Add(self.sort_dropdown, 0, wx.ALIGN_CENTER_VERTICAL) + + nlp_sizer.Add(sort_sizer, 0, wx.BOTTOM | wx.LEFT, 5) + + + self.nlp_html = wx.html.HtmlWindow(self, style=wx.html.HW_SCROLLBAR_AUTO | wx.BORDER_NONE) + self.nlp_html.Bind(wx.html.EVT_HTML_LINK_CLICKED, self.on_insight_link_clicked) + + nlp_sizer.Add(self.nlp_html, 1, wx.EXPAND | wx.ALL, 5) + bottom_dashboard_sizer.Add(nlp_sizer, 1, wx.EXPAND | wx.RIGHT, 10) + + table_sizer = wx.BoxSizer(wx.VERTICAL) + + table_header_sizer = wx.BoxSizer(wx.HORIZONTAL) + self.table_label = wx.StaticText(self, label="Highlight behaviors below 0.60: ") + self.table_label.SetFont(font) + self.metric_choice = wx.Choice(self, choices=["F1-score", "Precision", "Recall"]) + self.metric_choice.SetSelection(0) + self.metric_choice.Bind(wx.EVT_CHOICE, self.on_metric_change) + + table_header_sizer.Add(self.table_label, 0, wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, 5) + table_header_sizer.Add(self.metric_choice, 0, wx.ALIGN_CENTER_VERTICAL) + table_sizer.Add(table_header_sizer, 0, wx.BOTTOM, 5) + + self.list_ctrl = wx.ListCtrl(self, style=wx.LC_REPORT | wx.BORDER_SUNKEN) + self.list_ctrl.InsertColumn(0, "Behavior", width=120) + self.list_ctrl.InsertColumn(1, "Precision", width=80) + self.list_ctrl.InsertColumn(2, "Recall", width=80) + self.list_ctrl.InsertColumn(3, "F1", width=80) + self.list_ctrl.InsertColumn(4, "Support", width=80) + self.update_table_data() + + table_sizer.Add(self.list_ctrl, 1, wx.EXPAND) + bottom_dashboard_sizer.Add(table_sizer, 1, wx.EXPAND | wx.LEFT, 10) + + sizer.Add(bottom_dashboard_sizer, 1, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) + + btn_sizer = wx.BoxSizer(wx.HORIZONTAL) + close_btn = wx.Button(self, wx.ID_CLOSE, "Close") + close_btn.Bind(wx.EVT_BUTTON, lambda evt: self.EndModal(wx.ID_CANCEL)) + btn_sizer.Add(close_btn, 0, wx.ALL, 10) + sizer.Add(btn_sizer, 0, wx.ALIGN_RIGHT) + + self.analyze_confusion_data() + self.show_help_view(None) + + self.SetSizer(sizer) + self.Layout() + + def on_build_triage(self, event): + """Gathers all confusions and launches the Triage Builder.""" + all_confusions = [] + + for count, i, j, prop in self.nlp_major: + item = f"{self.classnames[i]} -> {self.classnames[j]} ({count} errors)" + if item not in all_confusions: + all_confusions.append(item) + + for mc in self.nlp_minor: + for err_count, pred_class in mc['top_confusions']: + item = f"{mc['class']} -> {pred_class} ({err_count} errors)" + if item not in all_confusions: + all_confusions.append(item) + + if not all_confusions: + wx.MessageBox("No confusions detected to triage!", "All Clear", wx.OK | wx.ICON_INFORMATION) + return + + dialog = TriageBuilderDialog( + self, + all_confusions, + self.example_map, + self.report, + self.cm, + self.classnames, + self.embedding_map, + source_dataset_root=self.source_dataset_root, + ) + dialog.ShowModal() + dialog.Destroy() + + def on_sort_changed(self, event): + """Re-sorts the NLP data and refreshes the views when the dropdown changes.""" + self.analyze_confusion_data() + + if getattr(self, 'current_view', 'major') == 'minor': + self.show_minor_confusions_view(None) + else: + self.show_major_confusions_view(None) + + def update_grid_data(self): + cm_rows = len(self.cm) + cm_cols = len(self.cm[0]) if cm_rows > 0 else 0 + data_to_use = self.cm_normalized if self.is_normalized else self.cm + + for i in range(len(self.classnames)): + row_sum = sum(self.cm[i]) if i < cm_rows else 0 + + for j in range(len(self.classnames)): + if i < cm_rows and j < cm_cols: + val = f"{data_to_use[i][j]}%" if self.is_normalized else str(data_to_use[i][j]) + + if i != j and self.cm[i][j] > 0: + err_pct = self.cm[i][j] / row_sum if row_sum > 0 else 0 + intensity = min(1.0, err_pct / 0.5) + r_val = int(40 + (215 * intensity)) + bg_color = wx.Colour(r_val, 0, 0) + elif i == j and row_sum > 0: + accuracy = self.cm[i][j] / row_sum if row_sum > 0 else 0 + bg_color = wx.Colour(*cm_correct_cell_rgb(accuracy)) + else: + bg_color = wx.Colour(30, 30, 30) + else: + val = "0.0%" if self.is_normalized else "0" + bg_color = wx.Colour(30, 30, 30) + + self.cm_grid.SetCellValue(i, j, val) + self.cm_grid.SetReadOnly(i, j, True) + self.cm_grid.SetCellAlignment(i, j, wx.ALIGN_CENTER, wx.ALIGN_CENTER) + self.cm_grid.SetCellBackgroundColour(i, j, bg_color) + self.cm_grid.SetCellTextColour(i, j, wx.Colour(255, 255, 255)) + + self.refresh_cm_column_widths() + self.cm_grid.ForceRefresh() + + def refresh_cm_column_widths(self): + """Size columns from current labels/values, with a padded floor for ``100.0%``.""" + grid = self.cm_grid + grid.AutoSizeColumns(False) + font = grid.GetDefaultCellFont() + text_w, _h, _d, _el = grid.GetFullTextExtent('100.0%', font) + # Modest horizontal padding so centered percentages are not clipped. + min_width = text_w + 16 + for col in range(grid.GetNumberCols()): + if grid.GetColSize(col) < min_width: + grid.SetColSize(col, min_width) + + def on_toggle_cm(self, event): + self.is_normalized = self.toggle_btn.GetValue() + if self.is_normalized: + self.toggle_btn.SetLabel("Show Raw Counts") + else: + self.toggle_btn.SetLabel("Show Normalized (%)") + + self.update_grid_data() + + def on_insight_link_clicked(self, event): + """Highlights the specific grid cell or row when a user clicks the diagnostic text.""" + href = event.GetLinkInfo().GetHref() + + self.update_grid_data() + + if href.startswith('cell:'): + coords = href.replace('cell:', '').split(',') + row, col = int(coords[0]), int(coords[1]) + self.cm_grid.SetCellBackgroundColour(row, col, wx.Colour(255, 203, 5)) + self.cm_grid.SetCellTextColour(row, col, wx.Colour(0, 0, 0)) + self.cm_grid.MakeCellVisible(row, col) + + elif href.startswith('row:'): + row = int(href.replace('row:', '')) + self.cm_grid.MakeCellVisible(row, row) + + self.cm_grid.SetCellBackgroundColour(row, row, wx.Colour(0, 255, 255)) + self.cm_grid.SetCellTextColour(row, row, wx.Colour(0, 0, 0)) + + cm_rows = len(self.cm) + confusions = [] + for j in range(cm_rows): + if row != j and self.cm[row][j] > 0: + confusions.append((self.cm[row][j], j)) + + confusions.sort(reverse=True, key=lambda x: x[0]) + for err_val, col in confusions[:3]: + self.cm_grid.SetCellBackgroundColour(row, col, wx.Colour(255, 203, 5)) + self.cm_grid.SetCellTextColour(row, col, wx.Colour(0, 0, 0)) + + self.cm_grid.ForceRefresh() + self.cm_grid.ClearSelection() + + def analyze_confusion_data(self): + """Runs once to pre-calculate errors and successes using proportional math.""" + cm_rows = len(self.cm) + self.nlp_major = [] + self.nlp_minor = [] + self.nlp_success = [] + self.nlp_meaningless = [] + + self.nlp_meaningless = collect_insufficient_support_entries(self.classnames, self.report) + low_support_classes = {entry['class'] for entry in self.nlp_meaningless} + + for i in range(cm_rows): + true_class = self.classnames[i] + metrics = self.report.get(true_class, {}) + support = float(metrics.get('support', 0)) + f1_score = float(metrics.get('f1-score', 0.0)) + + if true_class in low_support_classes: + continue + + if f1_score >= 0.85: + self.nlp_success.append({ + 'index': i, + 'class': true_class, + 'f1': f1_score, + 'support': support + }) + continue + + found_major_confusion = False + for j in range(cm_rows): + if i != j and self.cm[i][j] > 0: + error_count = self.cm[i][j] + error_proportion = error_count / support + + if error_proportion >= 0.10: + self.nlp_major.append((error_count, i, j, error_proportion)) + found_major_confusion = True + + if not found_major_confusion: + row_errors = sum(self.cm[i]) - self.cm[i][i] + pct_errors = (row_errors / support) * 100 if support > 0 else 0 + + specific_confusions = [] + for j in range(cm_rows): + if i != j and self.cm[i][j] > 0: + specific_confusions.append((self.cm[i][j], self.classnames[j])) + + specific_confusions.sort(reverse=True, key=lambda x: x[0]) + top_specifics = specific_confusions[:3] + + self.nlp_minor.append({ + 'index': i, + 'class': true_class, + 'support': support, + 'total_errors': row_errors, + 'pct_errors': pct_errors, + 'top_confusions': top_specifics + }) + + + sort_mode = self.sort_dropdown.GetStringSelection() + + if sort_mode == "Proportion": + self.nlp_major.sort(reverse=True, key=lambda x: x[3]) + self.nlp_minor.sort(reverse=True, key=lambda x: x['pct_errors']) + else: + self.nlp_major.sort(reverse=True, key=lambda x: x[0]) + self.nlp_minor.sort(reverse=True, key=lambda x: x['total_errors']) + + + major_count = len(self.nlp_major) + if major_count == 0: + self.synopsis_label.SetLabel("No major confusion patterns were identified at the configured thresholds.") + elif major_count > 5: + self.synopsis_label.SetLabel(f"{major_count} major systematic confusions detected. Showing top 5 most severe.") + else: + self.synopsis_label.SetLabel(f"{major_count} major systematic confusions detected.") + + + def show_major_confusions_view(self, event=None): + self.current_view = 'major' + self.sort_label.Show(True) + self.sort_dropdown.Show(True) + self.Layout() + + html = "" + + if not self.nlp_major: + html += "

No major confusion patterns

No major confusion patterns were identified at the configured thresholds.

" + else: + html += "

Major Systematic Confusions:

" + for count, i, j, prop in self.nlp_major[:5]: + true_class = self.classnames[i] + pred_class = self.classnames[j] + prop_pct = round(prop * 100, 1) + + link = f"{true_class} → {pred_class}" + html += "
" + + error_txt = f"{count} errors, {prop_pct}% of {true_class} data" + + html += f"

{link} ({error_txt})

" + + html += "
" + + html += "" + self.nlp_html.SetPage(html) + + def show_minor_confusions_view(self, event=None): + self.current_view = 'minor' + self.sort_label.Show(True) + self.sort_dropdown.Show(True) + self.Layout() + + html = "" + + + if not self.nlp_minor: + html += "

No dispersed minor confusion patterns

No dispersed minor confusion patterns were identified at the configured thresholds.

" + else: + html += "

Dispersed / Minor Confusions:

" + html += "

The Categorizer struggles with these behaviors, but the mistakes are scattered across many categories rather than just one. This usually indicates weak feature extraction signals, highly variable subject movement, or simply, too few video examples.

" + + for mc in self.nlp_minor: + c_idx = mc['index'] + c_name = mc['class'] + supp = int(mc['support']) + errs = mc['total_errors'] + pct = round(mc['pct_errors'], 1) + + warning = " (fewer than 100 examples)" if supp < 100 else "" + link = f"{c_name}" + + html += f"
" + html += f"

{link}{warning}
" + html += f"Support: {supp} examples | Total Errors: {errs} ({pct}% of data)

" + + if mc['top_confusions']: + html += "

Top confusions:

    " + for err_count, pred_class in mc['top_confusions']: + html += f"
  • To {pred_class}: {err_count} errors
  • " + html += "
" + html += "
" + + html += "" + self.nlp_html.SetPage(html) + + def show_successes_view(self, event=None): + self.current_view = 'successes' + self.sort_label.Show(False) + self.sort_dropdown.Show(False) + self.Layout() + + html = "" + + if self.nlp_success: + html += "

Performing Reliably (F1 ≥ 85%):

" + html += "

On this test set, the following behaviors meet the F1 ≥ 85% threshold (advisory; not a guarantee of field performance):

" + html += "
    " + for sc in self.nlp_success: + c_idx = sc['index'] + c_name = sc['class'] + f1_pct = round(sc['f1'] * 100, 1) + supp = int(sc['support']) + + link = f"{c_name}" + html += f"
  • {link} ({f1_pct}% F1) [{supp} examples]
  • " + html += "
" + else: + html += "

F1 threshold not met

" + html += "

No behaviors reached the F1 ≥ 85% threshold on this test set.

" + html += "

Review Major and Minor Confusions for advisory patterns.

" + + if self.nlp_meaningless: + html += "

Too few examples for automated analysis

" + html += "

These classes remain listed. Observed support is below the minimum required for automated major/minor interpretation. They are omitted from automated major/minor ranking only.

" + html += "
    " + for mc in self.nlp_meaningless: + html += ( + f"
  • {mc['class']}: {mc['support']} examples; " + f"at least {mc['min_support']} required
  • " + ) + html += "
" + + html += "" + self.nlp_html.SetPage(html) + + def show_help_view(self, event=None): + """Generates the HTML for the layman's explanation.""" + self.current_view = 'help' + self.sort_label.Show(False) + self.sort_dropdown.Show(False) + self.Layout() + + html = """ + +

Overview

+

A Confusion Matrix is a table that shows where the Categorizer gets confused on this test set.

+

Rows (Left): What the subject was actually doing (Ground Truth).

+

Columns (Top): What the Categorizer guessed the subject was doing (Prediction).

+

If you look at the diagonal line going from top-left to bottom-right, those are the correct guesses. Any numbers sitting outside that diagonal line represent mistakes.

+

You can click on any cell in the matrix to view the video examples of where the Categorizer either correctly or incorrectly guessed the behavior.

+

Diagnostic summaries are advisory and are based on the configured thresholds and this test set only.

+ + """ + self.nlp_html.SetPage(html) + + def on_metric_change(self, event): + self.update_table_data() + + def update_table_data(self): + self.list_ctrl.DeleteAllItems() + + selection = self.metric_choice.GetStringSelection() + metric_key = 'f1-score' + if selection == "Precision": + metric_key = 'precision' + elif selection == "Recall": + metric_key = 'recall' + + index = 0 + for name in self.classnames: + if name in self.report and isinstance(self.report[name], dict): + metrics = self.report[name] + self.list_ctrl.InsertItem(index, name) + + precision = float(metrics.get('precision', 0.0)) + recall = float(metrics.get('recall', 0.0)) + f1 = float(metrics.get('f1-score', 0.0)) + support = float(metrics.get('support', 0.0)) + + self.list_ctrl.SetItem(index, 1, f"{precision:.2f}") + self.list_ctrl.SetItem(index, 2, f"{recall:.2f}") + self.list_ctrl.SetItem(index, 3, f"{f1:.2f}") + self.list_ctrl.SetItem(index, 4, str(int(support))) + + val_to_check = float(metrics.get(metric_key, 0.0)) + if val_to_check < 0.60: + self.list_ctrl.SetItemBackgroundColour(index, wx.Colour(150, 0, 0)) + else: + self.list_ctrl.SetItemBackgroundColour(index, wx.Colour(30, 30, 30)) + + self.list_ctrl.SetItemTextColour(index, wx.Colour(255, 255, 255)) + index += 1 + + def generate_diagnostic_insights_html(self, top_n=3, support_threshold=50): + cm_rows = len(self.cm) + errors = [] + perfect_classes = [] + + for i in range(cm_rows): + true_class = self.classnames[i] + support_true = self.report.get(true_class, {}).get('support', 0) + + if support_true == 0: + continue + + row_errors = sum(self.cm[i]) - self.cm[i][i] + if row_errors == 0: + perfect_classes.append(true_class) + + for j in range(cm_rows): + if i != j and self.cm[i][j] > 0: + errors.append((self.cm[i][j], i, j)) + + errors.sort(reverse=True, key=lambda x: x[0]) + + html = "" + + if not errors: + html += "

No major confusion patterns

No major confusion patterns were identified at the configured thresholds.

" + else: + html += "

Here is where the Categorizer is struggling:

" + + for count, i, j in errors[:top_n]: + true_class = self.classnames[i] + pred_class = self.classnames[j] + support_true = self.report.get(true_class, {}).get('support', 0) + support_pred = self.report.get(pred_class, {}).get('support', 0) + + link = f"{true_class} → {pred_class}" + + html += "
" + + if support_true >= support_threshold and support_pred >= support_threshold: + html += f"

{link} ({count} errors)

Possible pattern (advisory): Both behaviors have relatively robust support on this test set. Because the Categorizer is still confusing them, they might be visually similar. Consider reviewing whether labels overlap.

" + else: + lowest_class = true_class if support_true < support_pred else pred_class + html += f"

{link} ({count} errors)

Possible pattern (advisory): Support for {lowest_class} is limited on this test set. Adding more examples may help, but this is not a definitive diagnosis.

" + + html += "
" + + if perfect_classes: + html += "

What's working perfectly:

" + html += "

Zero confusions predicting: " + ", ".join(perfect_classes) + "

" + + html += "" + return html + + def on_cell_click(self, event): + row = event.GetRow() + col = event.GetCol() + + self.cm_grid.ClearSelection() + + if row == -1 or col == -1: + return + + if row < len(self.classnames) and col < len(self.classnames): + true_class = self.classnames[row] + pred_class = self.classnames[col] + + key = (true_class, pred_class) + examples = self.example_map.get(key, []) + + if examples: + viewer = ExampleViewerDialog(self, true_class, pred_class, examples) + viewer.ShowModal() + viewer.Destroy() + else: + wx.MessageBox(f"No examples found for True: '{true_class}', Predicted: '{pred_class}'", "No Data", wx.OK | wx.ICON_INFORMATION) + + +class ExampleViewerDialog(wx.Dialog): + def __init__(self, parent, true_class, pred_class, examples): + title = f"Reviewing Examples: True '{true_class}' -> Predicted '{pred_class}'" + super().__init__(parent, title=title, size=(600, 400), style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER) + + self.examples = examples + self.init_ui() + + def init_ui(self): + sizer = wx.BoxSizer(wx.VERTICAL) + + info_label = wx.StaticText(self, label=f"Found {len(self.examples)} example(s). Double-click a file to open it:") + sizer.Add(info_label, 0, wx.ALL, 10) + + self.list_box = wx.ListBox(self, choices=self.examples, style=wx.LB_SINGLE | wx.LB_HSCROLL) + self.list_box.Bind(wx.EVT_LISTBOX_DCLICK, self.on_double_click) + sizer.Add(self.list_box, 1, wx.EXPAND | wx.LEFT | wx.RIGHT, 10) + + btn_sizer = wx.BoxSizer(wx.HORIZONTAL) + close_btn = wx.Button(self, wx.ID_CLOSE, "Close") + close_btn.Bind(wx.EVT_BUTTON, lambda evt: self.EndModal(wx.ID_CANCEL)) + btn_sizer.Add(close_btn, 0, wx.ALL, 10) + sizer.Add(btn_sizer, 0, wx.ALIGN_RIGHT) + + self.SetSizer(sizer) + self.Layout() + + def on_double_click(self, event): + selection = self.list_box.GetSelection() + if selection != wx.NOT_FOUND: + filepath = self.examples[selection] + + try: + if sys.platform == "win32": + os.startfile(filepath) + elif sys.platform == "darwin": + subprocess.call(["open", filepath]) + else: + subprocess.call(["xdg-open", filepath]) + except Exception as e: + wx.MessageBox(f"Failed to open file:\n{e}", "Error", wx.OK | wx.ICON_ERROR) + + +class TriageBuilderDialog(wx.Dialog): + NOMINAL_CLIENT_SIZE = (960, 720) + OPS_HELP_HEIGHT_NOMINAL = 150 + OPS_HELP_HEIGHT_FLOOR = 100 + + def __init__(self, parent, confusions_list, example_map, report, cm, classnames, embedding_map, source_dataset_root=None): + super().__init__( + parent, + title="Triage Action Plan Builder", + style=wx.DEFAULT_DIALOG_STYLE, + ) + self.confusions_list = confusions_list + self.example_map = example_map + self.embedding_map = embedding_map + + self.report = report + self.cm = cm + self.classnames = classnames + self.source_dataset_root = source_dataset_root + + self.init_ui() + self._apply_fitted_fixed_size() + + def _work_area_size(self): + """Return usable display client area for fitting this dialog.""" + try: + index = wx.Display.GetFromWindow(self) + if index == wx.NOT_FOUND and self.GetParent() is not None: + index = wx.Display.GetFromWindow(self.GetParent()) + if index == wx.NOT_FOUND: + index = 0 + area = wx.Display(index).GetClientArea() + if area.width > 0 and area.height > 0: + return area.width, area.height + except Exception: + pass + parent = self.GetParent() + if parent is not None: + top = parent.GetTopLevelParent() + if top is not None: + size = top.GetClientSize() + if size.width > 0 and size.height > 0: + return size.width, size.height + return 1024, 768 + + def _apply_fitted_fixed_size(self): + """Fit nominal client size to the active display and lock resizing.""" + nominal_w, nominal_h = self.NOMINAL_CLIENT_SIZE + work_w, work_h = self._work_area_size() + fitted_w, fitted_h = fit_dialog_client_size(nominal_w, nominal_h, work_w, work_h) + # Shrink ops-help pane on short fitted heights while keeping a usable floor. + shrink = max(0, nominal_h - fitted_h) + ops_h = max(self.OPS_HELP_HEIGHT_FLOOR, self.OPS_HELP_HEIGHT_NOMINAL - min(shrink, 50)) + if hasattr(self, 'ops_help_html'): + self.ops_help_html.SetMinSize((-1, ops_h)) + self.ops_help_html.SetSize((-1, ops_h)) + if hasattr(self, 'intro_lbl'): + self.intro_lbl.Wrap(max(200, fitted_w - 40)) + self.SetClientSize(fitted_w, fitted_h) + # Lock outer size after client size accounts for title-bar chrome. + outer = self.GetSize() + self.SetMinSize(outer) + self.SetMaxSize(outer) + if self.GetParent() is not None: + self.CentreOnParent() + else: + self.Centre() + self.Layout() + + def get_centroid(self, file_list): + """Calculates the mathematical centroid of a cluster of videos and returns the most representative file.""" + if not file_list: + return None + if len(file_list) == 1: + return file_list[0] + + import numpy as np + + embs = [self.embedding_map[f] for f in file_list] + + mean_emb = np.mean(embs, axis=0) + mean_norm = np.linalg.norm(mean_emb) + if mean_norm == 0: + return file_list[0] + + best_sim = -2.0 + centroid_file = file_list[0] + + for f, emb in zip(file_list, embs): + emb_norm = np.linalg.norm(emb) + if emb_norm == 0: continue + + sim = np.dot(emb, mean_emb) / (emb_norm * mean_norm) + if sim > best_sim: + best_sim = sim + centroid_file = f + + return centroid_file + + def init_ui(self): + main_sizer = wx.BoxSizer(wx.VERTICAL) + + title_lbl = wx.StaticText(self, label="Assign confusions to a root-cause hypothesis to generate your action plan.") + title_font = wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD) + title_lbl.SetFont(title_font) + title_lbl.SetForegroundColour(wx.Colour(255, 203, 5)) + main_sizer.Add(title_lbl, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, 15) + + intro_lbl = wx.StaticText( + self, + label=( + "Triage Plan: You are reviewing confusion patterns from this test set. " + "Assign each selected pattern to a possible follow-up hypothesis (H1, H2, or H3). " + "These hypotheses are advisory—they are not diagnoses or required actions. " + "LabGym prepares the plan from your selections; scientific decisions remain yours." + ), + ) + self.intro_lbl = intro_lbl + intro_lbl.Wrap(900) + main_sizer.Add(intro_lbl, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) + + self.ops_help_html = wx.html.HtmlWindow( + self, + size=(-1, self.OPS_HELP_HEIGHT_NOMINAL), + style=wx.html.HW_SCROLLBAR_AUTO | wx.BORDER_SIMPLE, + ) + self.ops_help_html.SetPage( + """ + +

H1 — Merge hypothesis (advisory): Confusion may indicate overlapping behavior definitions. + On Finish, LabGym creates a Triage Plan package and, on the revised sorted test examples only, + moves all examples from the true-class folder into the predicted-class folder and removes the emptied folder. + The original selected test fixture is unchanged. If scientifically accepted, apply the same class-definition + decision to separate training data; do not copy evaluation examples into training; train and reevaluate a new Categorizer.

+

H2 — New-class / extract hypothesis (advisory): H2 is advisory only. LabGym does not create the new class or move examples. + In revised_sorted_test_examples, manually review and organize examples if you accept this hypothesis. + Do not copy evaluation examples into training. Reproduce accepted taxonomy changes in separate training data, + then train and reevaluate a new Categorizer.

+

H3 — Needs-more-data hypothesis (advisory): Confusion may indicate insufficient variety of training examples. + On Finish, LabGym copies up to three reference example pairs into + LabGym_Diagnostics/H3_Variance_References in the package. + These references illustrate variance in the evaluation set. Collect or prepare additional independent training examples; + do not move these evaluation references into training. Train and reevaluate a new Categorizer afterward. + The source dataset is unchanged.

+ + """ + ) + main_sizer.Add(self.ops_help_html, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) + + columns_sizer = wx.BoxSizer(wx.HORIZONTAL) + + left_sizer = wx.BoxSizer(wx.VERTICAL) + lbl_unassigned = wx.StaticText(self, label="Unassigned Confusions:") + lbl_unassigned.SetFont(wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)) + left_sizer.Add(lbl_unassigned, 0, wx.BOTTOM, 8) + + self.lb_unassigned = wx.ListBox(self, choices=self.confusions_list, style=wx.LB_EXTENDED) + self.lb_unassigned.SetFont(wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) + left_sizer.Add(self.lb_unassigned, 1, wx.EXPAND) + columns_sizer.Add(left_sizer, 4, wx.EXPAND | wx.ALL, 10) + + mid_sizer = wx.BoxSizer(wx.VERTICAL) + mid_sizer.AddStretchSpacer() + + btn_h1 = wx.Button(self, label="Assign to H1 (Merge)", size=(190, 40)) + btn_h1.Bind(wx.EVT_BUTTON, lambda evt: self.move_items(self.lb_unassigned, self.lb_h1)) + mid_sizer.Add(btn_h1, 0, wx.BOTTOM | wx.ALIGN_CENTER_HORIZONTAL, 15) + + btn_h2 = wx.Button(self, label="Assign to H2 (Extract)", size=(190, 40)) + btn_h2.Bind(wx.EVT_BUTTON, self.on_move_h2) + mid_sizer.Add(btn_h2, 0, wx.BOTTOM | wx.ALIGN_CENTER_HORIZONTAL, 15) + + btn_h3 = wx.Button(self, label="Assign to H3 (Add Data)", size=(190, 40)) + btn_h3.Bind(wx.EVT_BUTTON, lambda evt: self.move_items(self.lb_unassigned, self.lb_h3)) + mid_sizer.Add(btn_h3, 0, wx.BOTTOM | wx.ALIGN_CENTER_HORIZONTAL, 15) + + btn_return = wx.Button(self, label="Return Selected", size=(190, 40)) + btn_return.Bind(wx.EVT_BUTTON, self.on_return_items) + mid_sizer.Add(btn_return, 0, wx.TOP | wx.ALIGN_CENTER_HORIZONTAL, 40) + + mid_sizer.AddStretchSpacer() + columns_sizer.Add(mid_sizer, 0, wx.EXPAND | wx.TOP | wx.BOTTOM, 10) + + right_sizer = wx.BoxSizer(wx.VERTICAL) + + lbl_h1 = wx.StaticText(self, label="H1: Merge on clone:") + lbl_h1.SetFont(wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)) + lbl_h1.SetForegroundColour(wx.Colour(100, 200, 100)) + right_sizer.Add(lbl_h1, 0, wx.BOTTOM, 4) + self.lb_h1 = wx.ListBox(self, style=wx.LB_EXTENDED) + right_sizer.Add(self.lb_h1, 1, wx.EXPAND | wx.BOTTOM, 10) + + lbl_h2 = wx.StaticText(self, label="H2: New class (manual):") + lbl_h2.SetFont(wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)) + lbl_h2.SetForegroundColour(wx.Colour(100, 150, 255)) + right_sizer.Add(lbl_h2, 0, wx.BOTTOM, 4) + self.lb_h2 = wx.ListBox(self, style=wx.LB_EXTENDED) + right_sizer.Add(self.lb_h2, 1, wx.EXPAND | wx.BOTTOM, 10) + + lbl_h3 = wx.StaticText(self, label="H3: Needs more data:") + lbl_h3.SetFont(wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)) + lbl_h3.SetForegroundColour(wx.Colour(255, 150, 100)) + right_sizer.Add(lbl_h3, 0, wx.BOTTOM, 4) + self.lb_h3 = wx.ListBox(self, style=wx.LB_EXTENDED) + right_sizer.Add(self.lb_h3, 1, wx.EXPAND) + + columns_sizer.Add(right_sizer, 5, wx.EXPAND | wx.ALL, 10) + + main_sizer.Add(columns_sizer, 1, wx.EXPAND) + + footer_sizer = wx.BoxSizer(wx.HORIZONTAL) + btn_finish = wx.Button(self, label="Finish and Generate Report", size=(220, 40)) + btn_finish.SetFont(wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)) + btn_finish.SetForegroundColour(wx.Colour(100, 200, 100)) + btn_finish.Bind(wx.EVT_BUTTON, self.on_finish) + footer_sizer.Add(btn_finish, 0, wx.ALL, 10) + + btn_cancel = wx.Button(self, wx.ID_CANCEL, "Cancel", size=(100, 40)) + footer_sizer.Add(btn_cancel, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 10) + + main_sizer.Add(footer_sizer, 0, wx.ALIGN_RIGHT) + self.SetSizer(main_sizer) + self.Layout() + + def move_items(self, source_lb, target_lb, append_text=""): + selections = source_lb.GetSelections() + if not selections: + return + + for idx in reversed(selections): + item_text = source_lb.GetString(idx) + target_lb.Append(f"{item_text} {append_text}") + source_lb.Delete(idx) + + def on_move_h2(self, event): + if not self.lb_unassigned.GetSelections(): + return + + dlg = wx.TextEntryDialog(self, "What is the name of this new emergent behavior?", "Define Emergent Class") + if dlg.ShowModal() == wx.ID_OK: + new_name = dlg.GetValue().strip() + if new_name: + self.move_items(self.lb_unassigned, self.lb_h2, f"[NEW: {new_name}]") + dlg.Destroy() + + def on_return_items(self, event): + """Returns selected items from any right-side bucket back to unassigned.""" + for lb in [self.lb_h1, self.lb_h2, self.lb_h3]: + selections = lb.GetSelections() + for idx in reversed(selections): + text = lb.GetString(idx) + if "[NEW:" in text: + text = text.split(" [NEW:")[0] + self.lb_unassigned.Append(text) + lb.Delete(idx) + + def _resolve_source_dataset_root(self): + """Return absolute normalized source root, or (None, error_message).""" + explicit = self.source_dataset_root + if explicit: + root = os.path.abspath(os.path.normpath(explicit)) + if not os.path.isdir(root): + return None, f"Selected source dataset root is not a directory:\n{root}" + return root, None + + sample_file = None + for files in self.example_map.values(): + if files: + sample_file = files[0] + break + if not sample_file: + return None, "Could not locate source files for the Triage Plan package." + root = os.path.abspath(os.path.normpath(os.path.dirname(os.path.dirname(sample_file)))) + if not os.path.isdir(root): + return None, f"Inferred source dataset root is not a directory:\n{root}" + return root, None + + def _collect_h1_pairs(self): + pairs = [] + for i in range(self.lb_h1.GetCount()): + text = self.lb_h1.GetString(i) + source_class = text.split(" -> ")[0].strip() + target_class = text.split(" -> ")[1].split(" (")[0].strip() + pairs.append((source_class, target_class)) + return pairs + + def _open_folder_safely(self, folder): + try: + if sys.platform == "win32": + os.startfile(folder) + elif sys.platform == "darwin": + subprocess.call(["open", folder]) + else: + subprocess.call(["xdg-open", folder]) + return True, None + except Exception as e: + return False, str(e) + + def on_finish(self, event): + if not triage_assignment_counts(self.lb_h1.GetCount(), self.lb_h2.GetCount(), self.lb_h3.GetCount()): + wx.MessageBox( + "Assign at least one confusion to H1, H2, or H3 before generating a triage plan.", + "Empty triage plan", + wx.OK | wx.ICON_ERROR, + ) + return + + ok_pdf, pdf_err = reportlab_importable() + if not ok_pdf: + wx.MessageBox( + f"ReportLab is required to generate PDFs ({pdf_err}). Please install reportlab before generating a triage plan.", + "Missing Dependency", + wx.OK | wx.ICON_ERROR, + ) + return + + source_root, source_err = self._resolve_source_dataset_root() + if source_root is None: + wx.MessageBox(source_err, "Source Error", wx.OK | wx.ICON_ERROR) + return + + parent_dir = os.path.dirname(source_root) + suggested_name = next_versioned_triage_package_name(parent_dir, os.path.basename(source_root)) + + dlg = wx.TextEntryDialog( + self, + "Enter a name for the Triage Plan package folder:", + "Triage Plan Package", + suggested_name, + ) + if dlg.ShowModal() != wx.ID_OK: + dlg.Destroy() + return + package_name = dlg.GetValue() + dlg.Destroy() + + ok_name, name_err = validate_triage_package_name(package_name) + if not ok_name: + wx.MessageBox(name_err, "Invalid Package Name", wx.OK | wx.ICON_ERROR) + return + + package_dir = os.path.join(parent_dir, package_name) + if os.path.exists(package_dir): + wx.MessageBox( + f"A folder named \"{package_name}\" already exists.\n\n{package_dir}", + "Package Exists", + wx.OK | wx.ICON_ERROR, + ) + return + + h1_pairs = self._collect_h1_pairs() + if h1_pairs: + collisions, missing = collect_h1_filename_collisions(source_root, h1_pairs) + if missing: + lines = [] + for kind, cls in missing: + label = "true-class (source)" if kind == "source" else "predicted-class (target)" + lines.append(f"- Missing {label} folder: {cls}") + wx.MessageBox( + "H1 class folders are missing from the selected source dataset. " + "No package was created.\n\n" + "\n".join(lines), + "H1 class folder missing", + wx.OK | wx.ICON_ERROR, + ) + return + if collisions: + lines = [] + for rec in collisions: + true_c, pred_c = rec['pair'] + names = ", ".join(rec['filenames']) + lines.append(f"{true_c} → {pred_c}: {names}") + wx.MessageBox( + "The H1 merge would place entries with the same name in one behavior folder. " + "No package was created. Resolve the listed filename collisions, then generate " + "the Triage Plan again.\n\n" + "\n".join(lines), + "H1 filename collision", + wx.OK | wx.ICON_ERROR, + ) + return + + revised_dir = os.path.join(package_dir, "revised_sorted_test_examples") + diagnostics_dir = os.path.join(package_dir, "LabGym_Diagnostics") + busy = False + package_created = False + + try: + total_size = sum( + os.path.getsize(os.path.join(dirpath, f)) + for dirpath, _, filenames in os.walk(source_root) + for f in filenames + ) + total_size_mb = total_size / (1024 * 1024) + + total, used, free = shutil.disk_usage(parent_dir) + if total_size > free: + wx.MessageBox( + f"Not enough disk space to create the Triage Plan package.\n" + f"Required: {total_size_mb:.2f} MB\nAvailable: {free / (1024*1024):.2f} MB", + "Disk Space Error", + wx.OK | wx.ICON_ERROR, + ) + return + + wx.BeginBusyCursor() + busy = True + + os.makedirs(package_dir) + package_created = True + shutil.copytree(source_root, revised_dir) + os.makedirs(diagnostics_dir) + + for source_class, target_class in h1_pairs: + revised_source_dir = os.path.join(revised_dir, source_class) + revised_target_dir = os.path.join(revised_dir, target_class) + if not os.path.isdir(revised_source_dir) or not os.path.isdir(revised_target_dir): + raise OSError( + f"H1 class folder missing after copy: {source_class} -> {target_class}" + ) + for filename in os.listdir(revised_source_dir): + shutil.move( + os.path.join(revised_source_dir, filename), + os.path.join(revised_target_dir, filename), + ) + shutil.rmtree(revised_source_dir) + + pdf_path = next_versioned_pdf_path(diagnostics_dir) + + if self.lb_h3.GetCount() > 0: + import random + h3_ref_dir = os.path.join(diagnostics_dir, "H3_Variance_References") + os.makedirs(h3_ref_dir, exist_ok=True) + + for i in range(self.lb_h3.GetCount()): + text = self.lb_h3.GetString(i) + source_class = text.split(" -> ")[0].strip() + target_class = text.split(" -> ")[1].split(" (")[0].strip() + + key = (source_class, target_class) + examples = self.example_map.get(key, []) + + if examples: + samples = random.sample(examples, min(3, len(examples))) + for idx, avi_path in enumerate(samples): + if os.path.exists(avi_path): + safe_source = source_class.replace(" ", "_") + safe_target = target_class.replace(" ", "_") + + new_avi_name = f"{safe_source}_to_{safe_target}_sample{idx+1}.avi" + shutil.copy2(avi_path, os.path.join(h3_ref_dir, new_avi_name)) + + jpg_path = avi_path.replace(".avi", ".jpg") + if os.path.exists(jpg_path): + new_jpg_name = f"{safe_source}_to_{safe_target}_sample{idx+1}.jpg" + shutil.copy2(jpg_path, os.path.join(h3_ref_dir, new_jpg_name)) + + pdf_ok, pdf_fail_reason = self.generate_pdf_report(pdf_path, package_name) + + if busy: + wx.EndBusyCursor() + busy = False + + if not pdf_ok or not os.path.isfile(pdf_path): + detail = pdf_fail_reason or "PDF was not created." + wx.MessageBox( + "The Triage Plan package exists, but the expected PDF was not created.\n\n" + f"Package:\n{package_dir}\n\n" + f"Revised sorted test examples:\n{revised_dir}\n\n" + f"Failure detail:\n{detail}", + "Partial triage outcome", + wx.OK | wx.ICON_WARNING, + ) + return + + wx.MessageBox( + "Triage Plan package created.\n\n" + f"Package:\n{package_dir}\n\n" + f"Revised sorted test examples (select this folder in LabGym):\n{revised_dir}\n\n" + f"PDF:\n{pdf_path}\n\n" + "The original source fixture was not modified.", + "Triage Complete", + wx.OK | wx.ICON_INFORMATION, + ) + + self.EndModal(wx.ID_OK) + + opened, open_err = self._open_folder_safely(package_dir) + if not opened: + wx.MessageBox( + "The Triage Plan package was created, but LabGym could not open the package folder.\n\n" + f"Package:\n{package_dir}\n\n" + f"Detail:\n{open_err}", + "Folder Open Failed", + wx.OK | wx.ICON_WARNING, + ) + + except PermissionError: + if busy: + wx.EndBusyCursor() + msg = "LabGym does not have permission to write to this directory. Check your folder permissions." + if package_created: + msg += f"\n\nA partial Triage Plan package may remain at:\n{package_dir}" + wx.MessageBox(msg, "Permission Error", wx.OK | wx.ICON_ERROR) + except Exception as e: + if busy: + wx.EndBusyCursor() + msg = f"An OS error occurred during triage execution:\n{e}" + if package_created: + msg += f"\n\nA partial Triage Plan package may remain at:\n{package_dir}" + wx.MessageBox(msg, "System Error", wx.OK | wx.ICON_ERROR) + + def generate_pdf_report(self, filepath, dataset_name): + """Generate triage PDF. Returns (ok, error_message_or_None).""" + try: + from reportlab.lib.pagesizes import letter + from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, Table, TableStyle + from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle + from reportlab.lib.colors import HexColor, Color + from reportlab.lib import colors + from reportlab.lib.units import inch + import datetime + import os + except ImportError as e: + return False, f"ReportLab is required to generate PDFs ({e})." + + try: + doc = SimpleDocTemplate(filepath, pagesize=letter, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18) + styles = getSampleStyleSheet() + + title_style = ParagraphStyle('Title', parent=styles['Heading1'], fontName='Helvetica-Bold', fontSize=16, textColor=HexColor("#00274C"), spaceAfter=16) + h2_style = ParagraphStyle('H2', parent=styles['Heading2'], fontName='Helvetica-Bold', fontSize=12, textColor=HexColor("#333333"), spaceBefore=16, spaceAfter=8) + body_style = ParagraphStyle('Body', parent=styles['Normal'], fontName='Helvetica', fontSize=10, leading=14, textColor=HexColor("#1A1A1A")) + action_style = ParagraphStyle('Action', parent=styles['Normal'], fontName='Helvetica-Bold', fontSize=10, textColor=HexColor("#D82C20"), spaceAfter=12) + item_style = ParagraphStyle('Item', parent=styles['Normal'], fontName='Helvetica', fontSize=10, leading=14, leftIndent=20, spaceAfter=6) + caption_style = ParagraphStyle('Caption', parent=styles['Normal'], fontName='Helvetica-Oblique', fontSize=8, textColor=HexColor("#666666"), leftIndent=20, spaceBefore=4, spaceAfter=16) + + Story = [] + + accuracy = self.report.get('accuracy', 0.0) + macro_f1 = self.report.get('macro avg', {}).get('f1-score', 0.0) + + Story.append(Paragraph(f"LabGym Triage Action Plan", title_style)) + Story.append(Paragraph(f"Package: {dataset_name}", body_style)) + Story.append(Paragraph(f"Date Generated: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}", body_style)) + Story.append(Paragraph(f"Overall Accuracy: {accuracy*100:.1f}% | Macro F1-Score: {macro_f1*100:.1f}%", body_style)) + Story.append(Spacer(1, 15)) + + Story.append(Paragraph("Package layout and remediation", h2_style)) + Story.append(Paragraph( + "revised_sorted_test_examples contains the revised sorted test examples, cloned from the selected evaluation fixture. " + "LabGym_Diagnostics contains this report and optional H3 references. The original source fixture is unchanged. " + "This package is a Triage Plan result, not a complete repair or training workflow. For later LabGym sorted-example steps, " + "select revised_sorted_test_examples, not the package root. Reproduce accepted remediation in separate training data, " + "do not copy evaluation examples into training, and train and reevaluate a new Categorizer.", + body_style, + )) + Story.append(Spacer(1, 15)) + + Story.append(Paragraph("Confusion Matrix Overview", h2_style)) + Story.append(Paragraph("Cells highlighted with a thick gold border indicate confusions that were addressed in this triage session.", caption_style)) + + headers = ["True \\ Pred"] + [str(idx + 1) for idx in range(len(self.classnames))] + cm_data = [headers] + + for i in range(len(self.classnames)): + row_data = [f"{i + 1}. {self.classnames[i]}"] + for j in range(len(self.classnames)): + row_data.append(str(self.cm[i][j])) + cm_data.append(row_data) + + t_style = TableStyle([ + ('BACKGROUND', (0,0), (-1,0), HexColor("#00274C")), + ('TEXTCOLOR', (0,0), (-1,0), colors.whitesmoke), + ('ALIGN', (0,0), (-1,-1), 'CENTER'), + ('ALIGN', (0,1), (0,-1), 'LEFT'), + ('FONTNAME', (0,0), (-1,0), 'Helvetica-Bold'), + ('FONTSIZE', (0,0), (-1,-1), 7), + ('BOTTOMPADDING', (0,0), (-1,0), 6), + ('BACKGROUND', (0,1), (0,-1), HexColor("#f0f0f0")), + ('FONTNAME', (0,1), (0,-1), 'Helvetica-Bold'), + ('GRID', (0,0), (-1,-1), 0.5, colors.grey), + ]) + + for i in range(len(self.classnames)): + row_sum = sum(self.cm[i]) + for j in range(len(self.classnames)): + val = self.cm[i][j] + if val > 0: + if i == j: + intensity = min(1.0, val / row_sum) if row_sum > 0 else 0 + bg_color = Color(0, 0.8, 0, alpha=0.1 + (0.4 * intensity)) + else: + pct = val / row_sum if row_sum > 0 else 0 + intensity = min(1.0, pct / 0.5) + bg_color = Color(0.9, 0, 0, alpha=0.1 + (0.5 * intensity)) + t_style.add('BACKGROUND', (j+1, i+1), (j+1, i+1), bg_color) + + addressed_pairs = [] + for lb in [self.lb_h1, self.lb_h2, self.lb_h3]: + for idx in range(lb.GetCount()): + item_text = lb.GetString(idx) + clean_text = item_text.split(" [NEW:")[0] + source_class = clean_text.split(" -> ")[0].strip() + target_class = clean_text.split(" -> ")[1].split(" (")[0].strip() + addressed_pairs.append((source_class, target_class)) + + for src, tgt in addressed_pairs: + if src in self.classnames and tgt in self.classnames: + i = self.classnames.index(src) + j = self.classnames.index(tgt) + t_style.add('BOX', (j+1, i+1), (j+1, i+1), 2, HexColor("#FFCB05")) + + first_col_width = 1.5 * inch + remaining_width = 5.0 * inch + data_col_width = remaining_width / max(len(self.classnames), 1) + + col_widths = [first_col_width] + [data_col_width] * len(self.classnames) + + cm_table = Table(cm_data, colWidths=col_widths) + cm_table.setStyle(t_style) + Story.append(cm_table) + Story.append(Spacer(1, 15)) + + Story.append(Paragraph("Hypothesis 1: Merge on revised sorted test examples (advisory)", h2_style)) + Story.append(Paragraph( + "Confusion may indicate overlapping behavior definitions. H1 is an advisory merge hypothesis. " + "The merge is applied only to the revised sorted test examples: LabGym moves all examples from each listed " + "true-class folder into the predicted-class folder and removes the emptied folder. The original selected test fixture remains unchanged. " + "If scientifically accepted, apply the same class-definition decision to the separate training dataset. " + "Do not copy evaluation examples into training. Train and reevaluate a new Categorizer.", + body_style, + )) + Story.append(Spacer(1, 5)) + + if self.lb_h1.GetCount() == 0: + Story.append(Paragraph("None selected.", item_style)) + for i in range(self.lb_h1.GetCount()): + Story.append(Paragraph(f"• {self.lb_h1.GetString(i)}", item_style)) + Story.append(Spacer(1, 10)) + + Story.append(Paragraph("Hypothesis 2: New class / extract (advisory)", h2_style)) + Story.append(Paragraph( + "H2 is advisory only. LabGym does not create the new class or move examples. " + "In revised_sorted_test_examples, manually review and organize examples if you accept this hypothesis. " + "Do not copy evaluation examples into training. Reproduce accepted taxonomy changes in separate training data, " + "then train and reevaluate a new Categorizer.", + body_style, + )) + Story.append(Paragraph( + "USER ACTION: In revised_sorted_test_examples, manually review and organize examples if you accept this hypothesis. " + "Reproduce accepted changes in separate training data; do not copy evaluation examples into training.", + action_style, + )) + + if self.lb_h2.GetCount() == 0: + Story.append(Paragraph("None selected.", item_style)) + else: + for i in range(self.lb_h2.GetCount()): + item_text = self.lb_h2.GetString(i) + Story.append(Paragraph(f"• {item_text}", item_style)) + + source_class = item_text.split(" -> ")[0].strip() + target_class = item_text.split(" -> ")[1].split(" (")[0].strip() + key = (source_class, target_class) + examples = self.example_map.get(key, []) + + if examples: + avi_path = self.get_centroid(examples) + jpg_path = avi_path.replace(".avi", ".jpg") + file_name = os.path.basename(avi_path) + + if os.path.exists(jpg_path): + img = Image(jpg_path) + img.drawWidth = 2 * inch + img.drawHeight = 2 * inch + Story.append(img) + Story.append(Paragraph(f"Reference file: {file_name}", caption_style)) + + Story.append(Paragraph("Hypothesis 3: Needs more data (advisory)", h2_style)) + Story.append(Paragraph( + "Confusion may indicate insufficient variety of training examples. LabGym copies up to three reference example pairs into " + "LabGym_Diagnostics/H3_Variance_References and does not merge classes. " + "These references illustrate variance in the evaluation set. Collect or prepare additional independent training examples; " + "do not move these evaluation references into training. Train and reevaluate a new Categorizer afterward. " + "The source dataset is unchanged.", + body_style, + )) + Story.append(Paragraph( + "USER ACTION (optional): Collect or prepare additional independent training examples; do not move these evaluation references into training.", + action_style, + )) + + if self.lb_h3.GetCount() == 0: + Story.append(Paragraph("None selected.", item_style)) + else: + export_dir = os.path.dirname(filepath) + h3_ref_dir = os.path.join(export_dir, "H3_Variance_References") + + for i in range(self.lb_h3.GetCount()): + item_text = self.lb_h3.GetString(i) + Story.append(Paragraph(f"• {item_text}", item_style)) + + source_class = item_text.split(" -> ")[0].strip() + target_class = item_text.split(" -> ")[1].split(" (")[0].strip() + safe_source = source_class.replace(" ", "_") + safe_target = target_class.replace(" ", "_") + + for idx in range(3): + jpg_name = f"{safe_source}_to_{safe_target}_sample{idx+1}.jpg" + avi_name = f"{safe_source}_to_{safe_target}_sample{idx+1}.avi" + jpg_path = os.path.join(h3_ref_dir, jpg_name) + + if os.path.exists(jpg_path): + img = Image(jpg_path) + img.drawWidth = 2 * inch + img.drawHeight = 2 * inch + Story.append(img) + Story.append(Paragraph(f"Reference file: H3_Variance_References/{avi_name}", caption_style)) + + Story.append(Paragraph("Baseline References (True Positives)", h2_style)) + Story.append(Paragraph("Below are representative examples of correctly classified behaviors on this test set. Use these as a visual baseline for what the model currently treats as an example of the class.", body_style)) + + has_baselines = False + for i in range(len(self.classnames)): + cls_name = self.classnames[i] + if self.cm[i][i] > 0: + key = (cls_name, cls_name) + examples = self.example_map.get(key, []) + + if examples: + has_baselines = True + Story.append(Paragraph(f"• {cls_name}", item_style)) + + avi_path = self.get_centroid(examples) + jpg_path = avi_path.replace(".avi", ".jpg") + file_name = os.path.basename(avi_path) + + if os.path.exists(jpg_path): + img = Image(jpg_path) + img.drawWidth = 2 * inch + img.drawHeight = 2 * inch + Story.append(img) + Story.append(Paragraph(f"Reference file: {file_name}", caption_style)) + + if not has_baselines: + Story.append(Paragraph("No correct classifications available to generate baselines.", item_style)) + + doc.build(Story) + if not os.path.isfile(filepath): + return False, "PDF build completed but the output file was not found." + return True, None + except Exception as e: + return False, str(e) diff --git a/LabGym/gui_detector.py b/LabGym/gui_detector.py index 93db96c9..053f1fcd 100644 --- a/LabGym/gui_detector.py +++ b/LabGym/gui_detector.py @@ -37,6 +37,7 @@ from LabGym import config from .detector import Detector from .tools import extract_frames +from .gui_utils import add_info_button, create_hyperlink, INFO_COLOUR_S2 class PanelLv2_GenerateImages(wx.Panel): @@ -62,6 +63,7 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S2) module_inputvideos=wx.BoxSizer(wx.HORIZONTAL) button_inputvideos=wx.Button(panel,label='Select the video(s) to generate\nimage examples',size=(300,40)) @@ -253,6 +255,7 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S2) module_selectimages=wx.BoxSizer(wx.HORIZONTAL) button_selectimages=wx.Button(panel,label='Select the folder containing\nall the training images',size=(300,40)) @@ -302,6 +305,18 @@ def display_window(self): boxsizer.Add(button_train,0,wx.RIGHT|wx.ALIGN_RIGHT,90) boxsizer.Add(0,10,0) + # Match nested 10px module + button margins so the link lines up with the button column. + module_tutorial=wx.BoxSizer(wx.HORIZONTAL) + module_tutorial.Add( + create_hyperlink( + panel, + 'Training a Detector using LabGym', + 'https://youtu.be/mvwc-kK1dCc?si=OLywKfHwg3qOz_u4', + ), + 0, wx.LEFT|wx.RIGHT, 10) + boxsizer.Add(module_tutorial,0,wx.LEFT|wx.RIGHT|wx.EXPAND,10) + boxsizer.Add(0, 10, 0) + panel.SetSizer(boxsizer) self.Centre() @@ -419,6 +434,7 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S2) module_selectdetector=wx.BoxSizer(wx.HORIZONTAL) button_selectdetector=wx.Button(panel,label='Select a Detector\nto test',size=(300,40)) diff --git a/LabGym/gui_main.py b/LabGym/gui_main.py index cad4e057..9ae1b1f9 100644 --- a/LabGym/gui_main.py +++ b/LabGym/gui_main.py @@ -19,7 +19,6 @@ # Standard library imports. import logging -import sys from .gui_app_icon import set_frame_icon, setup_application_icons # Log the load of this module (by the module loader, on first import). @@ -31,17 +30,25 @@ # Related third party imports. import wx import wx.aui -import wx.lib.agw.hyperlink as hl +import wx.html +import webbrowser # Local application/library specific imports. from LabGym import __version__ -from .gui_utils import add_or_select_notebook_page +from .gui_appearance import select_for_appearance +from .gui_utils import ( + add_or_select_notebook_page, + compute_workflow_map_transform, + create_hyperlink, + hyperlink_html_style, + is_protected_notebook_page, +) logger.debug('importing %s ...', '.gui_categorizer') from .gui_categorizer import PanelLv2_GenerateExamples,PanelLv2_TrainCategorizers,PanelLv2_SortBehaviors,PanelLv2_TestCategorizers logger.debug('importing %s done', '.gui_categorizer') from .gui_detector import PanelLv2_GenerateImages,PanelLv2_TrainDetectors,PanelLv2_TestDetectors from .gui_preprocessor import PanelLv2_ProcessVideos,PanelLv2_DrawMarkers -from .gui_analyzer import PanelLv2_AnalyzeBehaviors,PanelLv2_MineResults,PanelLv2_PlotBehaviors,PanelLv2_CalculateDistances +from .gui_analyzer import PanelLv2_AnalyzeBehaviors,PanelLv2_MineResults,PanelLv2_PlotBehaviors,PanelLv2_CalculateDistances, PanelLv2_StateTransitionMap from LabGym import selftest @@ -70,12 +77,11 @@ def display_window(self): boxsizer.Add(self.text_developers,0,wx.LEFT|wx.RIGHT|wx.EXPAND,5) boxsizer.Add(0,60,0) - links=wx.BoxSizer(wx.HORIZONTAL) - homepage=hl.HyperLinkCtrl(panel,0,'Home Page',URL='https://github.com/umyelab/LabGym') - userguide=hl.HyperLinkCtrl(panel,0,'Extended Guide',URL='https://github.com/yujiahu415/LabGym/blob/master/LabGym_extended_user_guide.pdf') - links.Add(homepage,0,wx.LEFT|wx.EXPAND,10) - links.Add(userguide,0,wx.LEFT|wx.RIGHT|wx.EXPAND,10) - boxsizer.Add(links,0,wx.ALIGN_CENTER,50) + homepage=create_hyperlink(panel,'Home Page','https://www.labgym.org') + boxsizer.Add(homepage,0,wx.ALIGN_CENTER,50) + boxsizer.Add(0,14,0) + resources=create_hyperlink(panel,'Resources','https://www.labgym.org/resources') + boxsizer.Add(resources,0,wx.ALIGN_CENTER,50) boxsizer.Add(0,50,0) module_modules=wx.BoxSizer(wx.HORIZONTAL) @@ -179,7 +185,6 @@ def __init__(self, parent): self.notebook = parent self.display_window() - def display_window(self): panel = self @@ -192,7 +197,7 @@ def display_window(self): boxsizer.Add(button_generateimages,0,wx.ALIGN_CENTER,10) boxsizer.Add(0,5,0) - link_annotate=wx.lib.agw.hyperlink.HyperLinkCtrl(panel,0,'\nAnnotate images with EZannot\n',URL='https://github.com/yujiahu415/EZannot') + link_annotate=create_hyperlink(panel,'\nAnnotate images with EZannot\n','https://github.com/yujiahu415/EZannot') boxsizer.Add(link_annotate,0,wx.ALIGN_CENTER,10) boxsizer.Add(0,5,0) @@ -237,57 +242,42 @@ def display_window(self): self.Centre() self.Show(True) - def generate_images(self,event): """Open the Generate Image Examples panel.""" - title = 'Generate Image Examples' add_or_select_notebook_page(self.notebook, lambda: PanelLv2_GenerateImages(self.notebook), title) - def train_detectors(self,event): """Open the Train Detectors panel.""" - title = 'Train Detectors' add_or_select_notebook_page(self.notebook, lambda: PanelLv2_TrainDetectors(self.notebook), title) - def test_detectors(self,event): """Open the Test Detectors panel.""" - title = 'Test Detectors' add_or_select_notebook_page(self.notebook, lambda: PanelLv2_TestDetectors(self.notebook), title) - def generate_behaviorexamples(self,event): """Open the Generate Behavior Examples panel.""" - title = 'Generate Behavior Examples' add_or_select_notebook_page(self.notebook, lambda: PanelLv2_GenerateExamples(self.notebook), title) - def sort_behaviorexamples(self,event): """Open the Sort Behavior Examples panel.""" - title = 'Sort Behavior Examples' add_or_select_notebook_page(self.notebook, lambda: PanelLv2_SortBehaviors(self.notebook), title) - def train_categorizers(self,event): """Open the Train Categorizers panel.""" - title = 'Train Categorizers' add_or_select_notebook_page(self.notebook, lambda: PanelLv2_TrainCategorizers(self.notebook), title) - def test_categorizers(self,event): """Open the Test Categorizers panel.""" - title = 'Test Categorizers' add_or_select_notebook_page(self.notebook, lambda: PanelLv2_TestCategorizers(self.notebook), title) - class PanelLv1_AnalysisModule(wx.Panel): """The Analysis Module.""" @@ -322,6 +312,18 @@ def display_window(self): boxsizer.Add(button_rasterplot,0,wx.ALIGN_CENTER,10) boxsizer.Add(0,20,0) + button_statetransition=wx.Button(panel,label='State Transition Map',size=(300,40)) + button_statetransition.Bind(wx.EVT_BUTTON,self.state_transition_map) + wx.Button.SetToolTip( + button_statetransition, + 'Generate one State Transition Map per animal from a LabGym all_events.xlsx file. ' + 'Results go to state_transition_map under your chosen folder (updated on regenerate). ' + 'Nodes show time occupancy; edges show bout-level transition probabilities. ' + 'Excluded behaviors remove nodes and break sequences rather than bridging transitions.' + ) + boxsizer.Add(button_statetransition,0,wx.ALIGN_CENTER,10) + boxsizer.Add(0,20,0) + button_calculatedistances=wx.Button(panel,label='Calculate Distances',size=(300,40)) button_calculatedistances.Bind(wx.EVT_BUTTON,self.calculate_distances) wx.Button.SetToolTip(button_calculatedistances,'Using LabGym analysis results to calculate: 1. The shortest distances among the locations where animals perform the selected behaviors for the first time, in chronological order. 2. The total traveling distances of the actual route the animals.') @@ -361,20 +363,582 @@ def calculate_distances(self,event): title = 'Calculate Distances' add_or_select_notebook_page(self.notebook, lambda: PanelLv2_CalculateDistances(self.notebook), title) + def state_transition_map(self,event): + """Open the State Transition Map panel.""" + + title = 'State Transition Map' + add_or_select_notebook_page( + self.notebook, + lambda: PanelLv2_StateTransitionMap(self.notebook), + title + ) + +# Popup content for each clickable workflow-map box: (section_title, box_title, description, guide_sections) +_BOX_POPUP = { + 'collect_footage': ( + 'Video Prep', + 'Collect Footage', + 'This is the video collection stage. Before LabGym can track animals or classify behaviors, you need videos that clearly capture the animals and the behaviors of interest. Good video quality, appropriate lighting, and consistent recording conditions will make downstream tracking and classification much more accurate.', + 'Part 2, Part 3.5', + ), + 'preprocessing': ( + 'Video Prep', + 'Preprocessing (Optional)', + 'This step involves modifying videos before analysis if needed. Examples include cropping, trimming, stabilizing recordings, adjusting contrast, or adding spatial markers. LabGym also includes tools that can help prepare videos for later analysis.', + 'Part 4.5, Part 4.6, Section l', + ), + 'tracking': ( + 'Tracking', + 'Tracking / Animal Detection', + 'This is where LabGym finds and follows animals across video frames. Every animal receives an identity and location over time, creating the movement information needed for behavior classification later. LabGym can use either background subtraction or a trained detector depending on video complexity.', + 'Part 3.1, Part 4.1, Section ll', + ), + 'bg_sub': ( + 'Tracking', + 'Background Subtraction', + 'For videos with stable lighting and a fixed background, LabGym automatically estimates the background and removes it. This leaves only the moving animal(s), making tracking faster and more reliable.', + 'Part 3.1, Part 4.1, Section lll A', + ), + 'detector': ( + 'Tracking', + 'Detector', + 'When backgrounds are complicated, lighting changes, or animals frequently overlap, LabGym can use a trained object detector instead of simple background subtraction. The detector learns what the target animal looks like and identifies it directly in each frame.', + 'Part 3.1, Part 4.1, Section ll', + ), + 'generate_images': ( + 'Tracking', + 'Generate Images', + "LabGym extracts representative frames from your videos that will be used to train a detector. These images become the dataset that you'll later annotate with animal locations.", + 'Section ll A', + ), + 'roboflow': ( + 'Tracking', + 'Roboflow OR EZannot', + 'These tools are used to annotate the generated images. You draw boxes around animals and label them so the detector can learn what the target animal looks like.', + 'Section ll B', + ), + 'train_detector': ( + 'Tracking', + 'Train Detector', + 'LabGym uses the annotated images to train an object detection model. The resulting detector can then automatically locate animals in new videos.', + 'Section ll C, Section ll D', + ), + 'generate_examples': ( + 'Classification', + 'Generate and Sort Behavior Examples', + 'LabGym tracks animals and automatically generates behavior examples. Each example contains both an animation and a "pattern image" that summarizes the animal\'s movement through time. Users then sort these examples into behavior categories such as grooming, rearing, or locomotion.', + 'Section lll A, Section lll B', + ), + 'train_categorizer': ( + 'Classification', + 'Train Categorizer', + 'The categorized behavior examples are used to train LabGym\'s "Categorizer," the deep-learning model that identifies behaviors. It learns from both the raw animations and the movement-pattern images.', + 'Section lll C', + ), + 'test_categorizer': ( + 'Classification', + 'Test Categorizer', + 'After training, LabGym evaluates how accurately the categorizer identifies behaviors it has not seen before. This helps determine whether more training examples are needed.', + 'Part 4.3, Section lll D', + ), + 'analyze_behaviors': ( + 'Classification', + 'Analyze Behaviors', + 'The trained categorizer is applied to experimental videos. LabGym classifies behaviors frame-by-frame and records when each behavior occurs. It also generates quantitative measurements such as duration, frequency, and movement metrics.', + 'Part 4.4, Section lV', + ), + 'mine_results': ( + 'Post Classification Analysis', + 'Mine Results', + 'LabGym exports spreadsheets and structured behavioral data that can be explored statistically. Users can compare groups, quantify treatment effects, or examine temporal patterns in behavior.', + 'Section lV B', + ), + 'generate_plot': ( + 'Post Classification Analysis', + 'Generate Behavior Plot', + 'LabGym can visualize behavior occurrence over time using raster plots and other summaries. These plots help users quickly identify patterns, transitions, and temporal organization of behaviors.', + 'Section lV C', + ), + 'calc_distances': ( + 'Post Classification Analysis', + 'Calculate Distances', + 'Using tracking information, LabGym computes movement-based measurements such as distance traveled, speed, and location-related metrics. These can be analyzed alongside behavior classifications.', + 'Part 4.4, Section lV', + ), +} + +# Practical-guide page numbers keyed by reference text (lowercase for case-insensitive lookup) +_GUIDE_PAGES = { + 'part 2': 4, + 'part 3.1': 5, + 'part 3.5': 6, + 'part 4.1': 7, + 'part 4.3': 8, + 'part 4.4': 8, + 'part 4.5': 9, + 'part 4.6': 9, + 'section l': 14, + 'section ll': 16, + 'section ll a': 16, + 'section ll b': 18, + 'section ll c': 21, + 'section ll d': 23, + # Section III A → practical guide page 28 (user-confirmed for Background Subtraction). + 'section lll a': 28, + 'section lll b': 31, + 'section lll c': 33, + 'section lll d': 37, + 'section lv': 38, + 'section lv b': 44, + 'section lv c': 44, +} + + +def resolve_guide_page_number(ref: str): + """Return practical-guide page number for a map popup guide token, or None.""" + if not ref: + return None + return _GUIDE_PAGES.get(ref.strip().lower()) + + +class BoxInfoPopup(wx.Frame): + """Info popup shown when clicking a workflow-map box. Closes on focus loss.""" + + def __init__(self, parent, section, title, description, guide, fill, ink): + super().__init__(None, style=wx.FRAME_NO_TASKBAR | wx.STAY_ON_TOP | wx.NO_BORDER) + self.SetBackgroundColour(ink) # ink peeks through as the border + + # Blend fill 50% toward white for a softer popup background + pf = wx.Colour( + fill.Red() + (255 - fill.Red()) // 2, + fill.Green() + (255 - fill.Green()) // 2, + fill.Blue() + (255 - fill.Blue()) // 2, + ) + + panel = wx.Panel(self) + panel.SetBackgroundColour(pf) + + html_win = wx.html.HtmlWindow(panel, size=(440, 100), style=wx.html.HW_NO_SELECTION) + html_win.SetBackgroundColour(pf) + html_win.SetBorders(0) + html_win.SetPage(self._make_html(section, title, description, guide, pf)) + html_win.Bind(wx.html.EVT_HTML_LINK_CLICKED, self._on_link) + + content_h = html_win.GetInternalRepresentation().GetHeight() + html_win.SetMinSize((440, content_h + 4)) + + inner = wx.BoxSizer(wx.VERTICAL) + inner.Add(html_win, 0, wx.ALL, 20) + panel.SetSizer(inner) + panel.Fit() + + outer = wx.BoxSizer(wx.VERTICAL) + outer.Add(panel, 1, wx.ALL | wx.EXPAND, 3) # 3px gap exposes ink-coloured frame background as border + self.SetSizer(outer) + self.Fit() + + frame = wx.GetTopLevelParent(parent) + fx, fy = frame.GetPosition() + fw, fh = frame.GetSize() + pw, ph = self.GetSize() + self.SetPosition((fx + (fw - pw) // 2, fy + (fh - ph) // 2)) + + self._ready = False + self.Bind(wx.EVT_ACTIVATE, self._on_activate) + wx.CallLater(150, self._set_ready) + + def _set_ready(self): + self._ready = True + + def _on_activate(self, evt): + if self._ready and not evt.GetActive(): + wx.CallAfter(self.Close) + evt.Skip() + + def _on_link(self, evt): + webbrowser.open(evt.GetLinkInfo().GetHref()) + + def _make_html(self, section, title, description, guide, fill): + import html as _h + bg = '#{:02X}{:02X}{:02X}'.format(fill.Red(), fill.Green(), fill.Blue()) + # Section-tinted cards stay light; pin dark body text for contrast under + # OS dark mode (HtmlWindow may otherwise inherit a light default). + text = select_for_appearance('#000000', '#111111') + # Shared cyan link family: normal == visited; hover slightly brighter. + link_c, vlink_c, hover_c = hyperlink_html_style() + base = 'https://www.labgym.org/guides/practical-guide#page-' + refs = [] + for ref in (r.strip() for r in guide.split(',')): + page = resolve_guide_page_number(ref) + refs.append( + '{}'.format(base, page, _h.escape(ref)) if page + else _h.escape(ref) + ) + guide_html = ', '.join(refs) + # body link/vlink + CSS cover both classic HtmlWindow and engines that + # honor style rules; visited never becomes purple. + return ( + '' + '' + '
' + '{section}
{title}
' + '

' + '{desc}' + '

' + 'Learn more in the following LabGym Practical Guide sections: {guide}' + '
' + '' + ).format( + bg=bg, + text=text, + link=link_c, + vlink=vlink_c, + hover=hover_c, + section=_h.escape(section), + title=_h.escape(title), + desc=_h.escape(description, quote=False), + guide=guide_html, + ) + + +def _system_colour(index, fallback): + """Return a wx.SystemSettings colour, or fallback if unavailable.""" + try: + colour = wx.SystemSettings.GetColour(index) + if colour and colour.IsOk(): + return colour + except Exception: + pass + return fallback + + +def _workflow_map_surface_colours(): + """Native canvas / text colours for the Workflow Map (not connector greys). + + Canvas and free-canvas text follow the system window colour pair. Connector + styles are resolved separately so greys can be tuned for hierarchy. + """ + window_bg = _system_colour(wx.SYS_COLOUR_WINDOW, wx.WHITE) + window_fg = _system_colour(wx.SYS_COLOUR_WINDOWTEXT, wx.BLACK) + # Light: retain a light canvas (prefer system window, else white). + # Dark: native/system window background (near-native dark surface). + canvas_bg = select_for_appearance(window_bg, window_bg) + # Titles and free-canvas labels follow system window text for contrast. + text_fg = select_for_appearance(window_fg, window_fg) + return canvas_bg, text_fg + + +def _workflow_map_connector_styles(): + """Appearance-aware connector colours for the Workflow Map. + + Between-phase greys are the most prominent neutrals; within-phase greys are + clearly visible but slightly less strong. Explicit greys (not grey-text / + button system roles) so connectors do not disappear against the canvas. + """ + # Between-phase: strongest neutrals — medium–dark on light; light on dark. + between_color = select_for_appearance( + wx.Colour(80, 80, 80), + wx.Colour(205, 205, 205), + ) + # Within-phase: secondary neutrals — medium on light; slightly dimmer light grey on dark. + within_color = select_for_appearance( + wx.Colour(120, 120, 120), + wx.Colour(168, 168, 168), + ) + return between_color, within_color + + +class WorkflowMapPanel(wx.Panel): + """Displays the LabGym workflow map scaled to the panel client size. + + The main frame remains fixed at ``MainFrame.FIXED_FRAME_SIZE``. Logical layout + coordinates are fixed; scale and centering are recomputed each paint from + the actual client size so hit rectangles stay aligned with drawn boxes. + """ + + # Logical (virtual) coordinate space — source of truth for layout. + VW = 2200 + VH = 660 + # Fallback client size when GetClientSize is temporarily invalid (startup). + _FALLBACK_CLIENT_W = 1100 + _FALLBACK_CLIENT_H = 560 + + # Connector geometry (logical units → client pixels via ps()). + # Between-phase: filled polygonal chevrons (most prominent neutrals). + BETWEEN_SHAFT_HALF = 9 # half-height of the thick shaft + BETWEEN_HEAD_HALF = 17 # arrowhead half-width + BETWEEN_NECK = 26 # distance from tip to neck + BETWEEN_OUTLINE_W = 2 # outline pen (logical; scaled with floor) + # Within-phase: stroke arrows (vertical / diagonal), secondary weight. + WITHIN_LINE_W = 4 # shaft thickness (logical; becomes ≥2 px) + WITHIN_HEAD_HALF = 6 # arrowhead half-width + WITHIN_HEAD_LEN = 11 # arrowhead length along shaft + + def __init__(self, parent): + super().__init__(parent) + self._clickable_boxes = [] # list of (bx, by, bw, bh, fill, ink, popup_data) in client pixels + self._apply_surface_colours() + self.Bind(wx.EVT_PAINT, self.on_paint) + self.Bind(wx.EVT_LEFT_DOWN, self._on_box_click) + # Refresh this map only when the OS appearance/system colours change. + if hasattr(wx, 'EVT_SYS_COLOUR_CHANGED'): + self.Bind(wx.EVT_SYS_COLOUR_CHANGED, self._on_sys_colour_changed) + # Some platforms update appearance on reactivation rather than colour-change. + frame = wx.GetTopLevelParent(self) + if frame is not None: + frame.Bind(wx.EVT_ACTIVATE, self._on_parent_activate) + + def _map_transform(self): + """Return (client_w, client_h, scale, ox, oy) from the current client size. + + Tiny or invalid dimensions fall back to a nominal canvas so drawing and + hit tests remain well-defined during early layout passes. + """ + try: + cw, ch = self.GetClientSize() + except Exception: + cw, ch = 0, 0 + return compute_workflow_map_transform( + cw, ch, vw=self.VW, vh=self.VH, + fallback_w=self._FALLBACK_CLIENT_W, fallback_h=self._FALLBACK_CLIENT_H, + ) + + def _apply_surface_colours(self): + """Set the panel background from the current native appearance.""" + canvas_bg, _ = _workflow_map_surface_colours() + self.SetBackgroundColour(canvas_bg) + + def _on_sys_colour_changed(self, event): + self._apply_surface_colours() + self.Refresh() + event.Skip() + + def _on_parent_activate(self, event): + if event.GetActive(): + self._apply_surface_colours() + self.Refresh() + event.Skip() + + def on_paint(self, event): + canvas_bg, text_fg = _workflow_map_surface_colours() + between_color, within_color = _workflow_map_connector_styles() + self.SetBackgroundColour(canvas_bg) + dc = wx.PaintDC(self) + dc.SetBackground(wx.Brush(canvas_bg)) + dc.Clear() + self._draw(dc, text_fg, between_color, within_color) + + def _draw(self, dc, text_fg, between_color, within_color): + import math # needed for diagonal arrow angle calculations + self._clickable_boxes = [] # reset so hit-test rects match this paint + W, _H, scale, ox, oy = self._map_transform() + + def px(v): return int(ox + v * scale) # logical x → client pixel + def py(v): return int(oy + v * scale) # logical y → client pixel + def ps(v): return max(1, int(v * scale))# logical size/thickness → pixels (minimum 1) + + # Centralized connector metrics (client pixels). Floors keep hierarchy at scale 0.5. + between_outline_w = max(1, ps(self.BETWEEN_OUTLINE_W)) + between_sh = max(5, ps(self.BETWEEN_SHAFT_HALF)) + between_hw = max(10, ps(self.BETWEEN_HEAD_HALF)) + between_neck = max(14, ps(self.BETWEEN_NECK)) + within_line_w = max(2, ps(self.WITHIN_LINE_W)) + within_ah = max(3, ps(self.WITHIN_HEAD_HALF)) + within_al = max(5, ps(self.WITHIN_HEAD_LEN)) + + # Section fill and ink (border only) colors — unchanged identity colours + s1_fill = wx.Colour(255, 210, 210) # super light red — section 1 + s1_ink = wx.Colour(160, 55, 55) # darker red — section 1 borders + s2_fill = wx.Colour(210, 228, 255) # super light blue — section 2 + s2_ink = wx.Colour(55, 95, 165) # darker blue — section 2 borders + s3_fill = wx.Colour(255, 228, 195) # super light orange — section 3 + s3_ink = wx.Colour(175, 100, 20) # darker orange — section 3 borders + s4_fill = wx.Colour(235, 215, 255) # light lavender — section 4 + s4_ink = wx.Colour(120, 60, 180) # deeper purple — section 4 borders + + font = wx.Font(max(12, ps(16)), wx.FONTFAMILY_DEFAULT, + wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL) # body text font at fixed map scale + bold_font = wx.Font(max(18, ps(26)), wx.FONTFAMILY_DEFAULT, + wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD) # large bold font for the main title + head_font = wx.Font(max(15, ps(22)), wx.FONTFAMILY_DEFAULT, + wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD) # smaller bold font for section headings + + dc.SetFont(font) + lh = dc.GetCharHeight() # single-line height in pixels + MX = ps(14) # horizontal margin each side in pixels + MY = ps(8) # vertical margin each side in pixels + def hbh(n): return (lh * n + 2 * MY) / 2 / scale # virtual half-box-height for n lines of text + + def draw_box(cx, cy, lines, fill, ink, key=None): + dc.SetFont(font) + # Light pastel fills: keep black labels (already correct contrast). + dc.SetTextForeground(wx.BLACK) + line_widths = [dc.GetTextExtent(l)[0] for l in lines] + box_w = max(line_widths) + 2 * MX + box_h = lh * len(lines) + 2 * MY + bx = px(cx) - box_w // 2 + by = py(cy) - box_h // 2 + dc.SetPen(wx.Pen(ink, ps(1))) + dc.SetBrush(wx.Brush(fill)) + dc.DrawRoundedRectangle(bx, by, box_w, box_h, ps(5)) + ty = by + MY + for i, (line, lw) in enumerate(zip(lines, line_widths)): + dc.DrawText(line, px(cx) - lw // 2, ty + i * lh) + if key is not None: + self._clickable_boxes.append((bx, by, box_w, box_h, fill, ink, _BOX_POPUP[key])) + + def v_arr(x, y1, y2): + """Vertical within-phase connector (downward) using secondary neutral style.""" + dc.SetPen(wx.Pen(within_color, within_line_w)) + dc.SetBrush(wx.Brush(within_color)) + dc.DrawLine(px(x), py(y1), px(x), py(y2)) + dc.DrawPolygon([(px(x), py(y2)), + (px(x)-within_ah, py(y2)-within_al), + (px(x)+within_ah, py(y2)-within_al)]) + + def diag_arr(x1, y1, x2, y2, lines=(), label_dx=0, label_dy=0): + """Diagonal within-phase connector using secondary neutral style.""" + dc.SetPen(wx.Pen(within_color, within_line_w)) + dc.SetBrush(wx.Brush(within_color)) + dc.DrawLine(px(x1), py(y1), px(x2), py(y2)) + dx_v, dy_v = x2 - x1, y2 - y1 + length = math.hypot(dx_v, dy_v) + ux, uy = dx_v / length, dy_v / length + tip_x, tip_y = px(x2), py(y2) + lft_x = int(tip_x - within_al * ux + within_ah * (-uy)) + lft_y = int(tip_y - within_al * uy + within_ah * ux) + rgt_x = int(tip_x - within_al * ux - within_ah * (-uy)) + rgt_y = int(tip_y - within_al * uy - within_ah * ux) + dc.DrawPolygon([(tip_x, tip_y), (lft_x, lft_y), (rgt_x, rgt_y)]) + if lines: + perp_x, perp_y = uy, -ux # 90 degrees left of arrow direction in screen coords + if perp_y > 0: # if that points downward, flip so label is always above the arrow + perp_x, perp_y = -perp_x, -perp_y + offset = ps(80) # pixels to push text away from the shaft + cx_label = px((x1 + x2) / 2) + int(perp_x * offset) + label_dx + cy_label = py((y1 + y2) / 2) + int(perp_y * offset) + label_dy + dc.SetFont(font) + dc.SetTextForeground(text_fg) + lh = dc.GetCharHeight() + top = cy_label - (lh * len(lines)) // 2 + for i, line in enumerate(lines): + lw, _ = dc.GetTextExtent(line) + dc.DrawText(line, cx_label - lw // 2, top + i * lh) + + def big_arr(x1, x2, cy): + """Large between-phase connector (right-pointing) using primary neutral style.""" + neck = px(x2) - between_neck + dc.SetPen(wx.Pen(between_color, between_outline_w)) + dc.SetBrush(wx.Brush(between_color)) + dc.DrawPolygon([ + (px(x1), py(cy) - between_sh), + (neck, py(cy) - between_sh), + (neck, py(cy) - between_hw), + (px(x2), py(cy)), + (neck, py(cy) + between_hw), + (neck, py(cy) + between_sh), + (px(x1), py(cy) + between_sh), + ]) + + + # MAIN TITLE + dc.SetFont(bold_font) + dc.SetTextForeground(text_fg) + tw, _ = dc.GetTextExtent('LabGym Workflow Map') + dc.DrawText('LabGym Workflow Map', (W - tw) // 2, py(65) // 3) + + # SECTION HEADINGS + dc.SetFont(head_font) + dc.SetTextForeground(text_fg) + for label, cx in [('1. Video Prep', 155), ('2. Tracking', 755), ('3. Classification', 1355)]: + tw, _ = dc.GetTextExtent(label) + dc.DrawText(label, px(cx) - tw // 2, py(65)) + lh_head = dc.GetCharHeight() + for i, line in enumerate(['4. Post Classification', 'Analysis']): + tw, _ = dc.GetTextExtent(line) + dc.DrawText(line, px(1955) - tw // 2, py(65) + i * lh_head) + + + # ── Section 1: Video Prep ────────────────────────────────────────────── + v_arr(155, 154 + hbh(2), 259 - hbh(2)) # Collect Footage -> Preprocessing + big_arr(380, 555, 65) # section 1 -> section 2 transition (centred in gap, at subtitle height) + + # ── Section 2: Tracking ─────────────────────────────────────────────── + diag_arr(715, 148 + hbh(2), 540, 280 - hbh(2), ['Static', 'Background'], label_dx=-ps(30), label_dy=ps(38)) # Tracking -> Background Subtraction (steeper angle) + diag_arr(795, 148 + hbh(2), 950, 280 - hbh(1), ['Dynamic', 'Background'], label_dx= ps(30), label_dy=ps(25)) # Tracking -> Detector (steeper angle) + v_arr(950, 280 + hbh(1), 380 - hbh(2)) # Detector -> Generate Images + v_arr(933, 380 + hbh(2), 480 - hbh(2)) # Generate Images -> Roboflow OR EZannot (left fork) + v_arr(967, 380 + hbh(2), 480 - hbh(2)) # Generate Images -> Roboflow OR EZannot (right fork) + v_arr(950, 480 + hbh(2), 580 - hbh(2)) # Roboflow OR EZannot -> Train Detector + big_arr(967, 1142, 65) # section 2 -> section 3 transition (centred in gap, at subtitle height) + + # ── Section 3: Classification ───────────────────────────────────────── + v_arr(1355, 164 + hbh(3), 278 - hbh(2)) # Generate and sort -> Train Categorizer + v_arr(1355, 278 + hbh(2), 378 - hbh(2)) # Train Categorizer -> Test Categorizer + v_arr(1355, 378 + hbh(2), 478 - hbh(2)) # Test Categorizer -> Analyze Behaviors + big_arr(1567, 1742, 65) # section 3 -> section 4 transition (centred in gap, at subtitle height) + + + # BOXES + + # section 1 + draw_box( 155, 154, ['Collect', 'Footage'], s1_fill, s1_ink, 'collect_footage') + draw_box( 155, 259, ['Preprocessing', '(Optional)'], s1_fill, s1_ink, 'preprocessing') + + # section 2 + draw_box( 755, 148, ['Tracking /', 'Animal Detection'], s2_fill, s2_ink, 'tracking') + draw_box( 540, 280, ['Background', 'Subtraction'], s2_fill, s2_ink, 'bg_sub') + draw_box( 950, 280, ['Detector'], s2_fill, s2_ink, 'detector') + draw_box( 950, 380, ['Generate', 'Images'], s2_fill, s2_ink, 'generate_images') + draw_box( 950, 480, ['Roboflow OR', 'EZannot'], s2_fill, s2_ink, 'roboflow') + draw_box( 950, 580, ['Train', 'Detector'], s2_fill, s2_ink, 'train_detector') + + # section 3 + draw_box(1355, 164, ['Generate and', 'Sort Behavior', 'Examples'], s3_fill, s3_ink, 'generate_examples') + draw_box(1355, 278, ['Train', 'Categorizer'], s3_fill, s3_ink, 'train_categorizer') + draw_box(1355, 378, ['Test', 'Categorizer'], s3_fill, s3_ink, 'test_categorizer') + draw_box(1355, 478, ['Analyze', 'Behaviors'], s3_fill, s3_ink, 'analyze_behaviors') + + # section 4 + draw_box(1955, 195, ['Mine', 'Results'], s4_fill, s4_ink, 'mine_results') + draw_box(1955, 295, ['Generate', 'Behavior Plot'], s4_fill, s4_ink, 'generate_plot') + draw_box(1955, 395, ['Calculate', 'Distances'], s4_fill, s4_ink, 'calc_distances') + + def _on_box_click(self, evt): + # Click coords are already in client space; box rects are recorded in the same space during paint. + x, y = evt.GetPosition() + for bx, by, bw, bh, fill, ink, data in self._clickable_boxes: + if bx <= x < bx + bw and by <= y < by + bh: + section, title, desc, guide = data + popup = BoxInfoPopup(self, section, title, desc, guide, fill, ink) + popup.Show() + return + evt.Skip() class MainFrame(wx.Frame): """Main frame and its notebook.""" + # Fixed outer window size — large enough for the full Workflow Map (canvas 1100×560) without scroll. + # Height includes map client + notebook tabs + menubar/chrome (~90px). Not resizable. + FIXED_FRAME_SIZE = (1100, 650) + def __init__(self): - super().__init__(None, title=f'LabGym v{__version__}') + # Disable resize border and maximize so the frame stays at FIXED_FRAME_SIZE. + style = wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX) + super().__init__(None, title=f'LabGym v{__version__}', style=style) - self.SetSize((1000, 600)) + self.SetSize(self.FIXED_FRAME_SIZE) + self.SetMinSize(self.FIXED_FRAME_SIZE) + self.SetMaxSize(self.FIXED_FRAME_SIZE) - # Set the app icon within GUI - set_frame_icon(self, context='normal') # Set normal icon first - if sys.platform.startswith("win"): - set_frame_icon(self, context='small', size=16) # Override with small icon for title bar + # Set the app icon within GUI (unified simplified artwork on all platforms) + set_frame_icon(self) self.init_menubar() @@ -390,12 +954,13 @@ def __init__(self): wx.aui.AuiPaneInfo().CenterPane(), ) - # Add panel as a page to the notebook. - panel = InitialPanel(self.notebook) - title = 'Home' - self.notebook.AddPage(panel, title, select=True) + # Store page objects for navigation/close protection (identity, not index/title). + self.home_page = InitialPanel(self.notebook) + self.notebook.AddPage(self.home_page, 'Home', select=True) + self.workflow_map_page = WorkflowMapPanel(self.notebook) + self.notebook.AddPage(self.workflow_map_page, 'Workflow Map', select=False) - # Bind the close event to prevent Home tab from being closed + # Bind the close event to protect stored Home / Workflow Map pages self.notebook.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.on_page_close) # Use a sizer to ensure the notebook fills the frame. @@ -409,9 +974,14 @@ def __init__(self): self.Show() # display the frame def on_page_close(self, event): - """Handle page close events to prevent Home tab from being closed.""" - # Prevent the Home tab (index 0) from being closed - if event.GetSelection() == 0: + """Veto closing of the stored Home and Workflow Map page objects.""" + selection = event.GetSelection() + try: + page = self.notebook.GetPage(selection) + except Exception: + page = None + if is_protected_notebook_page( + page, (self.home_page, self.workflow_map_page)): event.Veto() else: # Allow other tabs to be closed normally diff --git a/LabGym/gui_preprocessor.py b/LabGym/gui_preprocessor.py index 1a8b7bb5..8c7038a8 100644 --- a/LabGym/gui_preprocessor.py +++ b/LabGym/gui_preprocessor.py @@ -35,6 +35,7 @@ # Local application/library specific imports. from .tools import preprocess_video +from .gui_utils import add_info_button, create_hyperlink, INFO_COLOUR_S1 class PanelLv2_ProcessVideos(wx.Panel): @@ -71,6 +72,7 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S1) module_inputvideos=wx.BoxSizer(wx.HORIZONTAL) button_inputvideos=wx.Button(panel,label='Select the video(s)\nfor preprocessing',size=(300,40)) @@ -140,6 +142,18 @@ def display_window(self): boxsizer.Add(button_preprocessvideos,0,wx.RIGHT|wx.ALIGN_RIGHT,90) boxsizer.Add(0,10,0) + # Match nested 10px module + button margins so the link lines up with the button column. + module_tutorial=wx.BoxSizer(wx.HORIZONTAL) + module_tutorial.Add( + create_hyperlink( + panel, + 'Preprocessing Basics Tutorial Video', + 'https://youtu.be/51F-whqGIzU?si=IYMT3_etdnu46Zh3', + ), + 0, wx.LEFT|wx.RIGHT, 10) + boxsizer.Add(module_tutorial,0,wx.LEFT|wx.RIGHT|wx.EXPAND,10) + boxsizer.Add(0, 10, 0) + panel.SetSizer(boxsizer) self.Centre() @@ -442,6 +456,7 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S1) module_inputvideos=wx.BoxSizer(wx.HORIZONTAL) button_inputvideos=wx.Button(panel,label='Select the video(s)\nfor marker drawing',size=(300,40)) @@ -471,6 +486,18 @@ def display_window(self): boxsizer.Add(button_preprocessvideos,0,wx.RIGHT|wx.ALIGN_RIGHT,90) boxsizer.Add(0,10,0) + # Match nested 10px module + button margins so the link lines up with the button column. + module_tutorial=wx.BoxSizer(wx.HORIZONTAL) + module_tutorial.Add( + create_hyperlink( + panel, + 'Video preprocessing: Draw Markers Tutorial Video', + 'https://youtu.be/8Y9RQUGuPtk?si=3jPVZCddf62o2EUB', + ), + 0, wx.LEFT|wx.RIGHT, 10) + boxsizer.Add(module_tutorial,0,wx.LEFT|wx.RIGHT|wx.EXPAND,10) + boxsizer.Add(0, 10, 0) + panel.SetSizer(boxsizer) self.Centre() diff --git a/LabGym/gui_utils.py b/LabGym/gui_utils.py index d75961cd..e724c183 100644 --- a/LabGym/gui_utils.py +++ b/LabGym/gui_utils.py @@ -21,6 +21,287 @@ This module provides additional utility functions for the LabGym GUI. Currently, it contains a function to add a new page or select existing page if it already exists. ''' +import os + +import wx +import wx.lib.agw.hyperlink as hl +import wx.lib.buttons as wxbuttons + +from .gui_appearance import select_for_appearance + +# Section colour constants — match the workflow-map fill colours +INFO_COLOUR_S1 = wx.Colour(255, 210, 210) # light red — 1. Video Prep +INFO_COLOUR_S2 = wx.Colour(210, 228, 255) # light blue — 2. Tracking +INFO_COLOUR_S3 = wx.Colour(255, 228, 195) # light orange — 3. Classification +INFO_COLOUR_S4 = wx.Colour(235, 215, 255) # light lavender — 4. Post-Classification Analysis +INFO_COLOUR_GREY = wx.Colour(220, 220, 220) # light grey — fallback + +# Shared cyan/teal hyperlink family for all LabGym GUI links (AGW + HTML). +# Normal and visited are identical so AGW and browsers never show purple. +_LINK_LIGHT_NORMAL = wx.Colour(0, 140, 158) # darker cyan/teal on light surfaces +_LINK_DARK_NORMAL = wx.Colour(70, 230, 240) # brighter cyan on dark surfaces +_LINK_LIGHT_ROLLOVER = wx.Colour(0, 175, 195) # lighter cyan (same family) +_LINK_DARK_ROLLOVER = wx.Colour(140, 245, 255) # brighter cyan (same family) + + +def behavior_label_from_filename(filename): + """Return the prepared-example category label matching categorizer training. + + LabGym training takes the final underscore-delimited segment of the stem. + Filenames without an underscore yield None and are ignored by counting. + """ + base = os.path.splitext(os.path.basename(filename))[0] + if '_' not in base: + return None + return base.split('_')[-1] + + +def _list_media_for_counts(entries): + """Prefer AVI listings in a directory; otherwise use JPG listings.""" + avis = [f for f in entries if f.endswith('.avi')] + if avis: + return avis + return [f for f in entries if f.endswith('.jpg')] + + +def _count_prepared_files_in_dir(dir_path): + """Count prepared examples in a single flat directory (no recursion).""" + try: + entries = os.listdir(dir_path) + except OSError: + return {} + counts = {} + for f in _list_media_for_counts(entries): + label = behavior_label_from_filename(f) + if label is None: + continue + counts[label] = counts.get(label, 0) + 1 + return counts + + +def count_prepared_examples(folder_path): + """Count prepared training examples by behavior label. + + Supports: + - flat prepared folders (files directly under folder_path); or + - onfly layout with train/ plus validation/ (or counting-only vadilation/). + + Split mode is used only when train/ and either validation/ or vadilation/ + exist; counts are summed across recognized split directories (not recursive + below those directories). Incomplete split layouts fall back to flat-root scan. + """ + if not folder_path: + return {} + try: + os.listdir(folder_path) + except OSError: + return {} + + train_path = os.path.join(folder_path, 'train') + validation_path = os.path.join(folder_path, 'validation') + vadilation_path = os.path.join(folder_path, 'vadilation') + has_train = os.path.isdir(train_path) + has_validation = os.path.isdir(validation_path) + has_vadilation = os.path.isdir(vadilation_path) + + if has_train and (has_validation or has_vadilation): + counts = {} + for path in (train_path, validation_path, vadilation_path): + if not os.path.isdir(path): + continue + for label, n in _count_prepared_files_in_dir(path).items(): + counts[label] = counts.get(label, 0) + n + return counts + + return _count_prepared_files_in_dir(folder_path) + + +def count_sorted_examples(folder_path): + """Count sorted behavior examples per immediate behavior subfolder name. + + AVI-over-JPG precedence applies independently within each subfolder. + Empty behavior subfolders are included with count 0. + """ + if not folder_path: + return {} + try: + names = os.listdir(folder_path) + except OSError: + return {} + counts = {} + for name in names: + path = os.path.join(folder_path, name) + if not os.path.isdir(path): + continue + try: + entries = os.listdir(path) + except OSError: + counts[name] = 0 + continue + counts[name] = len(_list_media_for_counts(entries)) + return counts + + +def counts_enable_diagnostics(counts): + """True when at least one category has one or more counted examples.""" + return any(n > 0 for n in counts.values()) if counts else False + + +def compute_workflow_map_transform( + client_w, client_h, vw=2200, vh=660, + fallback_w=1100, fallback_h=560): + """Compute (client_w, client_h, scale, ox, oy) for the Workflow Map layout. + + Tiny or invalid client dimensions fall back to nominal sizes so drawing and + hit tests remain well-defined during early layout passes. + """ + try: + cw, ch = int(client_w), int(client_h) + except Exception: + cw, ch = 0, 0 + if cw < 1 or ch < 1: + cw, ch = fallback_w, fallback_h + scale = min(cw / vw, ch / vh) + if scale <= 0: + scale = min(fallback_w / vw, fallback_h / vh) + ox = (cw - vw * scale) / 2 + oy = (ch - vh * scale) / 2 + return cw, ch, scale, ox, oy + + +def _colour_to_hex(colour) -> str: + """Format a wx.Colour as #RRGGBB for HTML/CSS.""" + return '#{:02X}{:02X}{:02X}'.format(colour.Red(), colour.Green(), colour.Blue()) + + +def hyperlink_colours(): + """Return (normal, visited, rollover) wx.Colour for the current appearance. + + Visited is always identical to normal. + """ + normal = select_for_appearance(_LINK_LIGHT_NORMAL, _LINK_DARK_NORMAL) + rollover = select_for_appearance(_LINK_LIGHT_ROLLOVER, _LINK_DARK_ROLLOVER) + return normal, normal, rollover + + +def hyperlink_html_style(): + """Return (link_hex, visited_hex, hover_hex) for HTML anchors. + + Uses the same cyan family as AGW HyperLinkCtrl. Visited matches normal. + """ + normal, visited, rollover = hyperlink_colours() + return ( + _colour_to_hex(normal), + _colour_to_hex(visited), + _colour_to_hex(rollover), + ) + + +def style_hyperlink(link): + """Apply the shared cyan appearance-aware style to an AGW HyperLinkCtrl. + + Sets normal/visited/rollover colours, enables rollover, refreshes the link, + and binds a light restyle when the OS system colours change (if supported). + Preserves URL and browser-opening behaviour. + """ + if link is None: + return link + + def _apply(_event=None): + try: + if not link: # destroyed + return + normal, visited, rollover = hyperlink_colours() + link.SetColours(link=normal, visited=visited, rollover=rollover) + link.EnableRollover(True) + try: + # Keep internal visited flag from forcing a purple brand; colours already match. + link.SetVisited(False) + except Exception: + pass + link.UpdateLink(True) + except RuntimeError: + # Window may already be destroyed. + pass + + _apply() + + if not getattr(link, '_labgym_hyperlink_styled', False): + link._labgym_hyperlink_styled = True + if hasattr(wx, 'EVT_SYS_COLOUR_CHANGED'): + link.Bind(wx.EVT_SYS_COLOUR_CHANGED, lambda evt: (_apply(), evt.Skip())) + # Some platforms update appearance on reactivation. + frame = wx.GetTopLevelParent(link) + if frame is not None: + def _on_activate(evt): + if evt.GetActive(): + _apply() + evt.Skip() + frame.Bind(wx.EVT_ACTIVATE, _on_activate) + + return link + + +def create_hyperlink(parent, label, url): + """Create an AGW HyperLinkCtrl with LabGym's shared cyan link style.""" + link = hl.HyperLinkCtrl(parent, -1, label, URL=url) + return style_hyperlink(link) + + +# Backwards-compatible alias for earlier tutorial-only helper name. +create_tutorial_hyperlink = create_hyperlink + + +def select_notebook_page(notebook, page) -> bool: + """Select a notebook page by stored page-object identity (not index or title). + + Returns True if the page was found and selected. + """ + if notebook is None or page is None: + return False + for i in range(notebook.GetPageCount()): + if notebook.GetPage(i) is page: + notebook.SetSelection(i) + return True + return False + + +def is_protected_notebook_page(page, protected_pages) -> bool: + """Return True when page is one of the protected main-frame page objects.""" + if page is None: + return False + for protected in protected_pages: + if protected is not None and page is protected: + return True + return False + + +def add_info_button(panel, boxsizer, colour): + """Insert a coloured 'i' button at the top-right of a panel's vertical sizer. + + Clicking the button selects the main frame's stored Workflow Map page object + (``frame.workflow_map_page``) regardless of its notebook index or displayed title. + Use one of INFO_COLOUR_S1/S2/S3/GREY as the colour argument. + """ + bar = wx.BoxSizer(wx.HORIZONTAL) + bar.AddStretchSpacer() + btn = wxbuttons.GenButton(panel, label='i', size=(28, 28)) + btn.SetBackgroundColour(colour) + btn.SetForegroundColour(wx.Colour(60, 60, 60)) + btn.SetFont(wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)) + btn.SetToolTip('View Workflow Map') + bar.Add(btn, 0, wx.RIGHT | wx.TOP, 6) + boxsizer.Add(bar, 0, wx.EXPAND) + + def _go_to_workflow(evt): + frame = wx.GetTopLevelParent(panel) + notebook = getattr(frame, 'notebook', None) + workflow_page = getattr(frame, 'workflow_map_page', None) + select_notebook_page(notebook, workflow_page) + + btn.Bind(wx.EVT_BUTTON, _go_to_workflow) + + def add_or_select_notebook_page(notebook, panel_factory, title): """Helper function to add a new page or select existing page if it already exists. diff --git a/LabGym/mylogging.py b/LabGym/mylogging.py index ce17dd2b..792949a7 100644 --- a/LabGym/mylogging.py +++ b/LabGym/mylogging.py @@ -112,7 +112,10 @@ # tomllib is included in the Python Standard Library since version 3.11 import tomllib # type: ignore except ModuleNotFoundError: - import tomli as tomllib # A lil' TOML parser + try: + import tomli as tomllib # A lil' TOML parser + except ModuleNotFoundError: + tomllib = None from typing import Dict, List # Related third party imports. @@ -185,6 +188,8 @@ def _mydebug(myobj: str | Exception) -> logging.LogRecord: def get_configdict_from_configfile(configfile: Path) -> Dict: """Read the configfile and return the config dictionary.""" if configfile.name.endswith('.toml'): + if tomllib is None: + raise ModuleNotFoundError("TOML support requires Python >= 3.11 or the 'tomli' package. Please install it with: pip install tomli") with open(configfile, 'rb') as f: result = tomllib.load(f) elif configfile.name.endswith('.yaml'): diff --git a/LabGym/pkghash/lookup.py b/LabGym/pkghash/lookup.py index fbb80329..16b36853 100644 --- a/LabGym/pkghash/lookup.py +++ b/LabGym/pkghash/lookup.py @@ -34,7 +34,10 @@ # tomllib is included in the Python Standard Library since version 3.11 import tomllib # type: ignore except ModuleNotFoundError: - import tomli as tomllib # A lil' TOML parser + try: + import tomli as tomllib # A lil' TOML parser + except ModuleNotFoundError: + tomllib = None # Local application/library specific imports. from .hash import get_hashval diff --git a/LabGym/prob_matrix.py b/LabGym/prob_matrix.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/LabGym/prob_matrix.py @@ -0,0 +1 @@ + diff --git a/LabGym/probes.py b/LabGym/probes.py index 7ff92f83..e5814b1b 100644 --- a/LabGym/probes.py +++ b/LabGym/probes.py @@ -156,7 +156,7 @@ def probe_url_to_verify_cacert() -> None: try: # requests.get(url) returns response = requests.get(url, timeout=8) - except requests.exceptions.SSLError as e: + except requests.exceptions.RequestException as e: logger.debug('%s: %r', 'certifi.where()', certifi.where()) # sys.exit(f'(fatal) Trouble in SSL cert chain... ({e})') diff --git a/LabGym/tests/pytest.ini b/LabGym/tests/pytest.ini index 385a3fef..13aa2a3d 100644 --- a/LabGym/tests/pytest.ini +++ b/LabGym/tests/pytest.ini @@ -1,7 +1,2 @@ # pytest.ini [pytest] -# Avoid two coverage warnings from detectron2's import of cv2. -# (see Notes.opencv-python-and-coverage-warnings.txt) -filterwarnings = - ignore:Couldn't parse .*/config-3.py:coverage.exceptions.CoverageWarning - ignore:Couldn't parse .*/config.py:coverage.exceptions.CoverageWarning diff --git a/LabGym/tests/test_behavior_counts.py b/LabGym/tests/test_behavior_counts.py new file mode 100644 index 00000000..c0f73764 --- /dev/null +++ b/LabGym/tests/test_behavior_counts.py @@ -0,0 +1,117 @@ +"""AF regression: prepared/sorted behavior-count helpers (no live GUI).""" + +import os +from pathlib import Path + +from LabGym import mywx # patch wx.App before any import of wx / gui_utils +from LabGym.gui_utils import ( + behavior_label_from_filename, + count_prepared_examples, + count_sorted_examples, + counts_enable_diagnostics, +) + + +def _touch(path: Path): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b'') + + +def test_behavior_label_final_underscore_segment(): + assert behavior_label_from_filename('0_grooming.avi') == 'grooming' + assert behavior_label_from_filename('0_approach_partner.jpg') == 'partner' + assert behavior_label_from_filename('nounderscore.jpg') is None + assert behavior_label_from_filename('plain.jpg') is None + + +def test_flat_avi_examples(tmp_path): + _touch(tmp_path / '0_grooming.avi') + _touch(tmp_path / '1_rearing.avi') + _touch(tmp_path / '2_grooming.avi') + assert count_prepared_examples(str(tmp_path)) == { + 'grooming': 2, + 'rearing': 1, + } + + +def test_filenames_without_underscore_ignored(tmp_path): + _touch(tmp_path / 'orphan.avi') + _touch(tmp_path / '1_valid.avi') + assert count_prepared_examples(str(tmp_path)) == {'valid': 1} + + +def test_avi_over_jpg_no_double_count(tmp_path): + _touch(tmp_path / '0_grooming.avi') + _touch(tmp_path / '0_grooming.jpg') + _touch(tmp_path / '1_grooming.jpg') + # Any AVI present in the directory: count only AVI, not JPG. + assert count_prepared_examples(str(tmp_path)) == {'grooming': 1} + + +def test_jpg_only_when_no_avi(tmp_path): + _touch(tmp_path / '0_grooming.jpg') + _touch(tmp_path / '1_rearing.jpg') + assert count_prepared_examples(str(tmp_path)) == { + 'grooming': 1, + 'rearing': 1, + } + + +def test_train_validation_aggregation(tmp_path): + _touch(tmp_path / 'train' / '0_a.avi') + _touch(tmp_path / 'train' / '1_b.avi') + _touch(tmp_path / 'validation' / '2_a.avi') + _touch(tmp_path / 'validation' / '3_c.avi') + assert count_prepared_examples(str(tmp_path)) == {'a': 2, 'b': 1, 'c': 1} + + +def test_train_vadilation_compatibility(tmp_path): + _touch(tmp_path / 'train' / '0_x.avi') + _touch(tmp_path / 'vadilation' / '1_x.avi') + _touch(tmp_path / 'vadilation' / '2_y.avi') + assert count_prepared_examples(str(tmp_path)) == {'x': 2, 'y': 1} + + +def test_incomplete_split_falls_back_to_flat_root(tmp_path): + # train/ only — not split mode; flat-root scan ignores nested files. + _touch(tmp_path / 'train' / '0_hidden.avi') + _touch(tmp_path / '0_root.avi') + assert count_prepared_examples(str(tmp_path)) == {'root': 1} + + +def test_empty_and_unreadable(tmp_path): + assert count_prepared_examples(str(tmp_path)) == {} + assert count_prepared_examples(str(tmp_path / 'missing')) == {} + assert count_prepared_examples('') == {} + assert counts_enable_diagnostics({}) is False + + +def test_one_populated_category_enables_diagnostics(tmp_path): + _touch(tmp_path / '0_only.avi') + counts = count_prepared_examples(str(tmp_path)) + assert counts == {'only': 1} + assert counts_enable_diagnostics(counts) is True + + +def test_sorted_multiple_folders_and_empty_zero(tmp_path): + _touch(tmp_path / 'grooming' / 'a.avi') + _touch(tmp_path / 'grooming' / 'b.avi') + _touch(tmp_path / 'rearing' / 'c.jpg') + (tmp_path / 'empty_behavior').mkdir() + counts = count_sorted_examples(str(tmp_path)) + assert counts == {'grooming': 2, 'rearing': 1, 'empty_behavior': 0} + assert counts_enable_diagnostics(counts) is True + + +def test_sorted_per_folder_avi_jpg_precedence(tmp_path): + _touch(tmp_path / 'mixed' / '0.avi') + _touch(tmp_path / 'mixed' / '0.jpg') + _touch(tmp_path / 'mixed' / '1.jpg') + _touch(tmp_path / 'jpg_only' / 'x.jpg') + counts = count_sorted_examples(str(tmp_path)) + assert counts['mixed'] == 1 # avis only + assert counts['jpg_only'] == 1 + + +def test_sorted_unreadable_root(tmp_path): + assert count_sorted_examples(str(tmp_path / 'nope')) == {} diff --git a/LabGym/tests/test_categorizer_class_mismatch.py b/LabGym/tests/test_categorizer_class_mismatch.py new file mode 100644 index 00000000..e6e62c26 --- /dev/null +++ b/LabGym/tests/test_categorizer_class_mismatch.py @@ -0,0 +1,85 @@ +"""Categorizer class-mismatch contract.""" + +from unittest.mock import patch + +import pandas as pd +import pytest + +from LabGym import mywx # noqa: F401 +import wx + +from LabGym.categorizer import CategorizerClassMismatchError, Categorizers + + +@pytest.fixture(scope='module') +def wx_app(): + app = wx.App(False) + yield app + wx.CallAfter(app.ExitMainLoop) + app.MainLoop() + del app + wx.App._instance = None + + +def test_mismatch_error_lists_are_sorted_and_message_is_explicit(): + err = CategorizerClassMismatchError(['b_extra', 'a_extra'], ['missing_z', 'missing_a']) + assert err.unrecognized_folders == ['a_extra', 'b_extra'] + assert err.missing_classes == ['missing_a', 'missing_z'] + text = str(err) + assert 'exactly match' in text + assert 'a_extra' in text + assert 'missing_a' in text + + +def test_test_categorizer_raises_before_model_load_on_mismatch(tmp_path): + ground = tmp_path / 'gt' + (ground / 'walk').mkdir(parents=True) + (ground / 'extra').mkdir(parents=True) + model = tmp_path / 'model' + model.mkdir(parents=True) + pd.DataFrame( + { + 'network': [0, None], + 'time_step': [15, None], + 'inner_code': [1, None], + 'background_free': [0, None], + 'dim_conv': [8, None], + 'level_conv': [1, None], + 'channel': [1, None], + 'classnames': ['walk', 'run'], + } + ).to_csv(model / 'model_parameters.txt', index=False) + + ca = Categorizers() + with patch('LabGym.categorizer.load_model') as load_model: + with pytest.raises(CategorizerClassMismatchError) as caught: + ca.test_categorizer(str(ground), str(model), result_path=str(tmp_path / 'out')) + load_model.assert_not_called() + assert 'extra' in caught.value.unrecognized_folders + assert 'run' in caught.value.missing_classes + + +def test_gui_mismatch_handler_does_not_unpack_none(wx_app): + from LabGym.gui_categorizer import PanelLv2_TestCategorizers + + with patch.object(PanelLv2_TestCategorizers, 'display_window', lambda self: None): + with patch('LabGym.gui_categorizer.config.get_config', return_value={'models': '/tmp'}): + frame = wx.Frame(None) + panel = PanelLv2_TestCategorizers(frame) + panel.file_path = '/tmp/gt' + panel.path_to_categorizer = '/tmp/model' + panel.out_path = None + panel.checkbox_open_interactive = wx.CheckBox(frame) + panel.checkbox_open_interactive.SetValue(True) + + err = CategorizerClassMismatchError(['extra'], ['missing']) + with patch('LabGym.gui_categorizer.Categorizers') as CA: + CA.return_value.test_categorizer.side_effect = err + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + panel.test_categorizer(None) + mb.assert_called_once() + args, kwargs = mb.call_args + assert args[1] == 'Class name mismatch' + assert 'Unrecognized behavior folders' in args[0] + assert 'Model classes absent' in args[0] + frame.Destroy() diff --git a/LabGym/tests/test_diagnostics_cm_colors.py b/LabGym/tests/test_diagnostics_cm_colors.py new file mode 100644 index 00000000..517bebb4 --- /dev/null +++ b/LabGym/tests/test_diagnostics_cm_colors.py @@ -0,0 +1,177 @@ +"""Matrix correct-cell color endpoint and CM width refresh.""" + +import inspect +from unittest.mock import patch + +import pytest + +from LabGym import mywx # noqa: F401 # must precede wx-dependent LabGym imports +import wx + +from LabGym.gui_categorizer import ( + CM_CORRECT_RGB_MAX, + CM_CORRECT_RGB_MIN, + AutomatedDiagnosticsDialog, + cm_correct_cell_rgb, +) + + +def _srgb_channel_to_linear(c): + c = c / 255.0 + if c <= 0.04045: + return c / 12.92 + return ((c + 0.055) / 1.055) ** 2.4 + + +def relative_luminance(rgb): + r, g, b = rgb + return ( + 0.2126 * _srgb_channel_to_linear(r) + + 0.7152 * _srgb_channel_to_linear(g) + + 0.0722 * _srgb_channel_to_linear(b) + ) + + +def contrast_ratio(fg_rgb, bg_rgb): + l1 = relative_luminance(fg_rgb) + l2 = relative_luminance(bg_rgb) + lighter = max(l1, l2) + darker = min(l1, l2) + return (lighter + 0.05) / (darker + 0.05) + + +def test_cm_correct_max_endpoint_is_approved_green(): + assert CM_CORRECT_RGB_MAX == (46, 125, 50) + assert cm_correct_cell_rgb(1.0) == (46, 125, 50) + + +def test_cm_correct_min_endpoint_is_darker(): + lo = cm_correct_cell_rgb(0.0) + hi = cm_correct_cell_rgb(1.0) + assert lo == CM_CORRECT_RGB_MIN + assert sum(lo) < sum(hi) + + +def test_cm_correct_scale_is_monotonic_in_green(): + prev_g = -1 + for step in range(0, 11): + r, g, b = cm_correct_cell_rgb(step / 10) + assert g >= prev_g + prev_g = g + assert 0 <= r <= 255 and 0 <= g <= 255 and 0 <= b <= 255 + + +def test_white_text_contrast_at_max_green(): + """Approved max green must meet WCAG AA contrast for white text (>= 4.5:1).""" + rgb = cm_correct_cell_rgb(1.0) + assert rgb == (46, 125, 50) + ratio = contrast_ratio((255, 255, 255), rgb) + assert ratio >= 4.5 + assert abs(ratio - 5.13) < 0.05 + + +@pytest.fixture(scope='module') +def wx_app(): + app = wx.App(False) + yield app + wx.CallAfter(app.ExitMainLoop) + app.MainLoop() + del app + wx.App._instance = None + + +def _padded_100_pct_min_width(grid): + font = grid.GetDefaultCellFont() + text_w, _h, _d, _el = grid.GetFullTextExtent('100.0%', font) + return text_w + 16 + + +def _make_diagnostics_dialog(wx_app, classnames, cm): + parent = wx.Frame(None) + report = { + name: { + 'support': sum(cm[i]), + 'precision': 0.5, + 'recall': 0.5, + 'f1-score': 0.5, + } + for i, name in enumerate(classnames) + } + report['accuracy'] = 0.5 + report['macro avg'] = {'f1-score': 0.5, 'precision': 0.5, 'recall': 0.5} + report['weighted avg'] = {'f1-score': 0.5, 'precision': 0.5, 'recall': 0.5} + with patch.object(AutomatedDiagnosticsDialog, 'Maximize'): + dlg = AutomatedDiagnosticsDialog( + parent, + report, + cm, + classnames, + {}, + {}, + None, + ) + return parent, dlg + + +def test_diagnostics_cm_raw_first_toggle_refreshes_column_widths(wx_app): + # 198/250 == 79.2%; short labels exercise the padded floor. + classnames = ['idle', 'a', 'walk'] + cm = [ + [198, 52, 0], + [0, 10, 0], + [0, 0, 10], + ] + parent, dlg = _make_diagnostics_dialog(wx_app, classnames, cm) + try: + assert dlg.is_normalized is False + assert dlg.toggle_btn.GetLabel() == 'Show Normalized (%)' + assert dlg.cm_grid.GetCellValue(0, 0) == '198' + helper_src = inspect.getsource(AutomatedDiagnosticsDialog.refresh_cm_column_widths) + assert 'idle' not in helper_src + + refresh_calls = [] + original_refresh = dlg.refresh_cm_column_widths + + def tracking_refresh(): + refresh_calls.append(True) + return original_refresh() + + dlg.refresh_cm_column_widths = tracking_refresh + + dlg.toggle_btn.SetValue(True) + dlg.on_toggle_cm(None) + + assert dlg.is_normalized is True + assert dlg.toggle_btn.GetLabel() == 'Show Raw Counts' + assert dlg.cm_grid.GetCellValue(0, 0) == '79.2%' + assert dlg.cm_grid.GetCellValue(1, 1) == '100.0%' + assert len(refresh_calls) >= 1 + + min_w = _padded_100_pct_min_width(dlg.cm_grid) + for col in range(dlg.cm_grid.GetNumberCols()): + assert dlg.cm_grid.GetColSize(col) >= min_w + + # Generic short label (not idle) still meets the floor after refresh. + idle_w = dlg.cm_grid.GetColSize(0) + short_w = dlg.cm_grid.GetColSize(1) + assert short_w >= min_w + assert idle_w >= min_w + finally: + dlg.Destroy() + parent.Destroy() + + +def test_diagnostics_cm_column_width_helper_is_label_agnostic(wx_app): + classnames = ['z', 'yy'] + cm = [[5, 0], [0, 5]] + parent, dlg = _make_diagnostics_dialog(wx_app, classnames, cm) + try: + dlg.is_normalized = True + dlg.update_grid_data() + assert dlg.cm_grid.GetCellValue(0, 0) == '100.0%' + min_w = _padded_100_pct_min_width(dlg.cm_grid) + for col in range(dlg.cm_grid.GetNumberCols()): + assert dlg.cm_grid.GetColSize(col) >= min_w + finally: + dlg.Destroy() + parent.Destroy() diff --git a/LabGym/tests/test_diagnostics_copy_and_training_layout.py b/LabGym/tests/test_diagnostics_copy_and_training_layout.py new file mode 100644 index 00000000..0612bd6d --- /dev/null +++ b/LabGym/tests/test_diagnostics_copy_and_training_layout.py @@ -0,0 +1,151 @@ +"""Training Module single-column structure and diagnostic copy contracts.""" + +from pathlib import Path + +from LabGym import mywx # noqa: F401 + +from LabGym.gui_categorizer import ( + DIAGNOSTIC_BUTTON_LABELS, + collect_insufficient_support_entries, + insufficient_support_threshold, +) + + +APPROVED_ORDER = ( + 'Generate Image Examples', + 'Annotate images with EZannot', + 'Train Detectors', + 'Test Detectors', + 'Generate Behavior Examples', + 'Sort Behavior Examples', + 'Train Categorizers', + 'Test Categorizers', +) + + +def test_training_module_source_has_single_column_bindings(): + src = Path(__file__).resolve().parents[2] / 'LabGym' / 'gui_main.py' + text = src.read_text(encoding='utf-8') + start = text.index('class PanelLv1_TrainingModule') + end = text.index('class PanelLv1_AnalysisModule') + body = text[start:end] + assert 'ACTION_LABELS' not in body + assert 'Detector Pipeline' not in body + assert 'Categorizer Pipeline' not in body + assert 'divider_line' not in body + assert 'columns_sizer' not in body + for label in APPROVED_ORDER: + if label.startswith('Annotate'): + assert 'Annotate images with EZannot' in body + else: + assert f"label='{label}'" in body + for handler in ( + 'generate_images', + 'train_detectors', + 'test_detectors', + 'generate_behaviorexamples', + 'sort_behaviorexamples', + 'train_categorizers', + 'test_categorizers', + ): + assert f'self.{handler}' in body + + +def test_diagnostic_labels_have_no_emoji_and_overview_first(): + assert DIAGNOSTIC_BUTTON_LABELS[0] == 'Overview' + assert DIAGNOSTIC_BUTTON_LABELS == ( + 'Overview', + 'Major Confusions', + 'Minor Confusions', + 'Successes', + 'Build Triage Plan', + ) + joined = ' '.join(DIAGNOSTIC_BUTTON_LABELS) + for ch in ('🔴', '🟡', '🟢', '🔵', '📝', '⚠️', '⚠'): + assert ch not in joined + + +def test_diagnostic_button_construction_uses_label_constant(): + src = Path(__file__).resolve().parents[2] / 'LabGym' / 'gui_categorizer.py' + text = src.read_text(encoding='utf-8') + start = text.index('def init_ui(self):') + # Limit to AutomatedDiagnosticsDialog.init_ui (first init_ui after that class). + class_start = text.index('class AutomatedDiagnosticsDialog') + start = text.index('def init_ui(self):', class_start) + end = text.index('\tdef update_grid_data', start) + body = text[start:end] + assert 'DIAGNOSTIC_BUTTON_LABELS' in body + assert 'label="Overview"' not in body + assert 'label="🔴' not in body + + +def test_diagnostic_copy_rejects_overconfident_phrases_and_uses_new_low_support(): + src = Path(__file__).resolve().parents[2] / 'LabGym' / 'gui_categorizer.py' + text = src.read_text(encoding='utf-8') + banned = ( + 'Model looks great!', + 'Statistically Meaningless', + 'successfully and consistently', + 'Everything looks great!', + 'Keep Tuning!', + 'Diagnosis:', + 'Insufficient sample support for automated interpretation', + '⚠️', + ) + for phrase in banned: + assert phrase not in text, phrase + assert 'Too few examples for automated analysis' in text + assert ": {mc['support']} examples; " in text + assert "at least {mc['min_support']} required" in text + assert '(fewer than 100 examples)' in text + assert 'Possible pattern (advisory)' in text + assert 'H1 — Merge hypothesis (advisory)' in text + assert 'LabGym does not create the new class or move examples' in text + assert 'revised_sorted_test_examples' in text + assert 'H3_Variance_References' in text + assert 'Hypothesis 1: Merge on revised sorted test examples (advisory)' in text + assert 'Package layout and remediation' in text + assert 'select revised_sorted_test_examples, not the package root' in text + assert 'do not copy evaluation examples into training' in text + assert 'Triage Plan: You are reviewing confusion patterns' in text + assert 'Build Triage Plan' in text + assert 'scientific decisions remain yours' in text + assert 'Open interactive results when testing finishes' not in text + assert 'Show interactive results after testing' in text + assert 'Triage_Action_Plan.pdf' not in text + assert 'dataset_v2' not in text + assert 'next_versioned_pdf_path' in text + assert 'next_versioned_triage_package_name' in text + assert 'sanitize_triage_package_base' in text + assert 'validate_triage_package_name' in text + assert 'collect_h1_filename_collisions' in text + assert 'fit_dialog_client_size' in text + assert 'NOMINAL_CLIENT_SIZE = (960, 720)' in text + assert 'wx.RESIZE_BORDER' not in text.split('class TriageBuilderDialog')[1].split('def move_items')[0] + assert 'ops_help_html' in text + assert 'self.intro_lbl' in text + assert '→' in text + assert '≥' in text + assert 'Paragraph(f"• ' in text + assert 'LabGym Triage Action Plan' in text + assert 'source_dataset_root' in text + + +def test_zero_and_positive_low_support_entries(): + report = { + 'absent': {'support': 0, 'f1-score': 0.0}, + 'sparse': {'support': 5, 'f1-score': 0.2}, + 'enough': {'support': 100, 'f1-score': 0.5}, + } + classnames = ['absent', 'sparse', 'enough'] + # total support = 105; threshold = max(20, 1.05) = 20 + assert insufficient_support_threshold(105) == 20 + entries = collect_insufficient_support_entries(classnames, report) + by_class = {e['class']: e for e in entries} + assert 'absent' in by_class + assert by_class['absent']['support'] == 0 + assert by_class['absent']['min_support'] == 20 + assert 'sparse' in by_class + assert by_class['sparse']['support'] == 5 + assert by_class['sparse']['min_support'] == 20 + assert 'enough' not in by_class diff --git a/LabGym/tests/test_gui_appearance.py b/LabGym/tests/test_gui_appearance.py new file mode 100644 index 00000000..7e5395ba --- /dev/null +++ b/LabGym/tests/test_gui_appearance.py @@ -0,0 +1,120 @@ +"""Unit tests for LabGym.gui_appearance (no GUI window required).""" + +from types import SimpleNamespace +from unittest.mock import MagicMock + +from LabGym import mywx # patch wx.App before any import of wx +import wx + +from LabGym import gui_appearance + + +class _FakeColour: + """Minimal stand-in for wx.Colour with Red/Green/Blue accessors.""" + + def __init__(self, r, g, b): + self._r, self._g, self._b = r, g, b + + def Red(self): + return self._r + + def Green(self): + return self._g + + def Blue(self): + return self._b + + +def test_is_dark_appearance_true_when_IsDark(monkeypatch): + appearance = MagicMock() + appearance.IsDark.return_value = True + monkeypatch.setattr(wx.SystemSettings, 'GetAppearance', lambda: appearance) + + assert gui_appearance.is_dark_appearance() is True + appearance.IsDark.assert_called_once() + appearance.IsUsingDarkBackground.assert_not_called() + + +def test_is_dark_appearance_false_when_IsDark(monkeypatch): + appearance = MagicMock() + appearance.IsDark.return_value = False + monkeypatch.setattr(wx.SystemSettings, 'GetAppearance', lambda: appearance) + + assert gui_appearance.is_dark_appearance() is False + appearance.IsDark.assert_called_once() + + +def test_is_dark_appearance_falls_back_to_IsUsingDarkBackground(monkeypatch): + """Prefer IsDark; when absent, use IsUsingDarkBackground.""" + appearance = SimpleNamespace() + # No IsDark attribute. + appearance.IsUsingDarkBackground = MagicMock(return_value=True) + monkeypatch.setattr(wx.SystemSettings, 'GetAppearance', lambda: appearance) + + assert gui_appearance.is_dark_appearance() is True + appearance.IsUsingDarkBackground.assert_called_once() + + +def test_is_dark_appearance_falls_back_to_luminance_when_no_appearance_api( + monkeypatch): + """Without GetAppearance, compare system window colours.""" + if hasattr(wx.SystemSettings, 'GetAppearance'): + monkeypatch.delattr(wx.SystemSettings, 'GetAppearance') + + def fake_get_colour(index): + if index == wx.SYS_COLOUR_WINDOW: + return _FakeColour(30, 30, 30) # dark bg + if index == wx.SYS_COLOUR_WINDOWTEXT: + return _FakeColour(220, 220, 220) # light text + return _FakeColour(128, 128, 128) + + monkeypatch.setattr(wx.SystemSettings, 'GetColour', fake_get_colour) + + assert gui_appearance.is_dark_appearance() is True + + +def test_is_dark_appearance_luminance_light(monkeypatch): + if hasattr(wx.SystemSettings, 'GetAppearance'): + monkeypatch.delattr(wx.SystemSettings, 'GetAppearance') + + def fake_get_colour(index): + if index == wx.SYS_COLOUR_WINDOW: + return _FakeColour(255, 255, 255) + if index == wx.SYS_COLOUR_WINDOWTEXT: + return _FakeColour(0, 0, 0) + return _FakeColour(128, 128, 128) + + monkeypatch.setattr(wx.SystemSettings, 'GetColour', fake_get_colour) + + assert gui_appearance.is_dark_appearance() is False + + +def test_is_dark_appearance_IsDark_exception_then_IsUsingDarkBackground( + monkeypatch): + appearance = MagicMock() + appearance.IsDark.side_effect = RuntimeError('unavailable') + appearance.IsUsingDarkBackground.return_value = False + monkeypatch.setattr(wx.SystemSettings, 'GetAppearance', lambda: appearance) + + assert gui_appearance.is_dark_appearance() is False + appearance.IsUsingDarkBackground.assert_called_once() + + +def test_select_for_appearance_dark(monkeypatch): + monkeypatch.setattr(gui_appearance, 'is_dark_appearance', lambda: True) + assert gui_appearance.select_for_appearance('light', 'dark') == 'dark' + + +def test_select_for_appearance_light(monkeypatch): + monkeypatch.setattr(gui_appearance, 'is_dark_appearance', lambda: False) + assert gui_appearance.select_for_appearance('light', 'dark') == 'light' + + +def test_select_for_appearance_with_colours(monkeypatch): + light = _FakeColour(255, 255, 255) + dark = _FakeColour(20, 20, 20) + monkeypatch.setattr(gui_appearance, 'is_dark_appearance', lambda: True) + assert gui_appearance.select_for_appearance(light, dark) is dark + + monkeypatch.setattr(gui_appearance, 'is_dark_appearance', lambda: False) + assert gui_appearance.select_for_appearance(light, dark) is light diff --git a/LabGym/tests/test_guide_mapping.py b/LabGym/tests/test_guide_mapping.py new file mode 100644 index 00000000..28cb7d5d --- /dev/null +++ b/LabGym/tests/test_guide_mapping.py @@ -0,0 +1,74 @@ +"""AF regression: Workflow Map popup guide tokens resolve to page numbers. + +Isolated from gui_main import (and its heavy panel/selftest dependencies) by +reading the module source and evaluating only the guide table assignments. +""" + +import ast +from pathlib import Path + + +def _gui_main_source_path() -> Path: + # LabGym/tests/this_file.py -> LabGym/gui_main.py + return Path(__file__).resolve().parent.parent / 'gui_main.py' + + +def _literal_assign(tree: ast.AST, name: str): + """Return the literal value of a top-level assignment ``name = ``.""" + for node in tree.body: + if not isinstance(node, ast.Assign): + continue + for target in node.targets: + if isinstance(target, ast.Name) and target.id == name: + return ast.literal_eval(node.value) + raise AssertionError('Assignment {!r} not found in gui_main.py'.format(name)) + + +def _load_guide_tables(): + source = _gui_main_source_path().read_text(encoding='utf-8') + tree = ast.parse(source, filename=str(_gui_main_source_path())) + box_popup = _literal_assign(tree, '_BOX_POPUP') + guide_pages = _literal_assign(tree, '_GUIDE_PAGES') + return box_popup, guide_pages + + +def _resolve_guide_page_number(guide_pages, ref: str): + if not ref: + return None + return guide_pages.get(ref.strip().lower()) + + +def _iter_box_popup_guide_refs(box_popup): + for key, data in box_popup.items(): + guide = data[3] + for ref in guide.split(','): + ref = ref.strip() + if ref: + yield key, ref + + +def _practical_guide_url(page_number: int) -> str: + return 'https://www.labgym.org/guides/practical-guide#page-{}'.format(page_number) + + +def test_every_intentional_popup_guide_token_resolves(): + box_popup, guide_pages = _load_guide_tables() + unresolved = [] + for box_key, ref in _iter_box_popup_guide_refs(box_popup): + page = _resolve_guide_page_number(guide_pages, ref) + if page is None: + unresolved.append((box_key, ref)) + assert unresolved == [], 'Unresolved guide tokens: {}'.format(unresolved) + + +def test_background_subtraction_section_lll_a_is_page_28(): + box_popup, guide_pages = _load_guide_tables() + guide = box_popup['bg_sub'][3] + tokens = [r.strip() for r in guide.split(',')] + assert 'Part 3.1' in tokens + assert 'Part 4.1' in tokens + assert 'Section lll A' in tokens + assert _resolve_guide_page_number(guide_pages, 'Section lll A') == 28 + assert _practical_guide_url(28) == ( + 'https://www.labgym.org/guides/practical-guide#page-28' + ) diff --git a/LabGym/tests/test_interactive_results_checkbox.py b/LabGym/tests/test_interactive_results_checkbox.py new file mode 100644 index 00000000..caf33289 --- /dev/null +++ b/LabGym/tests/test_interactive_results_checkbox.py @@ -0,0 +1,144 @@ +"""Interactive-results checkbox on Test Categorizers.""" + +from unittest.mock import patch + +import pytest + +from LabGym import mywx # noqa: F401 +import wx + + +@pytest.fixture(scope='module') +def wx_app(): + app = wx.App(False) + yield app + wx.CallAfter(app.ExitMainLoop) + app.MainLoop() + del app + wx.App._instance = None + + +def _make_test_panel(wx_app, display=True): + from LabGym.gui_categorizer import PanelLv2_TestCategorizers + + frame = wx.Frame(None) + if display: + with patch('LabGym.gui_categorizer.config.get_config', return_value={'models': '/tmp'}): + panel = PanelLv2_TestCategorizers(frame) + else: + with patch.object(PanelLv2_TestCategorizers, 'display_window', lambda self: None): + with patch('LabGym.gui_categorizer.config.get_config', return_value={'models': '/tmp'}): + panel = PanelLv2_TestCategorizers(frame) + panel.checkbox_open_interactive = wx.CheckBox( + frame, + label='Show interactive results after testing', + ) + panel.checkbox_open_interactive.SetValue(True) + return frame, panel + + +def test_checkbox_exists_with_exact_label_and_defaults_checked(wx_app): + frame, panel = _make_test_panel(wx_app, display=True) + assert panel.checkbox_open_interactive.GetLabel() == ( + 'Show interactive results after testing' + ) + assert panel.checkbox_open_interactive.GetValue() is True + frame.Destroy() + + +def test_checked_path_opens_diagnostics_dialog(wx_app): + frame, panel = _make_test_panel(wx_app, display=False) + panel.file_path = '/tmp/gt' + panel.path_to_categorizer = '/tmp/model' + panel.out_path = None + panel.checkbox_open_interactive.SetValue(True) + + fake_report = { + 'walk': {'support': 10, 'f1-score': 0.9}, + 'accuracy': 0.9, + 'macro avg': {}, + 'weighted avg': {}, + } + with patch('LabGym.gui_categorizer.Categorizers') as CA: + CA.return_value.test_categorizer.return_value = ( + fake_report, + [[1]], + {}, + {}, + ) + with patch('LabGym.gui_categorizer.AutomatedDiagnosticsDialog') as Dialog: + instance = Dialog.return_value + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + panel.test_categorizer(None) + Dialog.assert_called_once() + instance.ShowModal.assert_called_once() + instance.Destroy.assert_called_once() + mb.assert_not_called() + frame.Destroy() + + +def test_unchecked_path_skips_dialog_and_passes_export_path(wx_app): + frame, panel = _make_test_panel(wx_app, display=False) + panel.file_path = '/tmp/gt' + panel.path_to_categorizer = '/tmp/model' + panel.out_path = '/tmp/export' + panel.checkbox_open_interactive.SetValue(False) + + fake_report = { + 'walk': {'support': 10, 'f1-score': 0.9}, + 'accuracy': 0.9, + 'macro avg': {}, + 'weighted avg': {}, + } + with patch('LabGym.gui_categorizer.Categorizers') as CA: + CA.return_value.test_categorizer.return_value = ( + fake_report, + [[1]], + {}, + {}, + ) + with patch('LabGym.gui_categorizer.AutomatedDiagnosticsDialog') as Dialog: + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + panel.test_categorizer(None) + CA.return_value.test_categorizer.assert_called_once_with( + '/tmp/gt', + '/tmp/model', + result_path='/tmp/export', + ) + Dialog.assert_not_called() + mb.assert_not_called() + assert panel.checkbox_open_interactive.GetValue() is False + frame.Destroy() + + +def test_unchecked_without_export_passes_none_result_path(wx_app): + frame, panel = _make_test_panel(wx_app, display=False) + panel.file_path = '/tmp/gt' + panel.path_to_categorizer = '/tmp/model' + panel.out_path = None + panel.checkbox_open_interactive.SetValue(False) + + fake_report = { + 'walk': {'support': 10, 'f1-score': 0.9}, + 'accuracy': 0.9, + 'macro avg': {}, + 'weighted avg': {}, + } + with patch('LabGym.gui_categorizer.Categorizers') as CA: + CA.return_value.test_categorizer.return_value = ( + fake_report, + [[1]], + {}, + {}, + ) + with patch('LabGym.gui_categorizer.AutomatedDiagnosticsDialog') as Dialog: + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + panel.test_categorizer(None) + CA.return_value.test_categorizer.assert_called_once_with( + '/tmp/gt', + '/tmp/model', + result_path=None, + ) + Dialog.assert_not_called() + mb.assert_not_called() + frame.Destroy() diff --git a/LabGym/tests/test_notebook_page_identity.py b/LabGym/tests/test_notebook_page_identity.py new file mode 100644 index 00000000..409b06fe --- /dev/null +++ b/LabGym/tests/test_notebook_page_identity.py @@ -0,0 +1,117 @@ +"""AF regression: notebook page selection and close protection by object identity.""" + +from LabGym import mywx # patch wx.App before any import of wx / gui_utils +from LabGym.gui_utils import is_protected_notebook_page, select_notebook_page + + +class _StubNotebook: + """Minimal notebook stand-in with reordering support (no live wx session).""" + + def __init__(self): + self._pages = [] + self._titles = [] + self.selection = None + + def AddPage(self, page, title, select=False): + self._pages.append(page) + self._titles.append(title) + if select or self.selection is None: + self.selection = len(self._pages) - 1 + + def GetPageCount(self): + return len(self._pages) + + def GetPage(self, index): + return self._pages[index] + + def GetPageText(self, index): + return self._titles[index] + + def SetPageText(self, index, title): + self._titles[index] = title + + def SetSelection(self, index): + self.selection = index + + def InsertPage(self, index, page, title, select=False): + self._pages.insert(index, page) + self._titles.insert(index, title) + if select: + self.selection = index + elif self.selection is not None and self.selection >= index: + self.selection += 1 + + def MovePage(self, old_index, new_index): + page = self._pages.pop(old_index) + title = self._titles.pop(old_index) + self._pages.insert(new_index, page) + self._titles.insert(new_index, title) + + +def test_select_workflow_map_after_unrelated_tabs_inserted_or_reordered(): + home = object() + workflow = object() + other = object() + nb = _StubNotebook() + nb.AddPage(home, 'Home', select=True) + nb.AddPage(workflow, 'Workflow Map') + nb.InsertPage(0, other, 'Other Tab') + assert nb.GetPage(0) is other + assert select_notebook_page(nb, workflow) is True + assert nb.GetPage(nb.selection) is workflow + + nb.MovePage(nb.selection, 0) + assert nb.GetPage(0) is workflow + extra = object() + nb.AddPage(extra, 'Extra') + assert select_notebook_page(nb, workflow) is True + assert nb.GetPage(nb.selection) is workflow + + +def test_home_and_workflow_protected_after_reordering(): + home = object() + workflow = object() + other = object() + nb = _StubNotebook() + nb.AddPage(home, 'Home') + nb.AddPage(workflow, 'Workflow Map') + nb.AddPage(other, 'Analysis') + nb.MovePage(0, 2) # home no longer at index 0 + protected = (home, workflow) + + for i in range(nb.GetPageCount()): + page = nb.GetPage(i) + should_protect = page is home or page is workflow + assert is_protected_notebook_page(page, protected) is should_protect + + +def test_other_pages_not_protected(): + home = object() + workflow = object() + other = object() + assert is_protected_notebook_page(other, (home, workflow)) is False + assert is_protected_notebook_page(None, (home, workflow)) is False + + +def test_title_change_does_not_break_object_identity(): + home = object() + workflow = object() + nb = _StubNotebook() + nb.AddPage(home, 'Home') + nb.AddPage(workflow, 'Workflow Map') + nb.SetPageText(0, 'Renamed Home') + nb.SetPageText(1, 'Renamed Map') + assert select_notebook_page(nb, home) is True + assert nb.GetPage(nb.selection) is home + assert select_notebook_page(nb, workflow) is True + assert nb.GetPage(nb.selection) is workflow + assert is_protected_notebook_page(home, (home, workflow)) + assert is_protected_notebook_page(workflow, (home, workflow)) + + +def test_select_missing_page_returns_false(): + nb = _StubNotebook() + nb.AddPage(object(), 'Home') + assert select_notebook_page(nb, object()) is False + assert select_notebook_page(None, object()) is False + assert select_notebook_page(nb, None) is False diff --git a/LabGym/tests/test_probability_heatmap.py b/LabGym/tests/test_probability_heatmap.py new file mode 100644 index 00000000..0675eea5 --- /dev/null +++ b/LabGym/tests/test_probability_heatmap.py @@ -0,0 +1,251 @@ +"""Probability heat-map missing-value masking and linear 0–1 scale.""" + +import os + +import matplotlib +matplotlib.use('Agg') + +from matplotlib.axes import Axes +from matplotlib.colors import LogNorm, Normalize, to_rgba +import matplotlib.pyplot as plt +import numpy as np +import pytest + +from LabGym.analyzebehavior import ( + PROBABILITY_HEATMAP_MISSING_COLOR, + PROBABILITY_HEATMAP_MISSING_LEGEND, + AnalyzeAnimal, + prepare_probability_heatmap_array, + probability_heatmap_colormap, + probability_heatmap_norm, +) +from LabGym.analyzebehavior_dt import AnalyzeAnimalDetector + + +def _capture_imshow(monkeypatch): + captured = {} + real_imshow = Axes.imshow + + def wrapper(self, X, *args, **kwargs): + captured['X'] = X + captured['kwargs'] = kwargs + captured['self'] = self + return real_imshow(self, X, *args, **kwargs) + + monkeypatch.setattr(Axes, 'imshow', wrapper) + return captured + + +def _non_detector_analyzer(tmp_path, walk_probs, sit_probs, times=None): + times = list(range(len(walk_probs))) if times is None else times + animal = AnalyzeAnimal() + animal.results_path = str(tmp_path) + animal.all_time = times + animal.event_probability = {0: None} + animal.all_behavior_parameters = { + 'walk': {'probability': {0: walk_probs}}, + 'sit': {'probability': {0: sit_probs}}, + } + return animal + + +def _detector_analyzer(tmp_path, walk_probs, sit_probs, times=None): + times = list(range(len(walk_probs))) if times is None else times + animal = AnalyzeAnimalDetector() + animal.results_path = str(tmp_path) + animal.all_time = times + animal.event_probability = {'mouse': {0: None}} + animal.all_behavior_parameters = { + 'mouse': { + 'walk': {'probability': {0: walk_probs}}, + 'sit': {'probability': {0: sit_probs}}, + } + } + return animal + + +def _assert_fixed_linear_norm(norm): + assert isinstance(norm, Normalize) + assert not isinstance(norm, LogNorm) + assert float(norm.vmin) == pytest.approx(0.0) + assert float(norm.vmax) == pytest.approx(1.0) + + +def test_nan_and_nonfinite_are_masked_not_converted_to_zero(): + raw = np.array([[np.nan, np.inf, -np.inf, 0.2]], dtype=np.float64) + prepared = prepare_probability_heatmap_array(raw) + assert np.ma.is_masked(prepared) + assert prepared.mask[0, 0] + assert prepared.mask[0, 1] + assert prepared.mask[0, 2] + assert not prepared.mask[0, 3] + assert prepared[0, 3] == pytest.approx(0.2) + np.testing.assert_array_equal(raw, [[np.nan, np.inf, -np.inf, 0.2]]) + + +def test_zero_is_valid_plotted_data_not_raised_or_masked(): + raw = np.array([[0.0, 0.001, 1.5, -0.1]], dtype=np.float64) + prepared = prepare_probability_heatmap_array(raw) + assert not np.any(prepared.mask) + assert prepared[0, 0] == pytest.approx(0.0) + assert prepared[0, 1] == pytest.approx(0.001) + assert prepared[0, 2] == pytest.approx(1.0) + assert prepared[0, 3] == pytest.approx(0.0) + + +def test_linear_norm_maps_zero_and_intermediates_proportionally(): + norm = probability_heatmap_norm() + _assert_fixed_linear_norm(norm) + raw = np.array([[0.0, 0.01, 0.5, 1.0]], dtype=np.float64) + prepared = prepare_probability_heatmap_array(raw) + for value in prepared.compressed(): + assert float(norm(value)) == pytest.approx(float(value)) + assert float(norm(0.0)) == pytest.approx(0.0) + assert float(norm(0.01)) == pytest.approx(0.01) + assert float(norm(0.5)) == pytest.approx(0.5) + assert float(norm(1.0)) == pytest.approx(1.0) + + +def test_colormap_bad_is_gray_and_does_not_mutate_global(): + inferno = plt.get_cmap('inferno') + before = inferno.get_bad().copy() + cmap = probability_heatmap_colormap() + after = inferno.get_bad() + np.testing.assert_array_equal(before, after) + expected_bad = np.array(to_rgba(PROBABILITY_HEATMAP_MISSING_COLOR)) + np.testing.assert_allclose(cmap.get_bad(), expected_bad) + assert PROBABILITY_HEATMAP_MISSING_COLOR == 'gray' + + +def _assert_plotted_linear_missing_and_zero(captured): + plotted = captured['X'] + assert np.ma.is_masked(plotted) + # After transpose: behaviors x frames. walk is row 0. + assert plotted.mask[0, 1] + assert not plotted.mask[0, 0] + assert plotted[0, 0] == pytest.approx(0.0) + assert not plotted.mask[0, 2] + assert plotted[0, 2] == pytest.approx(0.001) + assert not plotted.mask[1, 0] + assert plotted[1, 0] == pytest.approx(0.2) + _assert_fixed_linear_norm(captured['kwargs']['norm']) + cmap = captured['kwargs']['cmap'] + expected_bad = np.array(to_rgba(PROBABILITY_HEATMAP_MISSING_COLOR)) + np.testing.assert_allclose(cmap.get_bad(), expected_bad) + legend_labels = [t.get_text() for t in captured['self'].get_legend().get_texts()] + assert PROBABILITY_HEATMAP_MISSING_LEGEND in legend_labels + cbar = captured['self'].images[0].colorbar + assert 'log' not in cbar.ax.get_ylabel().lower() + assert 'Probability' in cbar.ax.get_ylabel() + + +def test_non_detector_heatmap_uses_fixed_linear_norm(tmp_path, monkeypatch): + captured = _capture_imshow(monkeypatch) + animal = _non_detector_analyzer( + tmp_path, + walk_probs=[0.0, np.nan, 0.001], + sit_probs=[0.2, 0.8, 1.0], + times=[0.0, 0.1, 0.2], + ) + animal.export_probability_matrices(make_heatmap=True) + _assert_plotted_linear_missing_and_zero(captured) + + +def test_detector_heatmap_follows_same_linear_and_missing_rules(tmp_path, monkeypatch): + captured = _capture_imshow(monkeypatch) + animal = _detector_analyzer( + tmp_path, + walk_probs=[0.0, np.nan, 0.001], + sit_probs=[0.2, 0.8, 1.0], + times=[0.0, 0.1, 0.2], + ) + animal.export_probability_matrices_dt(make_heatmap=True) + _assert_plotted_linear_missing_and_zero(captured) + + +def test_detector_and_non_detector_share_the_same_fixed_limits(tmp_path, monkeypatch): + captured_nd = _capture_imshow(monkeypatch) + nd = _non_detector_analyzer( + tmp_path / 'nd', + walk_probs=[0.01, 0.5, 1.0], + sit_probs=[0.0, 0.2, 0.9], + times=[0.0, 0.1, 0.2], + ) + (tmp_path / 'nd').mkdir() + nd.export_probability_matrices(make_heatmap=True) + nd_norm = captured_nd['kwargs']['norm'] + + captured_dt = _capture_imshow(monkeypatch) + dt = _detector_analyzer( + tmp_path / 'dt', + walk_probs=[0.3], + sit_probs=[0.7], + times=[0.0], + ) + (tmp_path / 'dt').mkdir() + dt.export_probability_matrices_dt(make_heatmap=True) + dt_norm = captured_dt['kwargs']['norm'] + + _assert_fixed_linear_norm(nd_norm) + _assert_fixed_linear_norm(dt_norm) + assert float(nd_norm.vmin) == float(dt_norm.vmin) + assert float(nd_norm.vmax) == float(dt_norm.vmax) + + +def test_saved_numeric_matrices_unchanged_by_plotting(tmp_path): + walk = [0.0, np.nan, 0.4] + sit = [0.2, np.inf, 1.0] + expected = np.array([walk, sit], dtype=np.float32).T + + true_dir = tmp_path / 'heat' + false_dir = tmp_path / 'noheat' + true_dir.mkdir() + false_dir.mkdir() + + a_true = _non_detector_analyzer(true_dir, walk, sit, times=[0.0, 0.1, 0.2]) + a_false = _non_detector_analyzer(false_dir, walk, sit, times=[0.0, 0.1, 0.2]) + a_true.export_probability_matrices(make_heatmap=True) + a_false.export_probability_matrices(make_heatmap=False) + + loaded_true = np.load(os.path.join(str(true_dir), 'probability_matrix_ID0.npy')) + loaded_false = np.load(os.path.join(str(false_dir), 'probability_matrix_ID0.npy')) + np.testing.assert_array_equal(loaded_true, expected) + np.testing.assert_array_equal(loaded_false, expected) + csv_true = np.genfromtxt( + os.path.join(str(true_dir), 'probability_matrix_ID0.csv'), + delimiter=',', + names=True, + ) + assert np.isnan(csv_true['walk'][1]) + + d_true = _detector_analyzer(true_dir / 'dt', walk, sit, times=[0.0, 0.1, 0.2]) + (true_dir / 'dt').mkdir() + d_true.export_probability_matrices_dt(make_heatmap=True) + loaded_dt = np.load(os.path.join(str(true_dir / 'dt'), 'mouse_probability_matrix_ID0.npy')) + np.testing.assert_array_equal(loaded_dt, expected) + + +def test_stride_downsampling_unchanged(tmp_path, monkeypatch): + captured = _capture_imshow(monkeypatch) + n = 10 + walk = [0.2] * n + sit = [0.3] * n + times = [i * 0.1 for i in range(n)] + max_frames = 4 + expected_stride = int(np.ceil(n / max_frames)) + assert expected_stride == 3 + expected_frames = len(np.arange(n)[::expected_stride]) + + animal = _non_detector_analyzer(tmp_path / 'nd', walk, sit, times=times) + (tmp_path / 'nd').mkdir() + animal.export_probability_matrices(make_heatmap=True, max_frames_for_heatmap=max_frames) + assert captured['X'].shape[1] == expected_frames + loaded = np.load(os.path.join(str(tmp_path / 'nd'), 'probability_matrix_ID0.npy')) + assert loaded.shape == (n, 2) + + dt = _detector_analyzer(tmp_path / 'dt', walk, sit, times=times) + (tmp_path / 'dt').mkdir() + dt.export_probability_matrices_dt(make_heatmap=True, max_frames_for_heatmap=max_frames) + assert captured['X'].shape[1] == expected_frames + loaded_dt = np.load(os.path.join(str(tmp_path / 'dt'), 'mouse_probability_matrix_ID0.npy')) + assert loaded_dt.shape == (n, 2) diff --git a/LabGym/tests/test_state_transition_map.py b/LabGym/tests/test_state_transition_map.py new file mode 100644 index 00000000..73eda802 --- /dev/null +++ b/LabGym/tests/test_state_transition_map.py @@ -0,0 +1,1910 @@ +""" +Focused tests for State Transition Map V1 computational product rules. +""" + +from __future__ import annotations + +import math +from pathlib import Path + +import matplotlib + +matplotlib.use('Agg') + +import pandas as pd +import pytest +from matplotlib.patches import FancyArrowPatch + +from LabGym.tools import ( + _STM_EDGE_CASING_EXTRA, + _STM_EDGE_LABEL_FONTSIZE, + _STM_EDGE_LABEL_MAX_ROTATION, + _STM_EDGE_LABEL_MIDDOT, + _STM_EDGE_LABEL_T, + _STM_EDGE_LW_MIN, + _STM_EDGE_LW_SPAN, + _STM_EDGE_MUTATION_SCALE, + _STM_EDGE_RAD_BIDIR, + _STM_EDGE_RAD_SINGLE, + _STM_FIGSIZE_MAP, + _STM_KEY_EXPLAIN, + _STM_KEY_GAP_PT, + _STM_LABEL_MIN_CLEARANCE_PT, + _STM_LEGEND_TEXT, + _STM_NODE_SIZE_MIN, + _STM_PASS_BEHIND_LEGEND, + _STM_PASS_BEHIND_MIN_INTERVAL_DT, + _STM_ROUTE_NODE_PAD_PT, + _STM_ROUTE_REASONABLE_MAX, + _STM_ROUTE_SAMPLE_N, + _stm_data_units_per_point, + _stm_draw_animal_map, + _stm_node_radius_data, + _stm_rad_sign, + _stm_sample_arc3_polyline, + plot_state_transition_map, + stm_arc3_point_and_tangent, + stm_arc3_point_at_arclength, + stm_assign_edge_identifiers, + stm_best_oncurve_label_candidate, + stm_cleanup_obsolete_artifacts, + stm_cleanup_stale_animal_folder, + stm_circular_layout, + stm_compute_animal_metrics, + stm_contrast_ratio, + stm_default_color_palette, + stm_edge_halfwidth_data, + stm_edge_label_half_extents_pt, + stm_edge_label_placement, + stm_edge_label_rotation, + stm_edge_linewidth, + stm_edge_rad, + stm_edge_route_reasonable_rads, + stm_edge_shrink_points, + stm_evaluate_oncurve_label_candidates, + stm_figure_id_subtitle, + stm_format_edge_label, + stm_format_node_label, + stm_format_occupancy_percent, + stm_format_transition_key_lines, + stm_hard_labels, + stm_is_animal_package_dirname, + stm_key_pack_y_positions, + stm_key_region_height_inches, + stm_marker_radius_points, + stm_node_label_color, + stm_node_marker_size, + stm_ordered_transition_edges, + stm_pass_behind_path_pieces, + stm_pick_edge_label_position, + stm_place_edge_label, + stm_relative_luminance, + stm_route_conservative_envelope_bounds, + stm_route_crossed_nodes, + stm_route_node_clearance, + stm_route_obstacle_t_intervals, + stm_safe_animal_folder_name, + stm_select_edge_route, + stm_selected_routes_fit_axes_bounds, + stm_visible_edge_halfwidth_pt, + stm_wrap_behavior_name, +) + +# Test-local geometric tolerances (not production exports). +_STM_ENDPOINT_TOLERANCE = 0.08 +_STM_ON_CURVE_TOLERANCE = 1e-9 + + + +def _events(labels, conf=None): + '''Build [label, conf] list; default conf=0.9.''' + if conf is None: + conf = [0.9] * len(labels) + return [[lab, float(c)] for lab, c in zip(labels, conf)] + + +def test_bouts_and_transitions_collapse_within_segment(): + labels = ['A', 'A', 'A', 'B', 'B', 'C'] + m = stm_compute_animal_metrics(labels, ['A', 'B', 'C']) + assert m['status'] == 'ok' + assert m['bout_labels'] == ['A', 'B', 'C'] + assert int(m['count_matrix'].loc['A', 'B']) == 1 + assert int(m['count_matrix'].loc['B', 'C']) == 1 + assert int(m['count_matrix'].values.sum()) == 2 + assert int(m['count_matrix'].loc['A', 'C']) == 0 + + +def test_na_breaks_without_bridging(): + m = stm_compute_animal_metrics(['A', 'NA', 'B'], ['A', 'B']) + assert m['bout_labels'] == ['A', 'B'] + assert int(m['count_matrix'].loc['A', 'B']) == 0 + assert m['transition_total'] == 0 + assert m['segments'] == [['A'], ['B']] + + +def test_excluded_behavior_breaks_without_bridging(): + labels = ['Walk', 'Groom', 'Rear'] + included = ['Walk', 'Rear'] # Groom excluded + m = stm_compute_animal_metrics(labels, included) + assert m['bout_labels'] == ['Walk', 'Rear'] + assert int(m['count_matrix'].loc['Walk', 'Rear']) == 0 + assert m['transition_total'] == 0 + assert 'Groom' not in m['observed_behaviors'] + + +def test_occupancy_uses_frame_counts_not_bouts(): + # 3 frames A, 2 frames B → occ A=0.6, B=0.4 (not bout share 0.5/0.5) + m = stm_compute_animal_metrics(['A', 'A', 'A', 'B', 'B'], ['A', 'B']) + assert m['frame_counts']['A'] == 3 + assert m['frame_counts']['B'] == 2 + assert m['occupancy']['A'] == pytest.approx(0.6) + assert m['occupancy']['B'] == pytest.approx(0.4) + assert sum(m['occupancy'].values()) == pytest.approx(1.0) + + +def test_occupancy_sums_to_one(): + m = stm_compute_animal_metrics( + ['A', 'A', 'B', 'B', 'X', 'C', 'C', 'A'], + ['A', 'B', 'C'], + ) + assert sum(m['occupancy'].values()) == pytest.approx(1.0) + assert m['included_frame_total'] == 7 + assert m['frame_counts']['A'] == 3 + + +def test_row_normalized_probabilities_and_zero_outgoing(): + # A→B twice, A→C once; C only terminal + labels = ['A', 'B', 'A', 'B', 'A', 'C'] + m = stm_compute_animal_metrics(labels, ['A', 'B', 'C']) + assert float(m['probability_matrix'].loc['A', 'B']) == pytest.approx(2 / 3) + assert float(m['probability_matrix'].loc['A', 'C']) == pytest.approx(1 / 3) + assert float(m['probability_matrix'].loc['A'].sum()) == pytest.approx(1.0) + # C has no outgoing + assert int(m['count_matrix'].loc['C'].sum()) == 0 + assert m['probability_matrix'].loc['C'].isna().all() + + +def test_edge_data_preserve_count_and_probability(): + m = stm_compute_animal_metrics(['A', 'B', 'A', 'B', 'A', 'B'], ['A', 'B']) + assert int(m['count_matrix'].loc['A', 'B']) == 3 + assert float(m['probability_matrix'].loc['A', 'B']) == pytest.approx(1.0) + assert int(m['count_matrix'].loc['B', 'A']) == 2 + assert float(m['probability_matrix'].loc['B', 'A']) == pytest.approx(1.0) + + +def test_confidence_ignored(): + labels = ['A', 'A', 'B', 'B', 'C'] + m1 = stm_compute_animal_metrics(labels, ['A', 'B', 'C']) + e1 = _events(labels, conf=[0.1, 0.2, 0.99, 0.01, 0.5]) + e2 = _events(labels, conf=[0.99, 0.99, 0.01, 0.99, 0.01]) + assert stm_hard_labels(e1) == stm_hard_labels(e2) + m2 = stm_compute_animal_metrics(stm_hard_labels(e1), ['A', 'B', 'C']) + m3 = stm_compute_animal_metrics(stm_hard_labels(e2), ['A', 'B', 'C']) + assert m2['count_matrix'].equals(m3['count_matrix']) + assert m2['occupancy'] == m3['occupancy'] + assert m1['count_matrix'].equals(m2['count_matrix']) + + +def test_per_animal_not_pooled(tmp_path): + event_probability = { + 0: _events(['A', 'B', 'A', 'B']), + 1: _events(['C', 'C', 'D']), + } + included = ['A', 'B', 'C', 'D'] + result = plot_state_transition_map( + str(tmp_path / 'run_stm'), + event_probability, + behavior_to_include=included, + behavior_colors={b: '#112233' for b in included}, + draw_maps=False, + ) + assert result['status'] == 'success' + assert result['maps_written'] == 2 + a0 = tmp_path / 'run_stm' / '0' + a1 = tmp_path / 'run_stm' / '1' + assert a0.is_dir() and a1.is_dir() + c0 = pd.read_excel(a0 / 'state_transition_counts.xlsx', index_col=0) + c1 = pd.read_excel(a1 / 'state_transition_counts.xlsx', index_col=0) + assert set(c0.index) == {'A', 'B'} + assert set(c1.index) == {'C', 'D'} + assert int(c0.loc['A', 'B']) == 2 + assert 'C' not in c0.index + assert int(c1.values.sum()) == 1 + + +def test_regeneration_removes_stale_animal_and_empty_maps(tmp_path): + stm = tmp_path / 'demo_state_transition_map' + included = ['A', 'B'] + r1 = plot_state_transition_map( + str(stm), + { + 0: _events(['A', 'B']), + 1: _events(['A', 'A', 'B']), + 2: _events(['A', 'B', 'A']), + }, + behavior_to_include=included, + behavior_colors={'A': '#aaaaff', 'B': '#ffaaaa'}, + draw_maps=False, + ) + assert r1['maps_written'] == 3 + assert (stm / '2').is_dir() + + r2 = plot_state_transition_map( + str(stm), + { + 0: _events(['A', 'B']), + 1: _events(['NA', 'NA']), + }, + behavior_to_include=included, + behavior_colors={'A': '#aaaaff', 'B': '#ffaaaa'}, + draw_maps=False, + ) + assert r2['status'] == 'warning_partial' + assert r2['maps_written'] == 1 + assert r2['empty_animals'] == 1 + assert not (stm / '2').exists() + assert (stm / '1' / 'state_transition_summary.xlsx').is_file() + assert not (stm / '1' / 'state_transition_counts.xlsx').exists() + + +def test_stale_animal_folder_with_only_stm_files_is_removed(tmp_path): + stm = tmp_path / 'stm_root' + stm.mkdir() + # Legacy animal_* package still cleaned. + stale_legacy = stm / 'animal_99' + stale_legacy.mkdir() + (stale_legacy / 'state_transition_map.png').write_bytes(b'x') + (stale_legacy / 'state_transition_counts.xlsx').write_bytes(b'y') + (stale_legacy / 'state_transition_summary.xlsx').write_bytes(b'z') + assert stm_cleanup_stale_animal_folder(str(stale_legacy)) == 'removed' + assert not stale_legacy.exists() + # ID-only package. + stale = stm / '99' + stale.mkdir() + (stale / 'state_transition_map.png').write_bytes(b'x') + assert stm_cleanup_stale_animal_folder(str(stale)) == 'removed' + assert not stale.exists() + + +def test_stale_animal_folder_preserves_unknown_content(tmp_path): + stm = tmp_path / 'stm_root2' + stm.mkdir() + stale = stm / '77' + stale.mkdir() + (stale / 'state_transition_map.png').write_bytes(b'x') + (stale / 'user_notes.txt').write_text('keep me') + outcome = stm_cleanup_stale_animal_folder(str(stale)) + assert outcome == 'preserved' + assert stale.is_dir() + assert (stale / 'user_notes.txt').is_file() + assert not (stale / 'state_transition_map.png').exists() + + +def test_stale_cleanup_reports_preserved_in_run_result(tmp_path): + stm = tmp_path / 'stm_run_preserve' + stm.mkdir() + stale = stm / '5' + stale.mkdir() + (stale / 'state_transition_counts.xlsx').write_bytes(b'old') + (stale / 'readme_user.txt').write_text('manual') + result = plot_state_transition_map( + str(stm), + {0: _events(['A', 'B'])}, + behavior_to_include=['A', 'B'], + behavior_colors={'A': '#111111', 'B': '#222222'}, + draw_maps=False, + ) + assert '5' in result['preserved_stale_animal_folders'] + assert (stale / 'readme_user.txt').is_file() + assert not (stale / 'state_transition_counts.xlsx').exists() + summary = pd.read_excel(stm / 'run_summary.xlsx') + assert '5' in str(summary['preserved_stale_animal_folders'].iloc[0]) + + +def test_all_empty_warning_status(tmp_path): + result = plot_state_transition_map( + str(tmp_path / 'empty_stm'), + { + 0: _events(['NA', 'NA']), + 1: _events(['NA']), + }, + behavior_to_include=['A', 'B'], + behavior_colors={'A': '#111111', 'B': '#222222'}, + draw_maps=False, + ) + assert result['status'] == 'warning_no_maps' + assert result['maps_written'] == 0 + assert result['empty_animals'] == 2 + assert (tmp_path / 'empty_stm' / 'run_summary.xlsx').is_file() + + +def test_error_when_no_included_behaviors(tmp_path): + result = plot_state_transition_map( + str(tmp_path / 'err_stm'), + {0: _events(['A', 'B'])}, + behavior_to_include=[], + draw_maps=False, + ) + assert result['status'] == 'error' + assert result['maps_written'] == 0 + + +def test_no_persistence_json_written(tmp_path): + stm = tmp_path / 'stateless_stm' + stm.mkdir() + # plant legacy files — should be cleaned, not recreated + (stm / 'state_transition_colors.json').write_text('{}') + (stm / 'state_transition_layout.json').write_text('{}') + plot_state_transition_map( + str(stm), + {0: _events(['A', 'B', 'A'])}, + behavior_to_include=['A', 'B'], + behavior_colors={'A': '#111111', 'B': '#222222'}, + draw_maps=False, + ) + assert not (stm / 'state_transition_colors.json').exists() + assert not (stm / 'state_transition_layout.json').exists() + assert (stm / '0' / 'state_transition_counts.xlsx').is_file() + + +def test_draw_maps_optional_png(tmp_path): + stm = tmp_path / 'png_stm' + result = plot_state_transition_map( + str(stm), + {0: _events(['A', 'B', 'C', 'A'])}, + behavior_to_include=['A', 'B', 'C'], + behavior_colors={'A': '#111111', 'B': '#222222', 'C': '#333333'}, + draw_maps=True, + map_dpi=72, + ) + assert result['status'] == 'success' + assert (stm / '0' / 'state_transition_map.png').is_file() + + +def test_safe_animal_folder_name(): + assert stm_safe_animal_folder_name(0) == '0' + assert stm_safe_animal_folder_name(12) == '12' + assert '/' not in stm_safe_animal_folder_name('a/b') + assert stm_safe_animal_folder_name('a/b') == 'a_b' + assert stm_is_animal_package_dirname('0') + assert stm_is_animal_package_dirname('animal_3') + assert not stm_is_animal_package_dirname('my notes') + assert not stm_is_animal_package_dirname('..') + + +def test_unrelated_numeric_folder_without_stm_files_not_cleaned(tmp_path): + '''Numeric user folder that is not an STM package must be left alone.''' + stm = tmp_path / 'state_transition_map' + stm.mkdir() + user_num = stm / '7' + user_num.mkdir() + (user_num / 'personal.txt').write_text('keep') + # Stale true ID package with STM artifacts. + stale = stm / '9' + stale.mkdir() + (stale / 'state_transition_counts.xlsx').write_bytes(b'x') + preserved = stm_cleanup_obsolete_artifacts(str(stm), current_animal_folder_names={'0'}) + assert user_num.is_dir() + assert (user_num / 'personal.txt').is_file() + assert not stale.exists() + assert '7' not in preserved + + +def test_figure_title_id_and_legend_constants(): + assert stm_figure_id_subtitle(0) == 'ID 0' + assert stm_figure_id_subtitle(12) == 'ID 12' + assert 'time spent in each behavior' in _STM_LEGEND_TEXT + assert 'probability of transitioning' in _STM_LEGEND_TEXT + assert 'T#' in _STM_LEGEND_TEXT + assert 'Transition key' in _STM_LEGEND_TEXT + + +def test_arrowhead_increased_without_linewidth_change(): + # Arrowheads grown since baseline 15; linewidth uses fixed 0–1 scale. + assert _STM_EDGE_MUTATION_SCALE > 15 + lw_max = stm_edge_linewidth(1.0) + assert lw_max == pytest.approx(_STM_EDGE_LW_MIN + _STM_EDGE_LW_SPAN) + assert lw_max <= 4.0 + + +def test_gui_stm_button_labels_in_source(): + '''STM panel wording without ellipses / exclusion parenthetical.''' + src = Path(__file__).resolve().parents[2] / 'LabGym' / 'gui_analyzer.py' + text = src.read_text(encoding='utf-8') + start = text.index('class PanelLv2_StateTransitionMap') + body = text[start:start + 6500] + assert 'Select an all_events.xlsx' in body + assert 'file...' not in body + assert 'Select an all_events.xlsx file...' not in body + assert 'Set behavior colors...' not in body + assert 'Set behavior' in body and 'colors' in body + assert '(nodes removed; sequence breaks)' not in body + assert 'not saved between runs' not in body + assert 'Generate state transition maps' in body + assert "state_transition_map'" in body or 'state_transition_map"' in body or "state_transition_map')" in body + assert 'all_events_state_transition_map' not in body + + +def test_stm_gui_exclusion_cancel_preserves_and_ok_updates(): + from LabGym.gui_analyzer import ( + stm_gui_apply_exclusion_dialog_result, + stm_gui_exclusion_status_label, + ) + + previous = ['Walk', 'Rear'] + assert stm_gui_apply_exclusion_dialog_result( + previous, ['Groom'], accepted=False, + ) == previous + assert stm_gui_apply_exclusion_dialog_result( + previous, ['Groom'], accepted=True, + ) == ['Groom'] + assert stm_gui_apply_exclusion_dialog_result( + previous, [], accepted=True, + ) == [] + assert stm_gui_exclusion_status_label(previous) == ( + "Excluded: ['Walk', 'Rear']." + ) + assert stm_gui_exclusion_status_label([]) == 'Default: none.' + + +def test_stm_gui_color_status_custom_flag(): + from LabGym.gui_analyzer import stm_gui_color_status_label + from LabGym.tools import stm_session_colors + + assert stm_gui_color_status_label(False) == 'Default behavior colors.' + assert stm_gui_color_status_label(True) == 'Custom behavior colors set.' + # Changing exclusions with session merge keeps custom colors; status must stay custom. + colors_are_custom = True + colors = stm_session_colors( + ['A', 'B'], + existing_colors={'A': '#111111', 'B': '#222222'}, + ) + # exclude B: remaining include A only + colors = stm_session_colors(['A'], existing_colors=colors) + assert 'A' in colors + assert colors_are_custom + assert stm_gui_color_status_label(colors_are_custom) == 'Custom behavior colors set.' + + +def test_stm_gui_color_dialog_cancel_preserves_flag_semantics(): + from LabGym.gui_analyzer import stm_gui_color_status_label + + # Model: cancel leaves colors_are_custom and mapping untouched. + prior_custom = True + prior_colors = {'Walk': '#abcdef'} + accepted = False + if accepted: + prior_custom = True + prior_colors = {'Walk': '#000000'} + assert prior_custom is True + assert prior_colors == {'Walk': '#abcdef'} + assert stm_gui_color_status_label(prior_custom) == 'Custom behavior colors set.' + + +def test_stm_gui_parse_failure_reset_semantics(): + '''Simulate successful load then failed load reset without constructing wx.Panel.''' + from LabGym.gui_analyzer import ( + stm_gui_color_status_label, + stm_gui_exclusion_status_label, + ) + + # After successful load + path_to_events = '/tmp/all_events.xlsx' + behavior_names = ['A', 'B'] + behavior_to_exclude = ['B'] + behavior_colors = {'A': '#111111'} + colors_are_custom = True + # After failed parse: same fields as reset_input_dependent_state + path_to_events = None + behavior_names = [] + behavior_to_exclude = [] + behavior_colors = {} + colors_are_custom = False + input_label = 'No valid all_events.xlsx file selected.' + assert path_to_events is None + assert behavior_names == [] + assert behavior_to_exclude == [] + assert behavior_colors == {} + assert colors_are_custom is False + assert input_label == 'No valid all_events.xlsx file selected.' + assert stm_gui_exclusion_status_label(behavior_to_exclude) == 'Default: none.' + assert stm_gui_color_status_label(colors_are_custom) == 'Default behavior colors.' + # Generate blocked without valid input + result_path = '/tmp/out' + blocked = path_to_events is None or result_path is None + assert blocked is True + + +def test_node_size_floor_and_occupancy_scaling(): + s0 = stm_node_marker_size(0.0) + s_half = stm_node_marker_size(0.5) + s1 = stm_node_marker_size(1.0) + assert s0 == pytest.approx(_STM_NODE_SIZE_MIN) + assert s_half > s0 + assert s1 > s_half + assert s0 >= 2000.0 + + +def test_deterministic_label_wrapping(): + # Default target ~8–9 chars: balanced multi-word labels, no mid-word splits. + assert stm_wrap_behavior_name('behind the wheel') == ['behind', 'the wheel'] + assert stm_wrap_behavior_name('body grooming fv') == ['body', 'grooming', 'fv'] + assert stm_wrap_behavior_name('face grooming fv') == ['face', 'grooming', 'fv'] + lines = stm_wrap_behavior_name('Very Long Behavior Name Token') + assert all(len(line) <= 9 for line in lines) + assert lines == stm_wrap_behavior_name('Very Long Behavior Name Token') + # Deterministic for fixed max_line_chars override. + assert stm_wrap_behavior_name('ab cd ef', max_line_chars=5) == ( + stm_wrap_behavior_name('ab cd ef', max_line_chars=5) + ) + label, fontsize = stm_format_node_label('Walk', 0.42) + assert label.split('\n')[0] == 'Walk' + assert label.endswith('42%') + assert '42%' in label + assert fontsize >= 7 + + +def test_occupancy_percent_display_lt1_vs_zero(): + assert stm_format_occupancy_percent(0.0) == '0%' + assert stm_format_occupancy_percent(0.0).startswith('0') + assert stm_format_occupancy_percent(0.004) == '<1%' + assert stm_format_occupancy_percent(0.0099) == '<1%' + assert stm_format_occupancy_percent(0.01) == '1%' + assert stm_format_occupancy_percent(0.42) == '42%' + label0, _ = stm_format_node_label('A', 0.0) + assert label0.endswith('0%') + assert '<1%' not in label0 + label_small, _ = stm_format_node_label('A', 0.004) + assert label_small.endswith('<1%') + + +def test_linewidth_monotonic_and_compressed(): + lw_small = stm_edge_linewidth(0.1) + lw_mid = stm_edge_linewidth(0.5) + lw_max = stm_edge_linewidth(1.0) + assert lw_small < lw_mid < lw_max + # Previous formula: 0.4 + 8.0 * sqrt(p/max) -> max 8.4 + previous_max = 0.4 + 8.0 + assert lw_max == pytest.approx(_STM_EDGE_LW_MIN + _STM_EDGE_LW_SPAN) + assert lw_max < previous_max + assert lw_max <= 4.0 + + +def test_linewidth_same_probability_same_width_across_maps(): + '''Width depends only on this edge's probability, not the map's maximum.''' + p = 0.25 + lw = stm_edge_linewidth(p) + assert lw == pytest.approx(_STM_EDGE_LW_MIN + _STM_EDGE_LW_SPAN * p) + # Old formula scaled by map max: sqrt(0.25/1) vs sqrt(0.25/0.25) differed. + assert math.sqrt(p / 1.0) != math.sqrt(p / p) + assert stm_edge_linewidth(p) == lw + + +def test_linewidth_unrelated_edge_cannot_change_target_width(): + target = stm_edge_linewidth(0.4) + stm_edge_linewidth(1.0) + stm_edge_linewidth(0.01) + assert stm_edge_linewidth(0.4) == pytest.approx(target) + + +def test_linewidth_monotonic_across_representative_probabilities(): + prev = stm_edge_linewidth(0.0) + for p in (0.01, 0.1, 0.25, 0.5, 0.9, 1.0): + lw = stm_edge_linewidth(p) + assert lw >= prev + prev = lw + + +def test_linewidth_small_positive_gets_minimum_visible_width(): + lw = stm_edge_linewidth(0.01) + assert lw >= _STM_EDGE_LW_MIN + assert lw == pytest.approx(_STM_EDGE_LW_MIN + _STM_EDGE_LW_SPAN * 0.01) + + +def test_linewidth_probability_one_reaches_fixed_maximum(): + assert stm_edge_linewidth(1.0) == pytest.approx( + _STM_EDGE_LW_MIN + _STM_EDGE_LW_SPAN + ) + + +def test_linewidth_uses_probability_not_count(): + import inspect + assert list(inspect.signature(stm_edge_linewidth).parameters) == ['probability'] + # Same row-normalized p, different observed counts: same width. + metrics_few = stm_compute_animal_metrics(['A', 'B', 'A', 'B'], ['A', 'B']) + metrics_many = stm_compute_animal_metrics(['A', 'B'] * 10, ['A', 'B']) + + def _ab(metrics): + return next( + e for e in stm_ordered_transition_edges( + metrics['observed_behaviors'], + metrics['count_matrix'], + metrics['probability_matrix'], + ) if e['src'] == 'A' and e['dst'] == 'B' + ) + + few = _ab(metrics_few) + many = _ab(metrics_many) + assert few['value'] == pytest.approx(many['value']) + assert few['count'] != many['count'] + assert stm_edge_linewidth(few['value']) == pytest.approx( + stm_edge_linewidth(many['value']) + ) + assert stm_format_edge_label(few['value'], few['count']) == '%.2f (%d)' % ( + few['value'], few['count'], + ) + + +def test_node_label_contrast_wcag_palette_and_custom(): + '''Defaults sit in exact luminance bands; customs keep accessible black/white text.''' + for fill in stm_default_color_palette(): + L = stm_relative_luminance(fill) + text = stm_node_label_color(fill) + assert text in ('#000000', '#FFFFFF') + assert not (0.15 < L < 0.28) + if L <= 0.15: + assert text == '#FFFFFF' + assert stm_contrast_ratio(fill, '#FFFFFF') >= 4.5 + else: + assert L >= 0.28 + assert text == '#000000' + assert stm_contrast_ratio(fill, '#000000') >= 4.5 + + # Custom fills may land mid-band; only text (black/white) is auto-chosen. + for fill in ( + '#000000', + '#111111', + '#1a1a1a', + '#FFFFFF', + '#F5F5F5', + '#EEEEEE', + '#4C72B0', + '#8172B3', + '#937860', + ): + text = stm_node_label_color(fill) + assert text in ('#000000', '#FFFFFF') + assert stm_contrast_ratio(fill, text) >= 4.5 + assert stm_node_label_color('#000000') == '#FFFFFF' + assert stm_node_label_color('#FFFFFF') == '#000000' + + +def test_edge_label_format_with_identifier(): + assert stm_format_edge_label(0.82, 37) == '0.82 (37)' + assert stm_format_edge_label(1.0, 1) == '1.00 (1)' + text = stm_format_edge_label(0.89, 8, edge_id='T5') + assert text == 'T5 · 0.89 (8)' + assert text == 'T5' + _STM_EDGE_LABEL_MIDDOT + '0.89 (8)' + assert '\n' not in text + assert _STM_EDGE_LABEL_MIDDOT == ' \u00b7 ' + # Longer ids still single-line. + assert stm_format_edge_label(0.82, 37, edge_id='T12') == 'T12 · 0.82 (37)' + assert '\n' not in stm_format_edge_label(0.5, 2, edge_id='T99') + + +def test_transition_key_format_unchanged_by_onmap_single_line(): + '''Key stays "T#: source → destination: p (n)"; on-map uses middle-dot form.''' + entries = [{ + 'edge_id': 'T5', + 'src': 'source', + 'dst': 'destination', + 'value': 0.89, + 'count': 8, + }] + key_lines = stm_format_transition_key_lines(entries) + assert key_lines == ['T5: source \u2192 destination: 0.89 (8)'] + assert ' · ' not in key_lines[0] + assert '\n' not in key_lines[0] + on_map = stm_format_edge_label(0.89, 8, edge_id='T5') + assert on_map == 'T5 · 0.89 (8)' + assert on_map != key_lines[0] + + +def test_edge_label_half_extents_single_line_bbox(): + '''Single-line bbox is wider than tall; not the legacy two-line 36×14 half-box.''' + text = stm_format_edge_label(0.89, 8, edge_id='T5') + hw, hh = stm_edge_label_half_extents_pt(text) + assert '\n' not in text + assert hw > hh + # Shorter than legacy two-line half-height (14 pt). + assert hh < 14.0 + # Representative long label is wider than short one. + hw_long, hh_long = stm_edge_label_half_extents_pt( + stm_format_edge_label(0.99, 999, edge_id='T99'), + ) + assert hw_long > hw + assert abs(hh_long - hh) < 1e-12 + # Default representative extents match long single-line sizing. + hw_def, hh_def = stm_edge_label_half_extents_pt() + assert hw_def == pytest.approx(hw_long) + assert hh_def == pytest.approx(hh_long) + assert _STM_EDGE_LABEL_FONTSIZE == 8.0 + + +def test_oncurve_and_callout_use_single_line_label_extents(): + '''Placement collides with the wider/shorter single-line half-extents.''' + x1, y1, x2, y2 = 0.0, 0.0, 2.0, 0.0 + rad = 0.28 + text = stm_format_edge_label(0.89, 8, edge_id='T5') + assert '\n' not in text + hw_pt, hh_pt = stm_edge_label_half_extents_pt(text) + # Data-ish half box proportional to pt estimate. + label_half_w = hw_pt * 0.01 + label_half_h = hh_pt * 0.01 + # Two-line legacy box was taller relative to this single-line height. + legacy_half_w = 36.0 * 0.01 + legacy_half_h = 14.0 * 0.01 + assert label_half_h < legacy_half_h + assert label_half_w != legacy_half_w or label_half_h != legacy_half_h + + node_centers = {'A': (0.0, 0.0), 'B': (2.0, 0.0)} + node_radii = {'A': 0.2, 'B': 0.2} + on_curve = stm_place_edge_label( + x1, y1, x2, y2, rad, + node_centers, node_radii, [], [], + label_half_w, label_half_h, + min_clearance_data=0.001, + units_per_point=0.01, + ) + assert on_curve['mode'] == 'on_curve' + callout = stm_place_edge_label( + x1, y1, x2, y2, rad, + node_centers, node_radii, [], [], + label_half_w, label_half_h, + min_clearance_data=5.0, + units_per_point=0.01, + ) + assert callout['mode'] == 'callout' + # Same extents + inputs → same placement (deterministic). + assert stm_place_edge_label( + x1, y1, x2, y2, rad, + node_centers, node_radii, [], [], + label_half_w, label_half_h, + min_clearance_data=0.001, + units_per_point=0.01, + ) == on_curve + assert stm_place_edge_label( + x1, y1, x2, y2, rad, + node_centers, node_radii, [], [], + label_half_w, label_half_h, + min_clearance_data=5.0, + units_per_point=0.01, + ) == callout + + +def test_deterministic_edge_identifiers_and_key_ordering(): + m = stm_compute_animal_metrics( + ['A', 'B', 'A', 'C', 'B', 'A'], + ['A', 'B', 'C'], + ) + e1 = stm_assign_edge_identifiers( + stm_ordered_transition_edges( + m['observed_behaviors'], + m['count_matrix'], + m['probability_matrix'], + ) + ) + e2 = stm_assign_edge_identifiers( + stm_ordered_transition_edges( + m['observed_behaviors'], + m['count_matrix'], + m['probability_matrix'], + ) + ) + assert [edge['edge_id'] for edge in e1] == [edge['edge_id'] for edge in e2] + assert [edge['edge_id'] for edge in e1] == [ + 'T%d' % i for i in range(1, len(e1) + 1) + ] + # Ordered by (src, dst) in sorted observed: A,B,C + assert [(edge['src'], edge['dst']) for edge in e1] == sorted( + [(edge['src'], edge['dst']) for edge in e1], + key=lambda pair: ( + m['observed_behaviors'].index(pair[0]), + m['observed_behaviors'].index(pair[1]), + ), + ) + key1 = stm_format_transition_key_lines(e1) + key2 = stm_format_transition_key_lines(e2) + assert key1 == key2 + assert key1[0].startswith('T1: ') + assert ' → ' in key1[0] + assert key1[0].endswith( + ': %.2f (%d)' % (e1[0]['value'], e1[0]['count']) + ) + + +def test_edge_endpoints_terminate_near_node_boundaries(): + '''Shrink tracks node radius so path endpoints meet node boundaries.''' + occ_src = 0.2 + occ_dst = 0.8 + s_src = stm_node_marker_size(occ_src) + s_dst = stm_node_marker_size(occ_dst) + shrink_a = stm_edge_shrink_points(s_src) + shrink_b = stm_edge_shrink_points(s_dst) + assert shrink_a == pytest.approx(stm_marker_radius_points(s_src) + 4.0) + assert shrink_b == pytest.approx(stm_marker_radius_points(s_dst) + 4.0) + assert shrink_b > shrink_a + + # Geometric check in a fixed data-space conversion (1 data unit = 50 points). + points_per_data = 50.0 + x1, y1, x2, y2 = 0.0, 0.0, 2.0, 0.0 + rad = _STM_EDGE_RAD_SINGLE + r_src = stm_marker_radius_points(s_src) / points_per_data + r_dst = stm_marker_radius_points(s_dst) / points_per_data + shrink_a_data = shrink_a / points_per_data + shrink_b_data = shrink_b / points_per_data + ex, ey, _ = stm_arc3_point_at_arclength( + x1, y1, x2, y2, rad, shrink_a_data, from_end=False, + ) + fx, fy, _ = stm_arc3_point_at_arclength( + x1, y1, x2, y2, rad, shrink_b_data, from_end=True, + ) + # Attachment points sit at node radius (+ small stroke pad) along the curve. + assert abs(math.hypot(ex - x1, ey - y1) - shrink_a_data) <= _STM_ENDPOINT_TOLERANCE + assert abs(math.hypot(fx - x2, fy - y2) - shrink_b_data) <= _STM_ENDPOINT_TOLERANCE + assert abs(shrink_a_data - r_src) <= 4.0 / points_per_data + 1e-9 + assert abs(shrink_b_data - r_dst) <= 4.0 / points_per_data + 1e-9 + + +def test_reciprocal_transitions_are_geometrically_distinguishable(): + assert _STM_EDGE_RAD_BIDIR > _STM_EDGE_RAD_SINGLE + m = stm_compute_animal_metrics(['A', 'B', 'A', 'B'], ['A', 'B']) + # Magnitude seed (not final drawn rad). + assert stm_edge_rad('A', 'B', m['count_matrix']) == _STM_EDGE_RAD_BIDIR + assert stm_edge_rad('B', 'A', m['count_matrix']) == _STM_EDGE_RAD_BIDIR + x1, y1 = 0.0, 0.0 + x2, y2 = 2.0, 0.0 + node_centers = {'A': (0.0, 0.0), 'B': (2.0, 0.0)} + node_radii = {'A': 0.2, 'B': 0.2} + r1 = stm_select_edge_route( + x1, y1, x2, y2, 'A', 'B', _STM_EDGE_RAD_BIDIR, + node_centers, node_radii, 0.05, 0.02, [], paired_sign=None, + ) + r2 = stm_select_edge_route( + x2, y2, x1, y1, 'B', 'A', _STM_EDGE_RAD_BIDIR, + node_centers, node_radii, 0.05, 0.02, [r1['polyline']], + paired_sign=_stm_rad_sign(r1['rad']), + ) + assert r1['clearance'] >= 0.0 + assert r2['clearance'] >= 0.0 + assert r2['reciprocal_side_relaxed'] is False + # Same Arc3 rad *sign* => opposite geometric bows when endpoints reverse. + assert _stm_rad_sign(r1['rad']) == _stm_rad_sign(r2['rad']) + mx1, my1, _, _ = stm_arc3_point_and_tangent(x1, y1, x2, y2, r1['rad'], 0.5) + mx2, my2, _, _ = stm_arc3_point_and_tangent(x2, y2, x1, y1, r2['rad'], 0.5) + assert my1 * my2 < 0.0 + assert math.hypot(mx1 - mx2, my1 - my2) > 0.2 + + +def test_edge_labels_lie_on_home_curve_and_are_deterministic(): + x1, y1, x2, y2 = 0.0, 0.0, 2.0, 0.0 + rad = 0.28 + lx, ly, rot = stm_edge_label_placement(x1, y1, x2, y2, rad) + home = _stm_sample_arc3_polyline(x1, y1, x2, y2, rad, n=64) + # Label is generated from the home Arc3 curve (exact sample or on polyline). + on_curve = False + for t in (_STM_EDGE_LABEL_T, 0.5, 0.55, 0.6): + px, py, _, _ = stm_arc3_point_and_tangent(x1, y1, x2, y2, rad, t) + if math.hypot(lx - px, ly - py) <= _STM_ON_CURVE_TOLERANCE: + on_curve = True + break + if not on_curve: + # Distance to densely sampled home curve must be within tolerance. + from LabGym.tools import _stm_min_dist_to_polyline + assert _stm_min_dist_to_polyline(lx, ly, home) <= 1e-6 + assert abs(rot) <= _STM_EDGE_LABEL_MAX_ROTATION + assert stm_edge_label_placement(x1, y1, x2, y2, rad) == (lx, ly, rot) + + # Opposite direction is also on its own curve and deterministic. + lx2, ly2, rot2 = stm_edge_label_placement(x2, y2, x1, y1, rad) + assert stm_edge_label_placement(x2, y2, x1, y1, rad) == (lx2, ly2, rot2) + assert math.hypot(lx - lx2, ly - ly2) > 0.2 + + # Picker returns an on-curve point; identical inputs -> identical placement. + node_centers = {'A': (0.0, 0.0), 'B': (2.0, 0.0)} + node_radii = {'A': 0.35, 'B': 0.35} + p1 = stm_pick_edge_label_position( + x1, y1, x2, y2, rad, + node_centers, node_radii, + other_polylines=[], + placed_centers=[], + label_half_w=0.12, + label_half_h=0.05, + ) + p2 = stm_pick_edge_label_position( + x1, y1, x2, y2, rad, + node_centers, node_radii, + other_polylines=[], + placed_centers=[], + label_half_w=0.12, + label_half_h=0.05, + ) + assert p1 == p2 + px, py, prot = p1 + matched = False + for t in ( + 0.55, 0.50, 0.60, 0.45, 0.65, 0.40, 0.70, + ): + qx, qy, _, _ = stm_arc3_point_and_tangent(x1, y1, x2, y2, rad, t) + if math.hypot(px - qx, py - qy) <= _STM_ON_CURVE_TOLERANCE: + matched = True + break + assert matched + assert abs(prot) <= _STM_EDGE_LABEL_MAX_ROTATION + assert math.hypot(px - 0.0, py - 0.0) > node_radii['A'] + assert math.hypot(px - 2.0, py - 0.0) > node_radii['B'] + + +def test_edge_label_collision_maximizes_minimum_clearance(): + '''Picker chooses the candidate t that maximizes min clearance to a crossing.''' + x1, y1, x2, y2 = 0.0, 0.0, 2.0, 0.0 + rad = 0.35 + # Foreign polyline crosses near the preferred mid-curve point. + foreign = [(1.0, -0.5), (1.0, 0.5)] + node_centers = {'A': (0.0, 0.0), 'B': (2.0, 0.0)} + node_radii = {'A': 0.2, 'B': 0.2} + px, py, _ = stm_pick_edge_label_position( + x1, y1, x2, y2, rad, + node_centers, node_radii, + other_polylines=[foreign], + placed_centers=[], + label_half_w=0.12, + label_half_h=0.05, + ) + from LabGym.tools import _stm_min_dist_to_polyline + # Chosen point remains on the home curve. + matched_t = None + for t in (0.55, 0.50, 0.60, 0.45, 0.65, 0.40, 0.70): + qx, qy, _, _ = stm_arc3_point_and_tangent(x1, y1, x2, y2, rad, t) + if math.hypot(px - qx, py - qy) <= _STM_ON_CURVE_TOLERANCE: + matched_t = t + break + assert matched_t is not None + mid_x, mid_y, _, _ = stm_arc3_point_and_tangent(x1, y1, x2, y2, rad, 0.55) + d_mid = _stm_min_dist_to_polyline(mid_x, mid_y, foreign) + d_pick = _stm_min_dist_to_polyline(px, py, foreign) + # Maximin clearance should leave the mid-curve crossing when a better t exists. + assert d_pick > d_mid + 1e-9 + assert matched_t != 0.55 + + +def test_edge_label_rotation_clamped_and_upright(): + '''Rotation is upright then clamped to +/- max degrees.''' + # Steep upward tangent would exceed clamp. + assert stm_edge_label_rotation(0.1, 1.0) == pytest.approx( + _STM_EDGE_LABEL_MAX_ROTATION + ) + assert stm_edge_label_rotation(0.1, -1.0) == pytest.approx( + -_STM_EDGE_LABEL_MAX_ROTATION + ) + # Near-horizontal is unchanged within clamp. + assert abs(stm_edge_label_rotation(1.0, 0.05)) <= _STM_EDGE_LABEL_MAX_ROTATION + # Upside-down tangents are flipped upright before clamp. + rot = stm_edge_label_rotation(-1.0, 0.0) + assert abs(rot) <= 90.0 + assert abs(rot) <= _STM_EDGE_LABEL_MAX_ROTATION + assert stm_edge_label_rotation(1.0, 0.0, max_deg=10.0) == pytest.approx(0.0) + + +def test_fancy_arrow_patch_casing_and_shrink_integration(tmp_path, monkeypatch): + '''Inspect FancyArrowPatch kwargs from _stm_draw_animal_map (no PNG write).''' + captured = [] + RealFancyArrowPatch = FancyArrowPatch + + class CapturingFancyArrowPatch(RealFancyArrowPatch): + def __init__(self, *args, **kwargs): + captured.append({ + 'posA': args[0] if len(args) > 0 else kwargs.get('posA'), + 'posB': args[1] if len(args) > 1 else kwargs.get('posB'), + 'kwargs': dict(kwargs), + }) + super().__init__(*args, **kwargs) + + monkeypatch.setattr( + 'matplotlib.patches.FancyArrowPatch', + CapturingFancyArrowPatch, + ) + import matplotlib.pyplot as plt + monkeypatch.setattr(plt, 'savefig', lambda *a, **k: None) + + labels = ['A', 'B', 'A', 'C', 'B'] + included = ['A', 'B', 'C'] + metrics = stm_compute_animal_metrics(labels, included) + assert metrics['status'] == 'ok' + edges = stm_ordered_transition_edges( + metrics['observed_behaviors'], + metrics['count_matrix'], + metrics['probability_matrix'], + ) + assert len(edges) >= 2 + positions = stm_circular_layout(metrics['observed_behaviors']) + colors = {name: '#6B9FE0' for name in metrics['observed_behaviors']} + animal_dir = tmp_path / '0' + animal_dir.mkdir() + _stm_draw_animal_map( + str(animal_dir), + 0, + metrics, + positions, + colors, + dpi=72, + ) + + assert len(captured) == 2 * len(edges) + occupancy = metrics['occupancy'] + for i, edge in enumerate(edges): + casing = captured[2 * i] + fg = captured[2 * i + 1] + ck = casing['kwargs'] + fk = fg['kwargs'] + assert ck.get('color') == 'white' + assert fk.get('color') == 'black' + assert float(ck['linewidth']) > float(fk['linewidth']) + assert float(ck['linewidth']) == pytest.approx( + float(fk['linewidth']) + _STM_EDGE_CASING_EXTRA + ) + assert int(ck['zorder']) < int(fk['zorder']) + assert casing['posA'] == fg['posA'] + assert casing['posB'] == fg['posB'] + assert ck['connectionstyle'] == fk['connectionstyle'] + assert ck['shrinkA'] == fk['shrinkA'] + assert ck['shrinkB'] == fg['kwargs']['shrinkB'] + assert ck['arrowstyle'] == fk['arrowstyle'] + src, dst = edge['src'], edge['dst'] + assert ck['shrinkA'] == pytest.approx( + stm_edge_shrink_points(stm_node_marker_size(occupancy[src])) + ) + assert ck['shrinkB'] == pytest.approx( + stm_edge_shrink_points(stm_node_marker_size(occupancy[dst])) + ) + assert float(fk['linewidth']) == pytest.approx( + stm_edge_linewidth(edge['value']) + ) + assert float(ck['linewidth']) == pytest.approx( + stm_edge_linewidth(edge['value']) + _STM_EDGE_CASING_EXTRA + ) + assert not (tmp_path / '0' / 'state_transition_map.png').exists() + + +def test_deterministic_layout_from_identical_inputs(): + names = ['A', 'B', 'C', 'D'] + p1 = stm_circular_layout(names) + p2 = stm_circular_layout(names) + assert p1 == p2 + assert set(p1.keys()) == set(names) + # Two independent generate-derived layouts from same animal metrics. + m = stm_compute_animal_metrics(['A', 'B', 'C', 'A'], names) + pos_a = stm_circular_layout(m['observed_behaviors']) + pos_b = stm_circular_layout(m['observed_behaviors']) + assert pos_a == pos_b + + +def test_route_casing_clearance_avoids_unrelated_nodes(): + '''Visible casing half-width + radius + pad are cleared of non-endpoints.''' + # Chord A->C passes through B on the x-axis; route must bow around B. + node_centers = { + 'A': (0.0, 0.0), + 'B': (1.0, 0.0), + 'C': (2.0, 0.0), + } + node_radii = {'A': 0.15, 'B': 0.20, 'C': 0.15} + half_w = 0.08 + pad = 0.03 + route = stm_select_edge_route( + 0.0, 0.0, 2.0, 0.0, 'A', 'C', 0.12, + node_centers, node_radii, half_w, pad, [], + ) + assert route['clearance'] >= 0.0 + assert route['pass_behind'] is False + obstacles = {'B': node_centers['B']} + clear = stm_route_node_clearance( + route['polyline'], + obstacles, + {'B': node_radii['B']}, + half_w, + pad, + ) + assert clear >= 0.0 + assert clear == pytest.approx(route['clearance']) + assert stm_visible_edge_halfwidth_pt(1.0) > 0.5 + + +def test_clear_route_remains_fully_solid(): + node_centers = {'A': (0.0, 0.0), 'B': (2.0, 0.0)} + node_radii = {'A': 0.15, 'B': 0.15} + route = stm_select_edge_route( + 0.0, 0.0, 2.0, 0.0, 'A', 'B', 0.12, + node_centers, node_radii, 0.05, 0.02, [], + ) + assert route['pass_behind'] is False + assert route['crossed_nodes'] == [] + pieces = stm_pass_behind_path_pieces( + 0.0, 0.0, 2.0, 0.0, route['rad'], [], 0.05, + ) + assert pieces + assert all(p['style'] == 'solid' for p in pieces) + + +def test_forced_no_clear_route_uses_pass_behind_not_raise(): + '''Oversized mid-node forces pass-behind; no RuntimeError.''' + node_centers = { + 'A': (0.0, 0.0), + 'B': (1.0, 0.0), + 'C': (2.0, 0.0), + } + node_radii = {'A': 0.1, 'B': 1.5, 'C': 0.1} + route = stm_select_edge_route( + 0.0, 0.0, 2.0, 0.0, 'A', 'C', 0.12, + node_centers, node_radii, 0.2, 0.1, [], + ) + assert route['pass_behind'] is True + assert 'B' in route['crossed_nodes'] + assert abs(route['rad']) <= _STM_ROUTE_REASONABLE_MAX + 1e-12 + assert max(abs(r) for r in stm_edge_route_reasonable_rads(0.12)) <= ( + _STM_ROUTE_REASONABLE_MAX + 1e-12 + ) + + +def test_pass_behind_hides_center_and_dashes_at_boundary(): + x1, y1, x2, y2 = 0.0, 0.0, 2.0, 0.0 + rad = 0.0 # straight through mid node + node_centers = { + 'A': (0.0, 0.0), + 'B': (1.0, 0.0), + 'C': (2.0, 0.0), + } + node_radii = {'A': 0.1, 'B': 0.25, 'C': 0.1} + half_w, pad = 0.05, 0.02 + intervals = stm_route_obstacle_t_intervals( + x1, y1, x2, y2, rad, {'B': (1.0, 0.0)}, {'B': 0.25}, half_w, pad, + ) + assert intervals + assert intervals[0][0] == 'B' + t_enter, t_exit = intervals[0][1], intervals[0][2] + assert 0.0 < t_enter < 0.5 < t_exit < 1.0 + pieces = stm_pass_behind_path_pieces( + x1, y1, x2, y2, rad, intervals, 0.06, + ) + styles = [p['style'] for p in pieces] + assert 'dash' in styles + assert 'solid' in styles + # No sample points deep inside the node disk. + r = 0.25 + half_w + pad + for piece in pieces: + for px, py in piece['points']: + assert math.hypot(px - 1.0, py - 0.0) + 1e-9 >= r * 0.85 + # Dash pieces should sit near enter/exit. + dash_mid_ts = [] + for piece in pieces: + if piece['style'] != 'dash': + continue + mx = sum(p[0] for p in piece['points']) / len(piece['points']) + # Straight chord: x ≈ 2t + dash_mid_ts.append(mx / 2.0) + assert any(abs(t - t_enter) < 0.15 for t in dash_mid_ts) + assert any(abs(t - t_exit) < 0.15 for t in dash_mid_ts) + + +def test_pass_behind_multiple_crossed_nodes(): + x1, y1, x2, y2 = 0.0, 0.0, 3.0, 0.0 + rad = 0.0 + obstacles = {'B': (1.0, 0.0), 'D': (2.0, 0.0)} + radii = {'B': 0.2, 'D': 0.2} + half_w, pad = 0.04, 0.01 + intervals = stm_route_obstacle_t_intervals( + x1, y1, x2, y2, rad, obstacles, radii, half_w, pad, + ) + names = [iv[0] for iv in intervals] + assert names == sorted(names) + assert 'B' in names and 'D' in names + pieces = stm_pass_behind_path_pieces( + x1, y1, x2, y2, rad, intervals, 0.04, + ) + assert sum(1 for p in pieces if p['style'] == 'dash') >= 2 + + +def test_pass_behind_preserves_probability_count_and_direction(tmp_path, monkeypatch): + import matplotlib.pyplot as plt + monkeypatch.setattr(plt, 'savefig', lambda *a, **k: None) + # Force pass-behind on A->C through large mid occupancy node. + labels = ['A', 'C', 'A', 'C'] + ['B'] * 20 + metrics = stm_compute_animal_metrics(labels, ['A', 'B', 'C']) + # Place B between A and C on a line-like layout. + positions = { + 'A': (0.0, 0.0), + 'B': (1.0, 0.0), + 'C': (2.0, 0.0), + } + # Inflate B by high occupancy when drawing radii; force route pass-behind + # via select API with fat radius. + max_edge = 1.0 + routes = [] + for edge in stm_ordered_transition_edges( + metrics['observed_behaviors'], + metrics['count_matrix'], + metrics['probability_matrix'], + ): + route = stm_select_edge_route( + positions[edge['src']][0], + positions[edge['src']][1], + positions[edge['dst']][0], + positions[edge['dst']][1], + edge['src'], + edge['dst'], + 0.12, + positions, + {'A': 0.1, 'B': 1.2, 'C': 0.1}, + 0.15, + 0.05, + [], + ) + routes.append((edge, route)) + ac = [r for e, r in routes if e['src'] == 'A' and e['dst'] == 'C'] + if ac: + assert ac[0]['pass_behind'] is True + e = next(e for e, r in routes if e['src'] == 'A' and e['dst'] == 'C') + assert e['value'] > 0 + assert e['count'] >= 1 + # Drawing must not raise with fat mid node. + metrics_force = metrics + # Artificially huge marker for B only via occupancy after clone of radii path: + animal_dir = tmp_path / '0' + animal_dir.mkdir() + colors = {n: '#6B9FE0' for n in metrics['observed_behaviors']} + # Still use circular layout but pass-behind not guaranteed; at least draw. + _stm_draw_animal_map( + str(animal_dir), + 0, + metrics_force, + stm_circular_layout(metrics['observed_behaviors']), + colors, + dpi=72, + ) + + +def test_conditional_legend_pass_behind_only_when_used(tmp_path, monkeypatch): + import matplotlib.pyplot as plt + from LabGym import tools as tools_mod + + captured = [] + + real_text = plt.Axes.text + + def capturing_text(self, *args, **kwargs): + if args: + captured.append(args[2] if len(args) > 2 else kwargs.get('s', '')) + elif 's' in kwargs: + captured.append(kwargs['s']) + return real_text(self, *args, **kwargs) + + monkeypatch.setattr(plt.Axes, 'text', capturing_text) + monkeypatch.setattr(plt, 'savefig', lambda *a, **k: None) + + # Clear map: only A↔B — no third-node crossings expected. + m_clear = stm_compute_animal_metrics(['A', 'B', 'A', 'B'], ['A', 'B']) + dirs = tmp_path / 'clear' + dirs.mkdir() + _stm_draw_animal_map( + str(dirs), + 0, + m_clear, + stm_circular_layout(m_clear['observed_behaviors']), + {n: '#6B9FE0' for n in m_clear['observed_behaviors']}, + dpi=72, + ) + legend_clear = [t for t in captured if isinstance(t, str) and 'Node size' in t] + assert legend_clear + assert _STM_PASS_BEHIND_LEGEND not in legend_clear[-1] + + # Force pass-behind by making final-transform clearance check always fail + # (flags any_pass_behind and appends the conditional legend line). + captured.clear() + + monkeypatch.setattr( + tools_mod, + 'stm_route_node_clearance', + lambda *a, **k: -0.05, + ) + monkeypatch.setattr( + tools_mod, + 'stm_route_crossed_nodes', + lambda *a, **k: ['forced'], + ) + dirp = tmp_path / 'pass' + dirp.mkdir() + _stm_draw_animal_map( + str(dirp), + 1, + m_clear, + stm_circular_layout(m_clear['observed_behaviors']), + {n: '#6B9FE0' for n in m_clear['observed_behaviors']}, + dpi=72, + ) + legend_pass = [t for t in captured if isinstance(t, str) and 'Node size' in t] + assert legend_pass + assert _STM_PASS_BEHIND_LEGEND in legend_pass[-1] + assert _STM_PASS_BEHIND_LEGEND == ( + 'Dashed segment = edge passes behind a node.' + ) + + +def test_multi_animal_continues_without_routing_exception(tmp_path, monkeypatch): + import matplotlib.pyplot as plt + monkeypatch.setattr(plt, 'savefig', lambda *a, **k: None) + event_probability = { + 0: [['A', 0.9], ['B', 0.9], ['A', 0.9]], + 1: [['X', 0.9], ['Y', 0.9], ['Z', 0.9], ['X', 0.9]], + } + # Mid-node dense chain animal should not abort package. + event_probability[1] = ( + [['A', 0.9], ['C', 0.9]] * 3 + + [['B', 0.9]] * 30 + ) + result = plot_state_transition_map( + str(tmp_path / 'stm'), + event_probability, + ['A', 'B', 'C'], + behavior_colors={ + 'A': '#6B9FE0', + 'B': '#DD8452', + 'C': '#55A868', + }, + draw_maps=True, + map_dpi=72, + ) + assert result['status'] in ('success', 'warning_partial', 'warning_no_maps') + assert result.get('maps_written', 0) >= 1 + + +def test_route_selection_deterministic(): + node_centers = {'A': (0.0, 0.0), 'B': (1.0, 0.5), 'C': (2.0, 0.0)} + node_radii = {'A': 0.15, 'B': 0.15, 'C': 0.15} + kwargs = dict( + x1=0.0, y1=0.0, x2=2.0, y2=0.0, src='A', dst='C', + seed_magnitude=0.12, + node_centers=node_centers, node_radii=node_radii, + half_width_data=0.05, pad_data=0.02, selected_polylines=[], + ) + r1 = stm_select_edge_route(**kwargs) + r2 = stm_select_edge_route(**kwargs) + assert r1['rad'] == r2['rad'] + assert r1['clearance'] == r2['clearance'] + assert r1['pass_behind'] == r2['pass_behind'] + + +def test_micro_crossing_interval_expanded_hidden_with_dashes(): + '''Single-sample real crossing must yield a hide interval and dash segments.''' + x1, y1, x2, y2 = 0.0, 0.0, 2.0, 0.0 + rad = 0.0 + n = _STM_ROUTE_SAMPLE_N * 2 + # Neighbor sample spacing on the chord is 2/n data units; choose R so only + # the exact midpoint sample lies inside the reserved disk (micro-hit). + r_disk = (2.0 / float(n)) * 0.49 + half_w = 0.0 + pad = 0.0 + obstacles = {'M': (1.0, 0.0)} + radii = {'M': r_disk} + # Raw hits: exactly one sample inside when sampling with n. + inside_count = 0 + for i in range(n + 1): + t = i / float(n) + px, py, _, _ = stm_arc3_point_and_tangent(x1, y1, x2, y2, rad, t) + if math.hypot(px - 1.0, py - 0.0) < r_disk + half_w + pad: + inside_count += 1 + assert inside_count == 1 + + intervals = stm_route_obstacle_t_intervals( + x1, y1, x2, y2, rad, obstacles, radii, half_w, pad, n=n, + ) + assert intervals, 'micro-crossing interval must not be discarded' + assert intervals[0][0] == 'M' + t_enter, t_exit = intervals[0][1], intervals[0][2] + assert t_exit > t_enter + 1e-9 + assert t_exit - t_enter + 1e-12 >= min( + _STM_PASS_BEHIND_MIN_INTERVAL_DT, 1.0 / float(n), + ) + assert 0.0 <= t_enter < 0.5 < t_exit <= 1.0 + + dash_dt = 0.05 + pieces = stm_pass_behind_path_pieces( + x1, y1, x2, y2, rad, intervals, dash_dt, n=n, + ) + styles = [p['style'] for p in pieces] + assert 'dash' in styles + assert 'solid' in styles + # Covered center at t=0.5 must not appear in any drawn polyline point. + r_reserved = r_disk + half_w + pad + for piece in pieces: + for px, py in piece['points']: + assert math.hypot(px - 1.0, py - 0.0) + 1e-9 >= r_reserved * 0.5 + # At least one sample on the curve midpoint is in the expanded hidden band. + assert t_enter - 1e-12 <= 0.5 <= t_exit + 1e-12 + + +def test_final_transform_reselection_picks_clear_alternate_rad(tmp_path, monkeypatch): + ''' + Real axes + clearance: preliminary rad can fail after bounds expand while + another reasonable rad remains clear; final routing must reselect it. + ''' + import matplotlib.pyplot as plt + from LabGym import tools as tools_mod + + monkeypatch.setattr(plt, 'savefig', lambda *a, **k: None) + + fig = plt.figure(figsize=(6, 6), dpi=72) + ax = fig.add_subplot(111) + ax.set_aspect('equal') + centers = {'A': (0.0, 0.0), 'M': (1.0, 0.0), 'B': (2.0, 0.0)} + occ = {'A': 0.15, 'M': 0.15, 'B': 0.15} + lw_pt = 1.5 + + def radii_pad_half(): + fig.canvas.draw() + pad = _STM_ROUTE_NODE_PAD_PT * _stm_data_units_per_point(ax) + radii = { + name: _stm_node_radius_data(ax, stm_node_marker_size(occ[name])) + for name in centers + } + half_w = stm_edge_halfwidth_data( + ax, stm_visible_edge_halfwidth_pt(lw_pt), + ) + return radii, pad, half_w + + # Preliminary (tight) transform: select a mild clear rad. + ax.set_xlim(-0.2, 2.2) + ax.set_ylim(-0.15, 0.15) + rad_p, pad_p, half_p = radii_pad_half() + preliminary = stm_select_edge_route( + 0.0, 0.0, 2.0, 0.0, 'A', 'B', 0.12, + centers, rad_p, half_p, pad_p, [], + ) + assert preliminary['pass_behind'] is False + prelim_rad = preliminary['rad'] + + # Final (expanded) transform: that same rad is no longer clear, but another + # reasonable rad still clears the mid node under real geometry. + ax.set_xlim(-0.2, 2.2) + ax.set_ylim(-1.8, 1.8) + rad_f, pad_f, half_f = radii_pad_half() + obst = {'M': centers['M']} + obst_r = {'M': rad_f['M']} + poly_prelim = _stm_sample_arc3_polyline( + 0.0, 0.0, 2.0, 0.0, prelim_rad, n=_STM_ROUTE_SAMPLE_N, + ) + clear_prelim_final = stm_route_node_clearance( + poly_prelim, obst, obst_r, half_f, pad_f, + ) + assert clear_prelim_final < 0.0, ( + 'fixture requires preliminary rad invalid under final transform' + ) + clear_alts = [] + for rad in stm_edge_route_reasonable_rads(0.12): + poly = _stm_sample_arc3_polyline( + 0.0, 0.0, 2.0, 0.0, rad, n=_STM_ROUTE_SAMPLE_N, + ) + c = stm_route_node_clearance(poly, obst, obst_r, half_f, pad_f) + if c >= 0.0: + clear_alts.append(rad) + assert clear_alts, 'fixture needs a clear alternate reasonable rad' + + # Full reselection under final transform (production ranking) — not demote. + final = stm_select_edge_route( + 0.0, 0.0, 2.0, 0.0, 'A', 'B', 0.12, + centers, rad_f, half_f, pad_f, [], + ) + assert final['pass_behind'] is False + assert final['rad'] in clear_alts + assert final['clearance'] >= 0.0 + assert final['rad'] != prelim_rad + + # Draw path records real select calls: last A→B selection must be clear. + recorded = [] + real_select = tools_mod.stm_select_edge_route + + def recording_select(*args, **kwargs): + route = real_select(*args, **kwargs) + # args: x1,y1,x2,y2,src,dst,... + src = args[4] if len(args) > 4 else kwargs.get('src') + dst = args[5] if len(args) > 5 else kwargs.get('dst') + item = dict(route) + item['_src'] = src + item['_dst'] = dst + recorded.append(item) + return route + + monkeypatch.setattr(tools_mod, 'stm_select_edge_route', recording_select) + + # Occupancy close to the geometric fixture (~0.15 mid among endpoints). + labels = ['A'] * 5 + ['M'] * 2 + ['B'] * 5 + ['A', 'B'] * 4 + metrics = stm_compute_animal_metrics(labels, ['A', 'M', 'B']) + assert metrics['status'] == 'ok' + positions = {'A': (0.0, 0.0), 'M': (1.0, 0.0), 'B': (2.0, 0.0)} + animal_dir = tmp_path / 'reselect' + animal_dir.mkdir() + _stm_draw_animal_map( + str(animal_dir), + 0, + metrics, + positions, + {name: '#6B9FE0' for name in metrics['observed_behaviors']}, + dpi=72, + ) + ab_selects = [ + r for r in recorded if r.get('_src') == 'A' and r.get('_dst') == 'B' + ] + assert ab_selects, 'draw must route the A→B edge' + final_ab = ab_selects[-1] + assert final_ab['pass_behind'] is False + assert final_ab['clearance'] >= 0.0 + # If the last pick still used the invalid prelim rad, clearance would be < 0 + # under final-transform-like wide radii — the reselection result must clear. + assert final_ab['rad'] in ( + list(stm_edge_route_reasonable_rads(0.12)) + ) + plt.close(fig) + + +def test_conservative_envelope_fallback_when_convergence_hits_limit( + tmp_path, monkeypatch, +): + ''' + Ordinary select/bounds loop hit its max → conservative envelope applied once, + final selection under that transform, routes+casing fit final axes. + ''' + import matplotlib.pyplot as plt + from LabGym import tools as tools_mod + + # Force ordinary convergence to exhaust after one non-matching iteration. + monkeypatch.setattr(tools_mod, '_STM_ROUTE_CONVERGENCE_MAX', 1) + monkeypatch.setattr(plt, 'savefig', lambda *a, **k: None) + + envelope_calls = [] + real_envelope = tools_mod.stm_route_conservative_envelope_bounds + + def tracking_envelope(*args, **kwargs): + bounds = real_envelope(*args, **kwargs) + envelope_calls.append(tuple(float(v) for v in bounds)) + return bounds + + monkeypatch.setattr( + tools_mod, 'stm_route_conservative_envelope_bounds', tracking_envelope, + ) + + select_events = [] + real_select = tools_mod.stm_select_edge_route + + def tracking_select(*args, **kwargs): + # Snapshot active map axes limits if present. + import matplotlib.pyplot as _plt + lim = None + for num in _plt.get_fignums(): + fig = _plt.figure(num) + for ax in fig.axes: + if ax.get_aspect() == 'equal' or True: + lim = ( + float(ax.get_xlim()[0]), + float(ax.get_xlim()[1]), + float(ax.get_ylim()[0]), + float(ax.get_ylim()[1]), + ) + break + route = real_select(*args, **kwargs) + src = args[4] if len(args) > 4 else kwargs.get('src') + dst = args[5] if len(args) > 5 else kwargs.get('dst') + select_events.append({ + 'src': src, + 'dst': dst, + 'limits': lim, + 'rad': route['rad'], + 'pass_behind': route['pass_behind'], + 'polyline': list(route['polyline']), + }) + return route + + monkeypatch.setattr(tools_mod, 'stm_select_edge_route', tracking_select) + + labels = ['A', 'B', 'A', 'C', 'B', 'A'] + metrics = stm_compute_animal_metrics(labels, ['A', 'B', 'C']) + assert metrics['status'] == 'ok' + positions = stm_circular_layout(metrics['observed_behaviors']) + animal_dir = tmp_path / 'envelope' + animal_dir.mkdir() + + _stm_draw_animal_map( + str(animal_dir), + 0, + metrics, + positions, + {n: '#6B9FE0' for n in metrics['observed_behaviors']}, + dpi=72, + ) + + assert envelope_calls, 'conservative envelope fallback must be used' + envelope_limits = envelope_calls[-1] + + # After envelope, final edge selections must run under that applied transform. + n_edges = len(stm_ordered_transition_edges( + metrics['observed_behaviors'], + metrics['count_matrix'], + metrics['probability_matrix'], + )) + assert n_edges >= 1 + final_selects = select_events[-n_edges:] + assert len(final_selects) == n_edges + for ev in final_selects: + assert ev['limits'] is not None + # Final selection under fallback transform (matches envelope, not stale). + assert all( + abs(a - b) <= 1e-6 + for a, b in zip(ev['limits'], envelope_limits) + ) + + # Reconstruct final casing under a live axes transform matching envelope. + fig_chk = plt.figure(figsize=(_STM_FIGSIZE_MAP, _STM_FIGSIZE_MAP), dpi=72) + ax_chk = fig_chk.add_subplot(111) + ax_chk.set_aspect('equal') + ax_chk.set_xlim(envelope_limits[0], envelope_limits[1]) + ax_chk.set_ylim(envelope_limits[2], envelope_limits[3]) + fig_chk.canvas.draw() + selected_like = [{'polyline': ev['polyline']} for ev in final_selects] + ordered = stm_assign_edge_identifiers( + stm_ordered_transition_edges( + metrics['observed_behaviors'], + metrics['count_matrix'], + metrics['probability_matrix'], + ) + ) + halfs = [] + for edge in ordered: + lw = stm_edge_linewidth(edge['value']) + halfs.append( + stm_edge_halfwidth_data(ax_chk, stm_visible_edge_halfwidth_pt(lw)) + ) + assert stm_selected_routes_fit_axes_bounds( + selected_like, halfs, envelope_limits, + ) + plt.close(fig_chk) + + # Stale bounds: ordinary-loop selections used limits different from envelope. + early = [e for e in select_events[:-n_edges] if e['limits'] is not None] + assert early, 'ordinary loop must perform at least one selection pass' + assert any( + any(abs(a - b) > 1e-6 for a, b in zip(e['limits'], envelope_limits)) + for e in early + ), 'fallback must supersede stale ordinary-loop bounds' + + +def test_reciprocal_opposite_side_when_possible(): + node_centers = {'A': (0.0, 0.0), 'B': (2.0, 0.0)} + node_radii = {'A': 0.2, 'B': 0.2} + r1 = stm_select_edge_route( + 0.0, 0.0, 2.0, 0.0, 'A', 'B', _STM_EDGE_RAD_BIDIR, + node_centers, node_radii, 0.04, 0.01, [], + ) + r2 = stm_select_edge_route( + 2.0, 0.0, 0.0, 0.0, 'B', 'A', _STM_EDGE_RAD_BIDIR, + node_centers, node_radii, 0.04, 0.01, [r1['polyline']], + paired_sign=_stm_rad_sign(r1['rad']), + ) + assert r2['reciprocal_side_relaxed'] is False + assert _stm_rad_sign(r1['rad']) == _stm_rad_sign(r2['rad']) + mx1, my1, _, _ = stm_arc3_point_and_tangent(0.0, 0.0, 2.0, 0.0, r1['rad'], 0.5) + mx2, my2, _, _ = stm_arc3_point_and_tangent(2.0, 0.0, 0.0, 0.0, r2['rad'], 0.5) + assert my1 * my2 < 0.0 + + +def test_reciprocal_side_relaxed_when_no_opposite(): + '''When opposite side cannot hard-clear, relax but stay non-negative.''' + # Large obstacle on the positive-bow side of A->B; force first route +rad. + node_centers = { + 'A': (0.0, 0.0), + 'B': (2.0, 0.0), + # Obstacle largely blocking negative rad for reverse may force relax. + 'O': (1.0, -0.55), + } + node_radii = {'A': 0.15, 'B': 0.15, 'O': 0.45} + half_w, pad = 0.06, 0.02 + r1 = stm_select_edge_route( + 0.0, 0.0, 2.0, 0.0, 'A', 'B', 0.28, + node_centers, node_radii, half_w, pad, [], + ) + r2 = stm_select_edge_route( + 2.0, 0.0, 0.0, 0.0, 'B', 'A', 0.28, + node_centers, node_radii, half_w, pad, [r1['polyline']], + paired_sign=_stm_rad_sign(r1['rad']), + ) + assert r1['clearance'] >= 0.0 + assert r2['clearance'] >= 0.0 + # Either opposite-side success or documented relaxed fallback. + if r2['reciprocal_side_relaxed']: + assert r2['clearance'] >= 0.0 + else: + assert _stm_rad_sign(r1['rad']) == _stm_rad_sign(r2['rad']) + + +def test_clear_label_stays_on_curve(): + x1, y1, x2, y2 = 0.0, 0.0, 2.0, 0.0 + rad = 0.28 + placement = stm_place_edge_label( + x1, y1, x2, y2, rad, + {'A': (0.0, 0.0), 'B': (2.0, 0.0)}, + {'A': 0.15, 'B': 0.15}, + [], + [], + 0.08, + 0.04, + min_clearance_data=0.001, + units_per_point=0.01, + ) + assert placement['mode'] == 'on_curve' + px, py, _, _ = stm_arc3_point_and_tangent( + x1, y1, x2, y2, rad, placement['attach_t'], + ) + assert math.hypot(placement['x'] - px, placement['y'] - py) <= 1e-9 + + +def test_forced_low_clearance_uses_callout(): + x1, y1, x2, y2 = 0.0, 0.0, 2.0, 0.0 + rad = 0.35 + # Huge endpoint reserves + midpoint obstacle on curve force under-threshold. + node_centers = { + 'A': (0.0, 0.0), + 'B': (2.0, 0.0), + 'M': (1.0, 0.2), + } + node_radii = {'A': 0.9, 'B': 0.9, 'M': 0.8} + placement = stm_place_edge_label( + x1, y1, x2, y2, rad, + node_centers, + node_radii, + [], + [], + 0.25, + 0.12, + min_clearance_data=0.5, + units_per_point=0.02, + ) + assert placement['mode'] == 'callout' + + +def test_callout_attachment_is_best_maximin_oncurve_t(): + x1, y1, x2, y2 = 0.0, 0.0, 2.0, 0.0 + rad = 0.35 + node_centers = { + 'A': (0.0, 0.0), + 'B': (2.0, 0.0), + 'M': (1.0, 0.2), + } + node_radii = {'A': 0.9, 'B': 0.9, 'M': 0.8} + candidates = stm_evaluate_oncurve_label_candidates( + x1, y1, x2, y2, rad, + node_centers, node_radii, [], [], 0.25, 0.12, + ) + best = stm_best_oncurve_label_candidate(candidates) + placement = stm_place_edge_label( + x1, y1, x2, y2, rad, + node_centers, node_radii, [], [], + 0.25, 0.12, + min_clearance_data=0.5, + units_per_point=0.02, + ) + assert placement['mode'] == 'callout' + assert placement['attach_t'] == best['t'] + assert abs(placement['attach_x'] - best['x']) <= 1e-12 + assert abs(placement['attach_y'] - best['y']) <= 1e-12 + + +def test_callout_leader_segment_clears_prohibited_geometry(): + x1, y1, x2, y2 = 0.0, 0.0, 2.0, 0.0 + rad = 0.4 + node_centers = {'A': (0.0, 0.0), 'B': (2.0, 0.0)} + node_radii = {'A': 0.25, 'B': 0.25} + # Force callout by high threshold after packing nodes near curve. + placement = stm_place_edge_label( + x1, y1, x2, y2, rad, + node_centers, node_radii, [], [], + 0.2, 0.1, + min_clearance_data=0.35, + units_per_point=0.02, + ) + if placement['mode'] != 'callout': + # Escalate threshold until callout triggers for a stable fixture. + placement = stm_place_edge_label( + x1, y1, x2, y2, rad, + node_centers, node_radii, [], [], + 0.2, 0.1, + min_clearance_data=5.0, + units_per_point=0.02, + ) + assert placement['mode'] == 'callout' + # Leader samples (coarse) stay outside endpoint node radii. + steps = 12 + for i in range(steps + 1): + u = i / float(steps) + sx = placement['attach_x'] + u * (placement['x'] - placement['attach_x']) + sy = placement['attach_y'] + u * (placement['y'] - placement['attach_y']) + for name, (nx, ny) in node_centers.items(): + d = math.hypot(sx - nx, sy - ny) + assert d + 1e-9 >= node_radii[name] * 0.5 + + +def test_callout_placement_deterministic(): + kwargs = dict( + x1=0.0, y1=0.0, x2=2.0, y2=0.0, rad=0.35, + node_centers={'A': (0.0, 0.0), 'B': (2.0, 0.0), 'M': (1.0, 0.2)}, + node_radii={'A': 0.9, 'B': 0.9, 'M': 0.8}, + other_polylines=[], + placed_centers=[], + label_half_w=0.25, + label_half_h=0.12, + min_clearance_data=0.5, + units_per_point=0.02, + ) + p1 = stm_place_edge_label(**kwargs) + p2 = stm_place_edge_label(**kwargs) + assert p1 == p2 + + +def test_key_explain_exact_wording(): + assert _STM_KEY_EXPLAIN == 'Values show: transition probability (count)' + + +def test_key_vertical_pack_uses_point_gaps(): + p1 = stm_key_pack_y_positions(1) + p3 = stm_key_pack_y_positions(3) + assert p1['gap_pt'] == _STM_KEY_GAP_PT + assert p1['title'] > p1['explain'] > p1['body'] + # More body lines requires a taller region; compact pack stays ordered. + h1 = stm_key_region_height_inches(1) + h3 = stm_key_region_height_inches(3) + assert h3 > h1 + # Not the Iteration-2 fixed axes fractions. + assert p1['explain'] != pytest.approx(0.78) + assert p1['body'] != pytest.approx(0.58) + + +def test_routes_remain_valid_after_final_transform(tmp_path, monkeypatch): + '''Drawing completes under final bounds; routes stay within reasonable rads.''' + import matplotlib.pyplot as plt + monkeypatch.setattr(plt, 'savefig', lambda *a, **k: None) + + labels = ['A', 'B', 'C', 'A', 'C', 'B'] + metrics = stm_compute_animal_metrics(labels, ['A', 'B', 'C']) + positions = stm_circular_layout(metrics['observed_behaviors']) + colors = {n: '#6B9FE0' for n in metrics['observed_behaviors']} + animal_dir = tmp_path / '0' + animal_dir.mkdir() + _stm_draw_animal_map(str(animal_dir), 0, metrics, positions, colors, dpi=72) + + edges = stm_ordered_transition_edges( + metrics['observed_behaviors'], + metrics['count_matrix'], + metrics['probability_matrix'], + ) + node_centers = {b: positions[b] for b in metrics['observed_behaviors']} + node_radii = {b: 0.12 for b in metrics['observed_behaviors']} + selected = [] + pair_signs = {} + for edge in edges: + src, dst = edge['src'], edge['dst'] + x1, y1 = positions[src] + x2, y2 = positions[dst] + hw = 0.5 * ( + stm_edge_linewidth(edge['value']) + _STM_EDGE_CASING_EXTRA + ) * 0.01 + seed = stm_edge_rad(src, dst, metrics['count_matrix']) + pk = tuple(sorted((src, dst))) + route = stm_select_edge_route( + x1, y1, x2, y2, src, dst, seed, + node_centers, node_radii, hw, 0.02, + [e['polyline'] for e in selected], + paired_sign=pair_signs.get(pk), + ) + assert abs(route['rad']) <= _STM_ROUTE_REASONABLE_MAX + 1e-12 + if route['pass_behind']: + assert route['clearance'] < 0.0 + else: + assert route['clearance'] >= 0.0 + if src != dst and pk not in pair_signs: + pair_signs[pk] = _stm_rad_sign(route['rad']) + selected.append(route) diff --git a/LabGym/tests/test_triage_guards.py b/LabGym/tests/test_triage_guards.py new file mode 100644 index 00000000..eb71c14f --- /dev/null +++ b/LabGym/tests/test_triage_guards.py @@ -0,0 +1,797 @@ +"""Triage empty-plan, PDF preflight, package wrapper, and outcome helpers.""" + +from unittest.mock import MagicMock, patch + +import pytest + +from LabGym import mywx # noqa: F401 +import wx + +from LabGym.gui_categorizer import ( + reportlab_importable, + triage_assignment_counts, + TriageBuilderDialog, +) + + +@pytest.fixture(scope='module') +def wx_app(): + app = wx.App(False) + yield app + wx.CallAfter(app.ExitMainLoop) + app.MainLoop() + del app + wx.App._instance = None + + +def test_triage_assignment_counts_require_at_least_one(): + assert triage_assignment_counts(0, 0, 0) is False + assert triage_assignment_counts(1, 0, 0) is True + assert triage_assignment_counts(0, 2, 0) is True + assert triage_assignment_counts(0, 0, 3) is True + + +def test_reportlab_importable_true_in_review_env(): + ok, err = reportlab_importable() + assert ok is True + assert err is None + + +def _make_triage_dialog(wx_app, source_dataset_root=None, example_map=None): + parent = wx.Frame(None) + with patch.object(TriageBuilderDialog, 'init_ui', lambda self: None): + dlg = TriageBuilderDialog( + parent, + confusions_list=['a -> b (1 errors)'], + example_map=example_map or {('a', 'b'): ['/tmp/ds/a/x.avi']}, + report={'accuracy': 0.5, 'macro avg': {'f1-score': 0.5}}, + cm=[[1, 0], [0, 1]], + classnames=['a', 'b'], + embedding_map={}, + source_dataset_root=source_dataset_root, + ) + dlg.lb_h1 = MagicMock() + dlg.lb_h2 = MagicMock() + dlg.lb_h3 = MagicMock() + dlg.lb_h1.GetCount.return_value = 0 + dlg.lb_h2.GetCount.return_value = 0 + dlg.lb_h3.GetCount.return_value = 0 + return parent, dlg + + +def _src_with_classes(tmp_path, classes=('a', 'b')): + src = tmp_path / 'test' + for cls in classes: + (src / cls).mkdir(parents=True) + (src / cls / f'{cls}_only.avi').write_bytes(b'avi') + return src + + +def test_empty_plan_returns_before_name_dialog_and_copytree(wx_app): + parent, dlg = _make_triage_dialog(wx_app) + with patch('LabGym.gui_categorizer.wx.TextEntryDialog') as name_dlg: + with patch('LabGym.gui_categorizer.shutil.copytree') as copytree: + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + dlg.on_finish(None) + mb.assert_called_once() + assert mb.call_args[0][1] == 'Empty triage plan' + name_dlg.assert_not_called() + copytree.assert_not_called() + parent.Destroy() + + +def test_missing_reportlab_returns_before_clone(wx_app): + parent, dlg = _make_triage_dialog(wx_app) + dlg.lb_h1.GetCount.return_value = 1 + with patch('LabGym.gui_categorizer.reportlab_importable', return_value=(False, 'no module')): + with patch('LabGym.gui_categorizer.wx.TextEntryDialog') as name_dlg: + with patch('LabGym.gui_categorizer.shutil.copytree') as copytree: + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + dlg.on_finish(None) + assert mb.call_args[0][1] == 'Missing Dependency' + name_dlg.assert_not_called() + copytree.assert_not_called() + parent.Destroy() + + +def test_h1_file_collision_blocks_before_makedirs(wx_app, tmp_path): + src = _src_with_classes(tmp_path) + (src / 'a' / 'same.avi').write_bytes(b'a') + (src / 'b' / 'same.avi').write_bytes(b'b') + parent, dlg = _make_triage_dialog(wx_app, source_dataset_root=str(src)) + dlg.lb_h1.GetCount.return_value = 1 + dlg.lb_h1.GetString.return_value = 'a -> b (1 errors)' + + name_dlg = MagicMock() + name_dlg.ShowModal.return_value = wx.ID_OK + name_dlg.GetValue.return_value = 'pkg_out' + + with patch('LabGym.gui_categorizer.reportlab_importable', return_value=(True, None)): + with patch('LabGym.gui_categorizer.wx.TextEntryDialog', return_value=name_dlg): + with patch('LabGym.gui_categorizer.os.makedirs') as makedirs: + with patch('LabGym.gui_categorizer.shutil.copytree') as copytree: + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + dlg.on_finish(None) + assert mb.call_args[0][1] == 'H1 filename collision' + makedirs.assert_not_called() + copytree.assert_not_called() + assert not (tmp_path / 'pkg_out').exists() + parent.Destroy() + + +def test_h1_missing_class_blocks_before_mutation(wx_app, tmp_path): + src = tmp_path / 'test' + (src / 'a').mkdir(parents=True) + (src / 'a' / 'x.avi').write_bytes(b'a') + parent, dlg = _make_triage_dialog(wx_app, source_dataset_root=str(src)) + dlg.lb_h1.GetCount.return_value = 1 + dlg.lb_h1.GetString.return_value = 'a -> b (1 errors)' + + name_dlg = MagicMock() + name_dlg.ShowModal.return_value = wx.ID_OK + name_dlg.GetValue.return_value = 'pkg_out' + + with patch('LabGym.gui_categorizer.reportlab_importable', return_value=(True, None)): + with patch('LabGym.gui_categorizer.wx.TextEntryDialog', return_value=name_dlg): + with patch('LabGym.gui_categorizer.shutil.copytree') as copytree: + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + dlg.on_finish(None) + assert mb.call_args[0][1] == 'H1 class folder missing' + copytree.assert_not_called() + assert not (tmp_path / 'pkg_out').exists() + parent.Destroy() + + +def test_invalid_package_name_creates_no_package(wx_app, tmp_path): + src = _src_with_classes(tmp_path) + parent, dlg = _make_triage_dialog(wx_app, source_dataset_root=str(src)) + dlg.lb_h1.GetCount.return_value = 1 + dlg.lb_h1.GetString.return_value = 'a -> b (1 errors)' + + name_dlg = MagicMock() + name_dlg.ShowModal.return_value = wx.ID_OK + name_dlg.GetValue.return_value = 'bad/name' + + with patch('LabGym.gui_categorizer.reportlab_importable', return_value=(True, None)): + with patch('LabGym.gui_categorizer.wx.TextEntryDialog', return_value=name_dlg): + with patch('LabGym.gui_categorizer.shutil.copytree') as copytree: + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + dlg.on_finish(None) + assert mb.call_args[0][1] == 'Invalid Package Name' + copytree.assert_not_called() + parent.Destroy() + + +def test_pdf_failure_after_package_suppresses_full_success(wx_app, tmp_path): + src = _src_with_classes(tmp_path) + parent, dlg = _make_triage_dialog( + wx_app, + source_dataset_root=str(src), + example_map={('a', 'b'): [str(src / 'a' / 'a_only.avi')]}, + ) + dlg.lb_h1.GetCount.return_value = 1 + dlg.lb_h1.GetString.return_value = 'a -> b (1 errors)' + + name_dlg = MagicMock() + name_dlg.ShowModal.return_value = wx.ID_OK + name_dlg.GetValue.return_value = 'pkg_out' + + with patch('LabGym.gui_categorizer.reportlab_importable', return_value=(True, None)): + with patch('LabGym.gui_categorizer.wx.TextEntryDialog', return_value=name_dlg): + with patch.object(dlg, 'generate_pdf_report', return_value=(False, 'boom')): + with patch('LabGym.gui_categorizer.wx.BeginBusyCursor'): + with patch('LabGym.gui_categorizer.wx.EndBusyCursor'): + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + with patch.object(dlg, '_open_folder_safely') as open_folder: + dlg.on_finish(None) + titles = [c[0][1] for c in mb.call_args_list] + assert 'Partial triage outcome' in titles + assert 'Triage Complete' not in titles + open_folder.assert_not_called() + pkg = tmp_path / 'pkg_out' + assert pkg.is_dir() + assert (pkg / 'revised_sorted_test_examples').is_dir() + assert (pkg / 'LabGym_Diagnostics').is_dir() + assert (src / 'a' / 'a_only.avi').exists() + parent.Destroy() + + +def test_existing_destination_fails_without_overwrite(wx_app, tmp_path): + src = _src_with_classes(tmp_path) + parent, dlg = _make_triage_dialog(wx_app, source_dataset_root=str(src)) + dlg.lb_h1.GetCount.return_value = 1 + dlg.lb_h1.GetString.return_value = 'a -> b (1 errors)' + existing = tmp_path / 'pkg_out' + existing.mkdir() + marker = existing / 'keep.txt' + marker.write_text('safe') + + name_dlg = MagicMock() + name_dlg.ShowModal.return_value = wx.ID_OK + name_dlg.GetValue.return_value = 'pkg_out' + + with patch('LabGym.gui_categorizer.reportlab_importable', return_value=(True, None)): + with patch('LabGym.gui_categorizer.wx.TextEntryDialog', return_value=name_dlg): + with patch('LabGym.gui_categorizer.wx.BeginBusyCursor'): + with patch('LabGym.gui_categorizer.wx.EndBusyCursor'): + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + dlg.on_finish(None) + assert marker.read_text() == 'safe' + assert mb.call_args[0][1] == 'Package Exists' + assert 'Triage Complete' not in [c[0][1] for c in mb.call_args_list] + parent.Destroy() + + +def test_full_success_package_layout_and_opens_package_root(wx_app, tmp_path): + src = _src_with_classes(tmp_path) + parent, dlg = _make_triage_dialog( + wx_app, + source_dataset_root=str(src), + example_map={('a', 'b'): [str(src / 'a' / 'a_only.avi')]}, + ) + dlg.lb_h1.GetCount.return_value = 1 + dlg.lb_h1.GetString.return_value = 'a -> b (1 errors)' + dlg.lb_h2.GetCount.return_value = 0 + dlg.lb_h3.GetCount.return_value = 0 + + name_dlg = MagicMock() + name_dlg.ShowModal.return_value = wx.ID_OK + name_dlg.GetValue.return_value = 'pkg_out' + + def fake_pdf(path, name): + from pathlib import Path + Path(path).write_bytes(b'%PDF') + return True, None + + with patch('LabGym.gui_categorizer.reportlab_importable', return_value=(True, None)): + with patch('LabGym.gui_categorizer.wx.TextEntryDialog', return_value=name_dlg): + with patch.object(dlg, 'generate_pdf_report', side_effect=fake_pdf): + with patch('LabGym.gui_categorizer.wx.BeginBusyCursor'): + with patch('LabGym.gui_categorizer.wx.EndBusyCursor'): + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + with patch.object(dlg, 'EndModal'): + with patch.object(dlg, '_open_folder_safely', return_value=(True, None)) as open_folder: + dlg.on_finish(None) + + pkg = tmp_path / 'pkg_out' + revised = pkg / 'revised_sorted_test_examples' + diagnostics = pkg / 'LabGym_Diagnostics' + assert revised.is_dir() + assert diagnostics.is_dir() + assert not (revised / 'LabGym_Diagnostics').exists() + assert not (revised / 'a').exists() + assert (revised / 'b' / 'a_only.avi').exists() + assert (revised / 'b' / 'b_only.avi').exists() + assert (src / 'a' / 'a_only.avi').exists() + assert list(pkg.iterdir()) # package root opened, not diagnostics alone + open_folder.assert_called_once_with(str(pkg)) + success_msgs = [c[0][0] for c in mb.call_args_list if c[0][1] == 'Triage Complete'] + assert success_msgs + body = success_msgs[0] + assert str(pkg) in body + assert str(revised) in body + assert 'select this folder in LabGym' in body + assert 'categorizer_diagnostics_v1.pdf' in body + assert 'original source fixture was not modified' in body + parent.Destroy() + + +def test_copy_failure_reports_partial_package(wx_app, tmp_path): + src = _src_with_classes(tmp_path) + parent, dlg = _make_triage_dialog(wx_app, source_dataset_root=str(src)) + dlg.lb_h1.GetCount.return_value = 1 + dlg.lb_h1.GetString.return_value = 'a -> b (1 errors)' + + name_dlg = MagicMock() + name_dlg.ShowModal.return_value = wx.ID_OK + name_dlg.GetValue.return_value = 'pkg_out' + + with patch('LabGym.gui_categorizer.reportlab_importable', return_value=(True, None)): + with patch('LabGym.gui_categorizer.wx.TextEntryDialog', return_value=name_dlg): + with patch('LabGym.gui_categorizer.shutil.copytree', side_effect=OSError('disk full')): + with patch('LabGym.gui_categorizer.wx.BeginBusyCursor'): + with patch('LabGym.gui_categorizer.wx.EndBusyCursor'): + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + dlg.on_finish(None) + assert (tmp_path / 'pkg_out').is_dir() + assert mb.call_args[0][1] == 'System Error' + assert 'partial Triage Plan package' in mb.call_args[0][0] + assert 'Triage Complete' not in [c[0][1] for c in mb.call_args_list] + parent.Destroy() + + +def test_open_failure_after_success_does_not_delete_package(wx_app, tmp_path): + src = _src_with_classes(tmp_path) + parent, dlg = _make_triage_dialog(wx_app, source_dataset_root=str(src)) + dlg.lb_h1.GetCount.return_value = 1 + dlg.lb_h1.GetString.return_value = 'a -> b (1 errors)' + + name_dlg = MagicMock() + name_dlg.ShowModal.return_value = wx.ID_OK + name_dlg.GetValue.return_value = 'pkg_out' + + def fake_pdf(path, name): + from pathlib import Path + Path(path).write_bytes(b'%PDF') + return True, None + + with patch('LabGym.gui_categorizer.reportlab_importable', return_value=(True, None)): + with patch('LabGym.gui_categorizer.wx.TextEntryDialog', return_value=name_dlg): + with patch.object(dlg, 'generate_pdf_report', side_effect=fake_pdf): + with patch('LabGym.gui_categorizer.wx.BeginBusyCursor'): + with patch('LabGym.gui_categorizer.wx.EndBusyCursor'): + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + with patch.object(dlg, 'EndModal'): + with patch.object(dlg, '_open_folder_safely', return_value=(False, 'denied')): + dlg.on_finish(None) + titles = [c[0][1] for c in mb.call_args_list] + assert 'Triage Complete' in titles + assert 'Folder Open Failed' in titles + assert (tmp_path / 'pkg_out' / 'revised_sorted_test_examples').is_dir() + parent.Destroy() + + +def test_h2_does_not_create_class_or_move_examples(wx_app, tmp_path): + src = _src_with_classes(tmp_path) + parent, dlg = _make_triage_dialog(wx_app, source_dataset_root=str(src)) + dlg.lb_h1.GetCount.return_value = 0 + dlg.lb_h2.GetCount.return_value = 1 + dlg.lb_h2.GetString.return_value = 'a -> b (1 errors) [NEW: novel]' + dlg.lb_h3.GetCount.return_value = 0 + + name_dlg = MagicMock() + name_dlg.ShowModal.return_value = wx.ID_OK + name_dlg.GetValue.return_value = 'pkg_out' + + def fake_pdf(path, name): + from pathlib import Path + Path(path).write_bytes(b'%PDF') + return True, None + + with patch('LabGym.gui_categorizer.reportlab_importable', return_value=(True, None)): + with patch('LabGym.gui_categorizer.wx.TextEntryDialog', return_value=name_dlg): + with patch.object(dlg, 'generate_pdf_report', side_effect=fake_pdf): + with patch('LabGym.gui_categorizer.wx.BeginBusyCursor'): + with patch('LabGym.gui_categorizer.wx.EndBusyCursor'): + with patch('LabGym.gui_categorizer.wx.MessageBox'): + with patch.object(dlg, 'EndModal'): + with patch.object(dlg, '_open_folder_safely', return_value=(True, None)): + dlg.on_finish(None) + revised = tmp_path / 'pkg_out' / 'revised_sorted_test_examples' + assert (revised / 'a' / 'a_only.avi').exists() + assert (revised / 'b' / 'b_only.avi').exists() + assert not (revised / 'novel').exists() + parent.Destroy() + + +def test_h3_references_go_to_diagnostics_only(wx_app, tmp_path): + src = _src_with_classes(tmp_path) + avi = src / 'a' / 'a_only.avi' + jpg = src / 'a' / 'a_only.jpg' + jpg.write_bytes(b'jpg') + parent, dlg = _make_triage_dialog( + wx_app, + source_dataset_root=str(src), + example_map={('a', 'b'): [str(avi)]}, + ) + dlg.lb_h1.GetCount.return_value = 0 + dlg.lb_h2.GetCount.return_value = 0 + dlg.lb_h3.GetCount.return_value = 1 + dlg.lb_h3.GetString.return_value = 'a -> b (1 errors)' + + name_dlg = MagicMock() + name_dlg.ShowModal.return_value = wx.ID_OK + name_dlg.GetValue.return_value = 'pkg_out' + + def fake_pdf(path, name): + from pathlib import Path + Path(path).write_bytes(b'%PDF') + return True, None + + with patch('LabGym.gui_categorizer.reportlab_importable', return_value=(True, None)): + with patch('LabGym.gui_categorizer.wx.TextEntryDialog', return_value=name_dlg): + with patch.object(dlg, 'generate_pdf_report', side_effect=fake_pdf): + with patch('LabGym.gui_categorizer.wx.BeginBusyCursor'): + with patch('LabGym.gui_categorizer.wx.EndBusyCursor'): + with patch('LabGym.gui_categorizer.wx.MessageBox'): + with patch.object(dlg, 'EndModal'): + with patch.object(dlg, '_open_folder_safely', return_value=(True, None)): + with patch('random.sample', side_effect=lambda seq, k: list(seq)[:k]): + dlg.on_finish(None) + pkg = tmp_path / 'pkg_out' + h3 = pkg / 'LabGym_Diagnostics' / 'H3_Variance_References' + assert h3.is_dir() + assert list(h3.glob('*.avi')) + assert not (pkg / 'revised_sorted_test_examples' / 'H3_Variance_References').exists() + assert avi.exists() + parent.Destroy() + + +# --- CI #38: deferred analyzer imports --- + +_ANALYZER_MSG = ( + 'LabGym could not load the analysis components required for this Generate ' + 'Examples workflow. Verify that the LabGym environment and its required ' + 'dependencies are installed correctly, then try again.' +) +_ANALYZER_TITLE = 'Analysis dependency unavailable' + + +def test_gui_categorizer_import_does_not_load_analyzer_detector_stack(): + """Fresh interpreter: importing gui_categorizer must not newly load analyzer stack.""" + import os + import subprocess + import sys + from pathlib import Path + + script = ( + "import sys\n" + "before = set(sys.modules)\n" + "import LabGym.gui_categorizer # noqa: F401\n" + "after = set(sys.modules)\n" + "newly = after - before\n" + "forbidden = {\n" + " 'LabGym.analyzebehavior',\n" + " 'LabGym.analyzebehavior_dt',\n" + " 'LabGym.detector',\n" + " 'LabGym.detectron2.model_zoo',\n" + " 'torch',\n" + "}\n" + "hit = sorted(name for name in forbidden if name in newly)\n" + "if hit:\n" + " raise SystemExit('unexpected newly loaded: ' + ','.join(hit))\n" + "print('ok')\n" + ) + env = dict(os.environ) + env['PYTHONDONTWRITEBYTECODE'] = '1' + repo = str(Path(__file__).resolve().parents[2]) + proc = subprocess.run( + [sys.executable, '-c', script], + capture_output=True, + text=True, + env=env, + cwd=repo, + ) + assert proc.returncode == 0, proc.stdout + '\n' + proc.stderr + assert 'ok' in proc.stdout + + +def _analyzer_module_keys(): + return ( + 'LabGym.analyzebehavior', + 'LabGym.analyzebehavior_dt', + ) + + +def _stash_analyzer_modules(): + import sys + import LabGym + + stashed = {k: sys.modules.get(k) for k in _analyzer_module_keys()} + attrs = { + 'analyzebehavior': getattr(LabGym, 'analyzebehavior', _MISSING), + 'analyzebehavior_dt': getattr(LabGym, 'analyzebehavior_dt', _MISSING), + } + return stashed, attrs + + +_MISSING = object() + + +def _restore_analyzer_modules(stashed, attrs): + import sys + import LabGym + + for k, v in stashed.items(): + if v is None and k not in sys.modules: + continue + if v is None: + sys.modules.pop(k, None) + else: + sys.modules[k] = v + for name, val in attrs.items(): + if val is _MISSING: + if hasattr(LabGym, name): + delattr(LabGym, name) + else: + setattr(LabGym, name, val) + + +def _install_fake_analyzer(module_name, class_name, cls): + import sys + import types + import LabGym + + mod = types.ModuleType(module_name) + setattr(mod, class_name, cls) + sys.modules[module_name] = mod + short = module_name.rsplit('.', 1)[-1] + setattr(LabGym, short, mod) + return mod + + +def _install_bomb_analyzer(module_name): + """Module that fails loudly if imported for from-import of analyzer classes.""" + import sys + import types + import LabGym + + class Bomb(types.ModuleType): + def __getattr__(self, name): + raise AssertionError(f'unexpected attribute {module_name}.{name}') + + mod = Bomb(module_name) + sys.modules[module_name] = mod + short = module_name.rsplit('.', 1)[-1] + setattr(LabGym, short, mod) + return mod + + +def _raise_on_analyzer_import(exc): + """Make relative analyzer imports raise ImportError or OSError.""" + import builtins + + orig = builtins.__import__ + + def fake_import(name, globals=None, locals=None, fromlist=(), level=0): + if level > 0 and name in ('analyzebehavior', 'analyzebehavior_dt'): + raise exc + if name in ('LabGym.analyzebehavior', 'LabGym.analyzebehavior_dt'): + raise exc + return orig(name, globals, locals, fromlist, level) + + return patch('builtins.__import__', side_effect=fake_import) + + +def test_import_generate_examples_analyzer_import_error_shows_messagebox_once(): + from LabGym.gui_categorizer import import_generate_examples_analyzer + + with _raise_on_analyzer_import(ImportError('simulated missing analyzer')): + with patch('LabGym.gui_categorizer.logger') as log: + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + result = import_generate_examples_analyzer('animal') + assert result is None + assert mb.call_count == 1 + assert mb.call_args[0][0] == _ANALYZER_MSG + assert mb.call_args[0][1] == _ANALYZER_TITLE + assert log.exception.called + + +def test_import_generate_examples_analyzer_oserror_shows_messagebox(): + from LabGym.gui_categorizer import import_generate_examples_analyzer + + with _raise_on_analyzer_import(OSError('simulated native library failure')): + with patch('LabGym.gui_categorizer.logger') as log: + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + result = import_generate_examples_analyzer('detector') + assert result is None + assert mb.call_count == 1 + assert mb.call_args[0][0] == _ANALYZER_MSG + assert mb.call_args[0][1] == _ANALYZER_TITLE + assert log.exception.called + + +def test_import_generate_examples_analyzer_invalid_kind_raises(): + """Unknown kind must fail loudly without importing analyzers or showing UI.""" + import builtins + + from LabGym.gui_categorizer import import_generate_examples_analyzer + + seen = [] + orig_import = builtins.__import__ + + def spy_import(name, globals=None, locals=None, fromlist=(), level=0): + if level > 0 and name in ('analyzebehavior', 'analyzebehavior_dt'): + seen.append(name) + if name in ('LabGym.analyzebehavior', 'LabGym.analyzebehavior_dt'): + seen.append(name) + return orig_import(name, globals, locals, fromlist, level) + + with patch('builtins.__import__', side_effect=spy_import): + with patch('LabGym.gui_categorizer.logger') as log: + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + with pytest.raises(ValueError, match='animal.*detector'): + import_generate_examples_analyzer('not-a-valid-kind') + assert seen == [] + assert mb.call_count == 0 + assert not log.exception.called + + +def _make_generate_panel(wx_app): + from LabGym.gui_categorizer import PanelLv2_GenerateExamples + + parent = wx.Frame(None) + with patch.object(PanelLv2_GenerateExamples, 'display_window', lambda self: None): + with patch( + 'LabGym.gui_categorizer.config.get_config', + return_value={'detectors': '/tmp', 'models': '/tmp'}, + ): + panel = PanelLv2_GenerateExamples(parent) + panel.path_to_videos = ['/tmp/v.avi'] + panel.result_path = '/tmp/out' + panel.behavior_mode = 0 + panel.use_detector = False + panel.path_to_detector = '/tmp/det' + panel.animal_kinds = ['a'] + panel.animal_number = 1 + panel.framewidth = None + panel.detection_threshold = 0.5 + panel.background_free = True + panel.black_background = True + panel.include_bodyparts = False + panel.std = 0 + panel.delta = 1.2 + panel.stable_illumination = True + panel.background_path = None + panel.autofind_t = False + panel.t = 0 + panel.duration = 0 + panel.ex_start = 0 + panel.ex_end = None + panel.length = 15 + panel.animal_vs_bg = 1 + panel.skip_redundant = 0 + panel.social_distance = 0 + panel.decode_animalnumber = False + panel.decode_t = False + panel.decode_extraction = False + panel.color_costar = False + return parent, panel + + +def _patch_generate_dialogs(): + def factory(*a, **k): + d = MagicMock() + d.ShowModal.return_value = wx.ID_YES + d.GetValue.return_value = 0 + d.Destroy = MagicMock() + return d + + return ( + patch('LabGym.gui_categorizer.wx.MessageDialog', side_effect=factory), + patch('LabGym.gui_categorizer.wx.NumberEntryDialog', side_effect=factory), + ) + + +def test_generate_data_background_branch_imports_animal_only(wx_app): + """Background path imports AnalyzeAnimal from a test-scoped fake; detector stays unused.""" + from LabGym.gui_categorizer import import_generate_examples_analyzer + + parent, panel = _make_generate_panel(wx_app) + panel.use_detector = False + panel.behavior_mode = 0 + constructed = [] + + class FakeAnimal: + def __init__(self): + constructed.append('animal') + + def prepare_analysis(self, *a, **k): + pass + + def generate_data(self, **k): + pass + + def generate_data_interact_basic(self, **k): + pass + + stashed, attrs = _stash_analyzer_modules() + md, nd = _patch_generate_dialogs() + try: + _install_fake_analyzer('LabGym.analyzebehavior', 'AnalyzeAnimal', FakeAnimal) + _install_bomb_analyzer('LabGym.analyzebehavior_dt') + with md, nd: + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + # Prove helper returns the real symbol from the fake module. + cls = import_generate_examples_analyzer('animal') + assert cls is FakeAnimal + panel.generate_data(None) + assert constructed == ['animal'] + assert mb.call_count == 0 + finally: + _restore_analyzer_modules(stashed, attrs) + parent.Destroy() + + +def test_generate_data_video_detector_branch_imports_detector_only(wx_app): + parent, panel = _make_generate_panel(wx_app) + panel.use_detector = True + panel.behavior_mode = 0 + constructed = [] + + class FakeDet: + def __init__(self): + constructed.append('detector') + + def prepare_analysis(self, *a, **k): + pass + + def generate_data(self, **k): + pass + + def generate_data_interact_basic(self, **k): + pass + + def generate_data_interact_advance(self, **k): + pass + + stashed, attrs = _stash_analyzer_modules() + md, nd = _patch_generate_dialogs() + try: + _install_bomb_analyzer('LabGym.analyzebehavior') + _install_fake_analyzer('LabGym.analyzebehavior_dt', 'AnalyzeAnimalDetector', FakeDet) + with md, nd: + panel.generate_data(None) + assert constructed == ['detector'] + finally: + _restore_analyzer_modules(stashed, attrs) + parent.Destroy() + + +def test_generate_data_static_detector_branch_imports_detector(wx_app): + parent, panel = _make_generate_panel(wx_app) + panel.behavior_mode = 3 + panel.path_to_detector = '/tmp/det' + constructed = [] + + class FakeDet: + def __init__(self): + constructed.append('detector') + + def analyze_images_individuals(self, *a, **k): + pass + + stashed, attrs = _stash_analyzer_modules() + md, nd = _patch_generate_dialogs() + try: + _install_bomb_analyzer('LabGym.analyzebehavior') + _install_fake_analyzer('LabGym.analyzebehavior_dt', 'AnalyzeAnimalDetector', FakeDet) + with md, nd: + panel.generate_data(None) + assert constructed == ['detector'] + finally: + _restore_analyzer_modules(stashed, attrs) + parent.Destroy() + + +def test_generate_data_import_failure_returns_without_construct_or_repeat(wx_app): + parent, panel = _make_generate_panel(wx_app) + panel.use_detector = False + panel.path_to_videos = ['/tmp/a.avi', '/tmp/b.avi'] + constructed = [] + + md, nd = _patch_generate_dialogs() + with md, nd: + with _raise_on_analyzer_import(ImportError('simulated missing analyzer')): + with patch('LabGym.gui_categorizer.logger') as log: + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + panel.generate_data(None) + assert constructed == [] + assert mb.call_count == 1 + assert mb.call_args[0][0] == _ANALYZER_MSG + assert mb.call_args[0][1] == _ANALYZER_TITLE + assert log.exception.called + parent.Destroy() + + +def test_pyproject_declares_reportlab_min_5(): + from pathlib import Path + + text = (Path(__file__).resolve().parents[2] / 'pyproject.toml').read_text(encoding='utf-8') + assert "'reportlab>=5.0.0'" in text + assert text.count('reportlab') == 1 + + +def test_gui_categorizer_has_no_module_level_analyzer_imports(): + from pathlib import Path + import re + + text = (Path(__file__).resolve().parents[2] / 'LabGym' / 'gui_categorizer.py').read_text(encoding='utf-8') + # Imports before the deferred-import helper are module-level. + head = text.split('def import_generate_examples_analyzer', 1)[0] + assert 'from .analyzebehavior import AnalyzeAnimal' not in head + assert 'from .analyzebehavior_dt import AnalyzeAnimalDetector' not in head + # Helper performs both imports; Generate Examples has three call sites. + assert text.count("import_generate_examples_analyzer('detector')") == 2 + assert text.count("import_generate_examples_analyzer('animal')") == 1 + assert len(re.findall(r'from \.analyzebehavior(?:_dt)? import ', text)) == 2 diff --git a/LabGym/tests/test_triage_layout_pdf.py b/LabGym/tests/test_triage_layout_pdf.py new file mode 100644 index 00000000..b596992f --- /dev/null +++ b/LabGym/tests/test_triage_layout_pdf.py @@ -0,0 +1,92 @@ +"""Pure helpers for Triage Builder sizing, PDF allocation, and package naming.""" + +from pathlib import Path + +from LabGym import mywx # noqa: F401 + +from LabGym.gui_categorizer import ( + fit_dialog_client_size, + next_versioned_pdf_path, +) + + +def test_fit_dialog_preserves_nominal_on_large_work_area(): + assert fit_dialog_client_size(960, 720, 1920, 1080) == (960, 720) + + +def test_fit_dialog_clamps_to_margin_and_max_frac(): + w, h = fit_dialog_client_size(960, 720, 1000, 700, margin=40, max_frac=0.92) + assert w == min(960, 1000 - 80, int(1000 * 0.92)) + assert h == min(720, 700 - 80, int(700 * 0.92)) + assert w <= int(1000 * 0.92) + assert h <= int(700 * 0.92) + assert w <= 1000 - 80 + assert h <= 700 - 80 + + +def test_fit_dialog_returns_positive_integers_on_tiny_work_area(): + w, h = fit_dialog_client_size(960, 720, 50, 40, margin=40, max_frac=0.92) + assert isinstance(w, int) and isinstance(h, int) + assert w >= 1 and h >= 1 + assert w <= 50 and h <= 40 + + +def test_next_versioned_pdf_empty_directory_is_v1(tmp_path): + path = next_versioned_pdf_path(str(tmp_path)) + assert path == str(tmp_path / 'categorizer_diagnostics_v1.pdf') + + +def test_next_versioned_pdf_increments_from_existing_v1(tmp_path): + (tmp_path / 'categorizer_diagnostics_v1.pdf').write_bytes(b'pdf') + path = next_versioned_pdf_path(str(tmp_path)) + assert path.endswith('categorizer_diagnostics_v2.pdf') + assert not Path(path).exists() + + +def test_next_versioned_pdf_uses_max_plus_one_and_skips_gaps(tmp_path): + (tmp_path / 'categorizer_diagnostics_v1.pdf').write_bytes(b'a') + (tmp_path / 'categorizer_diagnostics_v3.pdf').write_bytes(b'b') + path = next_versioned_pdf_path(str(tmp_path)) + assert path.endswith('categorizer_diagnostics_v4.pdf') + + +def test_next_versioned_pdf_ignores_unrelated_and_case_mismatches(tmp_path): + (tmp_path / 'categorizer_diagnostics.pdf').write_bytes(b'x') + (tmp_path / 'categorizer_diagnostics_notes.pdf').write_bytes(b'x') + (tmp_path / 'categorizer_diagnostics_vx.pdf').write_bytes(b'x') + (tmp_path / 'Categorizer_diagnostics_v1.pdf').write_bytes(b'x') + (tmp_path / 'categorizer_diagnostics_v1').mkdir() + path = next_versioned_pdf_path(str(tmp_path)) + assert path.endswith('categorizer_diagnostics_v1.pdf') + + +def test_next_versioned_pdf_does_not_overwrite_existing(tmp_path): + existing = tmp_path / 'categorizer_diagnostics_v1.pdf' + existing.write_bytes(b'keep') + path = Path(next_versioned_pdf_path(str(tmp_path))) + assert path != existing + assert existing.read_bytes() == b'keep' + assert path.parent == tmp_path + + +def test_triage_builder_source_is_fixed_and_anchored(): + src = Path(__file__).resolve().parents[2] / 'LabGym' / 'gui_categorizer.py' + text = src.read_text(encoding='utf-8') + start = text.index('class TriageBuilderDialog') + body = text[start:text.index('def move_items', start)] + assert 'wx.RESIZE_BORDER' not in body + assert 'NOMINAL_CLIENT_SIZE = (960, 720)' in body + assert 'fit_dialog_client_size' in body + assert 'self.intro_lbl' in body + assert 'ops_help_html' in body + assert 'Finish and Generate Report' in body + assert 'wx.ID_CANCEL' in body + assert 'scientific decisions remain yours.' in body + ops_page_start = body.index('self.ops_help_html.SetPage') + assert 'scientific decisions remain yours' not in body[ops_page_start:] + assert 'next_versioned_pdf_path(diagnostics_dir)' in text + assert 'revised_sorted_test_examples' in text + assert 'source_dataset_root' in text + assert 'dataset_v2' not in text + assert 'Triage_Action_Plan.pdf' not in text + assert 'LabGym Triage Action Plan' in text diff --git a/LabGym/tests/test_triage_package_names.py b/LabGym/tests/test_triage_package_names.py new file mode 100644 index 00000000..6ad491e8 --- /dev/null +++ b/LabGym/tests/test_triage_package_names.py @@ -0,0 +1,169 @@ +"""Pure helpers for Triage Plan package naming and H1 collision preflight.""" + +from pathlib import Path + +from LabGym import mywx # noqa: F401 + +from LabGym.gui_categorizer import ( + collect_h1_filename_collisions, + next_versioned_triage_package_name, + sanitize_triage_package_base, + validate_triage_package_name, +) + + +def test_sanitize_source_test_becomes_test(): + assert sanitize_triage_package_base('test') == 'test' + + +def test_sanitize_strips_existing_trailing_triage_version(): + assert sanitize_triage_package_base('test_triage_v3') == 'test' + assert sanitize_triage_package_base('demo_triage_v12') == 'demo' + + +def test_sanitize_spaces_punctuation_and_collapses_underscores(): + assert sanitize_triage_package_base('my test!!set') == 'my_test_set' + assert sanitize_triage_package_base('a___b') == 'a_b' + assert sanitize_triage_package_base('a/b\\c:d*e') == 'a_b_c_d_e' + + +def test_sanitize_preserves_unicode_letters_and_digits(): + assert sanitize_triage_package_base('données_αβ_42') == 'données_αβ_42' + + +def test_sanitize_empty_falls_back(): + assert sanitize_triage_package_base('!!!') == 'sorted_test_examples' + assert sanitize_triage_package_base(' ') == 'sorted_test_examples' + + +def test_sanitize_truncates_to_eighty_before_suffix(): + long_name = 'x' * 100 + base = sanitize_triage_package_base(long_name) + assert len(base) == 80 + assert base == 'x' * 80 + + +def test_sanitize_windows_reserved_appends_data(): + assert sanitize_triage_package_base('CON') == 'CON_data' + assert sanitize_triage_package_base('com1') == 'com1_data' + assert sanitize_triage_package_base('LPT9') == 'LPT9_data' + + +def test_next_version_empty_parent_is_v1(tmp_path): + src = tmp_path / 'test' + src.mkdir() + assert next_versioned_triage_package_name(str(tmp_path), 'test') == 'test_triage_v1' + + +def test_next_version_increments_from_existing_v1(tmp_path): + (tmp_path / 'test_triage_v1').mkdir() + assert next_versioned_triage_package_name(str(tmp_path), 'test') == 'test_triage_v2' + + +def test_next_version_uses_max_plus_one_skips_gaps(tmp_path): + (tmp_path / 'test_triage_v1').mkdir() + (tmp_path / 'test_triage_v3').mkdir() + assert next_versioned_triage_package_name(str(tmp_path), 'test') == 'test_triage_v4' + + +def test_next_version_ignores_files_and_malformed_prefixes(tmp_path): + (tmp_path / 'test_triage_v1.txt').write_text('file') + (tmp_path / 'test_triage_vX').mkdir() + (tmp_path / 'test_triage').mkdir() + (tmp_path / 'other_triage_v1').mkdir() + (tmp_path / 'Test_triage_v1').mkdir() + assert next_versioned_triage_package_name(str(tmp_path), 'test') == 'test_triage_v1' + + +def test_next_version_does_not_create_or_overwrite(tmp_path): + existing = tmp_path / 'test_triage_v1' + existing.mkdir() + marker = existing / 'keep.txt' + marker.write_text('safe') + name = next_versioned_triage_package_name(str(tmp_path), 'test') + assert name == 'test_triage_v2' + assert marker.read_text() == 'safe' + assert not (tmp_path / name).exists() + + +def test_validate_rejects_invalid_user_names(tmp_path): + cases = [ + '', + ' ', + '.', + '..', + '/abs/path', + 'has/slash', + 'has\\slash', + 'bad:name', + 'trail.', + 'CON', + 'con.txt', + 'NUL', + ] + for name in cases: + ok, err = validate_triage_package_name(name) + assert ok is False, name + assert err + + +def test_validate_accepts_simple_basename(): + ok, err = validate_triage_package_name('test_triage_v1') + assert ok is True + assert err is None + + +def test_h1_collision_none(tmp_path): + src = tmp_path / 'src' + (src / 'a').mkdir(parents=True) + (src / 'b').mkdir() + (src / 'a' / 'x.avi').write_bytes(b'a') + (src / 'b' / 'y.avi').write_bytes(b'b') + collisions, missing = collect_h1_filename_collisions(str(src), [('a', 'b')]) + assert collisions == [] + assert missing == [] + + +def test_h1_file_collision_collected(tmp_path): + src = tmp_path / 'src' + (src / 'a').mkdir(parents=True) + (src / 'b').mkdir() + (src / 'a' / 'same.avi').write_bytes(b'a') + (src / 'b' / 'same.avi').write_bytes(b'b') + collisions, missing = collect_h1_filename_collisions(str(src), [('a', 'b')]) + assert missing == [] + assert len(collisions) == 1 + assert collisions[0]['pair'] == ('a', 'b') + assert collisions[0]['filenames'] == ['same.avi'] + + +def test_h1_directory_collision_collected(tmp_path): + src = tmp_path / 'src' + (src / 'a' / 'subdir').mkdir(parents=True) + (src / 'b' / 'subdir').mkdir(parents=True) + collisions, missing = collect_h1_filename_collisions(str(src), [('a', 'b')]) + assert missing == [] + assert collisions[0]['filenames'] == ['subdir'] + + +def test_h1_multiple_collisions_sorted(tmp_path): + src = tmp_path / 'src' + for cls in ('a', 'b', 'c', 'd'): + (src / cls).mkdir(parents=True) + (src / 'a' / 'z.avi').write_bytes(b'1') + (src / 'b' / 'z.avi').write_bytes(b'2') + (src / 'c' / 'm.avi').write_bytes(b'3') + (src / 'd' / 'm.avi').write_bytes(b'4') + (src / 'c' / 'a.avi').write_bytes(b'5') + (src / 'd' / 'a.avi').write_bytes(b'6') + collisions, missing = collect_h1_filename_collisions(str(src), [('c', 'd'), ('a', 'b')]) + assert missing == [] + assert [c['pair'] for c in collisions] == [('a', 'b'), ('c', 'd')] + assert collisions[1]['filenames'] == ['a.avi', 'm.avi'] + + +def test_h1_missing_class_reported(tmp_path): + src = tmp_path / 'src' + (src / 'a').mkdir(parents=True) + collisions, missing = collect_h1_filename_collisions(str(src), [('a', 'b')]) + assert ('target', 'b') in missing diff --git a/LabGym/tests/test_workflow_map_transform.py b/LabGym/tests/test_workflow_map_transform.py new file mode 100644 index 00000000..e0305e7b --- /dev/null +++ b/LabGym/tests/test_workflow_map_transform.py @@ -0,0 +1,18 @@ +"""AF regression: Workflow Map client-size transform (no live GUI windows).""" + +from LabGym import mywx # patch wx.App before any import of wx / gui_utils +from LabGym.gui_utils import compute_workflow_map_transform + + +def test_map_transform_uses_client_size(): + cw, ch, scale, ox, oy = compute_workflow_map_transform(1100, 560) + assert cw == 1100 and ch == 560 + assert abs(scale - min(1100 / 2200, 560 / 660)) < 1e-9 + assert abs(ox - (1100 - 2200 * scale) / 2) < 1e-9 + assert abs(oy - (560 - 660 * scale) / 2) < 1e-9 + + +def test_map_transform_tiny_client_falls_back(): + cw, ch, scale, ox, oy = compute_workflow_map_transform(0, 0) + assert cw == 1100 and ch == 560 + assert scale > 0 diff --git a/LabGym/tools.py b/LabGym/tools.py index 1bdc909c..0f4e91b0 100644 --- a/LabGym/tools.py +++ b/LabGym/tools.py @@ -28,6 +28,10 @@ import os import shutil +from matplotlib import lines, text +from black import lines +from skimage.measure import label + # Log the load of this module (by the module loader, on first import). # Intentionally positioning these statements before other imports, against the # guidance of PEP-8, to log the load before other imports log messages. @@ -45,7 +49,7 @@ import seaborn as sb from skimage import exposure logger.debug('importing tensorflow.keras.preprocessing.image (starting...)') -from tensorflow import keras # pylint: disable=unused-import +from tensorflow import keras, pad # pylint: disable=unused-import from keras.utils import img_to_array logger.debug('importing tensorflow.keras.preprocessing.image (done)') @@ -987,6 +991,2494 @@ def plot_events(result_path,event_probability,time_points,names_and_colors,behav print('The raster plot stored in: '+str(result_path)) +def stm_safe_animal_folder_name(animal_id): + '''Return a filesystem-safe animal package folder name (ID only).''' + raw = str(animal_id).strip() + safe = [] + for ch in raw: + if ch in '/\\:*?"<>|' or ord(ch) < 32: + safe.append('_') + else: + safe.append(ch) + name = ''.join(safe).rstrip(' .') + return name if name else 'unknown' + + +def stm_is_animal_package_dirname(name): + ''' + True if a directory basename is a legitimate STM animal package name. + + Accepts legacy animal_* names and ID-only names that could be produced by + stm_safe_animal_folder_name (digits and simple sanitized IDs). Rejects + arbitrary prose folder names so user content is not treated as packages. + ''' + if not name or name in ('.', '..') or name.startswith('.'): + return False + if name.startswith('animal_'): + return True + # ID-only: must already be filesystem-safe. + if name != stm_safe_animal_folder_name(name): + return False + # Narrow patterns: pure digit IDs (including negative) or simple alnum IDs. + if name.isdigit(): + return True + if len(name) > 1 and name[0] == '-' and name[1:].isdigit(): + return True + has_alnum = False + for ch in name: + if ch.isalnum(): + has_alnum = True + continue + if ch in '_-.': + continue + return False + return has_alnum + + +def stm_figure_id_subtitle(animal_id): + '''Second line of the map title (slightly smaller in the figure).''' + return 'ID ' + str(animal_id) + + +# Default fills must be either dark (L <= 0.15, white text >= 4.5:1) or +# light (L >= 0.28, black text >= 4.5:1); no mid-band defaults (0.15 < L < 0.28). +_STM_DEFAULT_COLOR_PALETTE = ( + # Light band (auto black text) + '#6B9FE0', + '#DD8452', + '#55A868', + '#E57373', + '#DA8BC3', + '#64B5CD', + '#CCB974', + '#90CAF9', + '#A5D6A7', + '#FFAB91', + # Dark band (auto white text) + '#0D47A1', + '#1B5E20', + '#B71C1C', + '#4A148C', + '#006064', +) + + +def stm_default_color_palette(): + '''Return the curated default behavior-color palette.''' + return _STM_DEFAULT_COLOR_PALETTE + + +def stm_default_behavior_color(behavior_name, index=0): + '''Deterministic default hex color for a behavior name.''' + palette = stm_default_color_palette() + if not palette: + return '#4C72B0' + # Prefer index when provided; fall back to stable hash for unknown order. + if index is not None and index >= 0: + return palette[index % len(palette)] + return palette[abs(hash(behavior_name)) % len(palette)] + + +def stm_get_hex_color(color_info): + '''Extract a #RRGGBB color from common LabGym color containers.''' + if isinstance(color_info, (list, tuple)): + for item in reversed(color_info): + if isinstance(item, str) and item.startswith('#') and len(item) == 7: + return item + if isinstance(color_info, str) and color_info.startswith('#') and len(color_info) == 7: + return color_info + return '#4C72B0' + + +def stm_hex_to_rgb01(hex_color): + '''Convert #RRGGBB to RGB floats in [0, 1].''' + h = stm_get_hex_color(hex_color).lstrip('#') + return tuple(int(h[i:i + 2], 16) / 255.0 for i in (0, 2, 4)) + + +def stm_relative_luminance(hex_color): + '''WCAG relative luminance for a hex color.''' + def channel(c): + return c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4 + + r, g, b = stm_hex_to_rgb01(hex_color) + return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b) + + +def stm_contrast_ratio(color_a, color_b): + '''WCAG contrast ratio between two hex colors.''' + l1 = stm_relative_luminance(color_a) + l2 = stm_relative_luminance(color_b) + lighter = max(l1, l2) + darker = min(l1, l2) + return (lighter + 0.05) / (darker + 0.05) + + +def stm_node_label_color(hex_color): + ''' + Choose black or white node-label text for readable contrast on fill. + + Uses WCAG luminance cut at 0.179 (maximizes contrast vs #000 / #FFF). + ''' + if stm_relative_luminance(hex_color) < 0.179: + return '#FFFFFF' + return '#000000' + + +def stm_hard_labels(events): + '''Return hard behavior labels only from event [name, probability] pairs.''' + labels = [] + for event in events: + if isinstance(event, (list, tuple)) and len(event) >= 1: + labels.append(event[0]) + else: + labels.append('NA') + return labels + + +def stm_compute_animal_metrics(hard_labels, included_behaviors): + ''' + Build bout segments, occupancy, and row-normalized transition metrics + for one animal from hard labels. + + included_behaviors: iterable of behavior names to keep on the map. + NA and any label not in included_behaviors create sequence breaks. + + Returns a dict with: + status: 'ok' or 'empty' + observed_behaviors, frame_counts, occupancy, bout_labels, segments, + count_matrix (DataFrame), probability_matrix (DataFrame with NaN for + zero-outgoing rows), transition_total, bout_total, included_frame_total + ''' + included = list(included_behaviors) + included_set = set(included) + frame_counts = {b: 0 for b in included} + segments = [] + current_bouts = [] + current_label = None + current_count = 0 + + def flush_bout(): + nonlocal current_label, current_count + if current_label is not None: + current_bouts.append(current_label) + current_label = None + current_count = 0 + + def flush_segment(): + nonlocal current_bouts + flush_bout() + if current_bouts: + segments.append(list(current_bouts)) + current_bouts = [] + + for label in hard_labels: + if label == 'NA' or label not in included_set: + flush_segment() + continue + frame_counts[label] += 1 + if current_label is None: + current_label = label + current_count = 1 + elif label == current_label: + current_count += 1 + else: + current_bouts.append(current_label) + current_label = label + current_count = 1 + flush_segment() + + included_frame_total = sum(frame_counts[b] for b in included) + bout_labels = [b for seg in segments for b in seg] + bout_total = len(bout_labels) + + if included_frame_total == 0: + return { + 'status': 'empty', + 'observed_behaviors': [], + 'frame_counts': {}, + 'occupancy': {}, + 'bout_labels': [], + 'segments': [], + 'count_matrix': None, + 'probability_matrix': None, + 'transition_total': 0, + 'bout_total': 0, + 'included_frame_total': 0, + } + + observed = sorted([b for b in included if frame_counts[b] > 0]) + occupancy = { + b: float(frame_counts[b]) / float(included_frame_total) + for b in observed + } + + n = len(observed) + name_to_idx = {name: i for i, name in enumerate(observed)} + counts = np.zeros((n, n), dtype=np.int64) + for seg in segments: + for i in range(len(seg) - 1): + src = seg[i] + dst = seg[i + 1] + counts[name_to_idx[src], name_to_idx[dst]] += 1 + + count_df = pd.DataFrame(counts, index=observed, columns=observed) + prob = np.full((n, n), np.nan, dtype=np.float64) + for i in range(n): + row_sum = int(counts[i, :].sum()) + if row_sum > 0: + prob[i, :] = counts[i, :].astype(np.float64) / float(row_sum) + prob_df = pd.DataFrame(prob, index=observed, columns=observed) + + return { + 'status': 'ok', + 'observed_behaviors': observed, + 'frame_counts': {b: int(frame_counts[b]) for b in observed}, + 'occupancy': occupancy, + 'bout_labels': bout_labels, + 'segments': segments, + 'count_matrix': count_df, + 'probability_matrix': prob_df, + 'transition_total': int(counts.sum()), + 'bout_total': bout_total, + 'included_frame_total': int(included_frame_total), + } + + +# Known STM artifacts inside a per-animal package (ID folder; current + obsolete names). +_STM_ANIMAL_KNOWN_FILES = frozenset({ + 'state_transition_map.png', + 'state_transition_counts.xlsx', + 'state_transition_probabilities.xlsx', + 'state_behavior_occupancy.xlsx', + 'state_transition_summary.xlsx', + 'state_transition_map_normalized.png', + 'state_transition_map_counts.png', + 'state_transition_observed_probability.xlsx', + 'state_transition_expected_probability.xlsx', + 'state_transition_normalized_enrichment.xlsx', + 'state_behavior_frequency.xlsx', +}) + +# Known obsolete/misplaced STM files at the STM results root only. +_STM_ROOT_OBSOLETE_FILES = frozenset({ + 'state_transition_map_normalized.png', + 'state_transition_map_counts.png', + 'state_transition_observed_probability.xlsx', + 'state_transition_expected_probability.xlsx', + 'state_transition_normalized_enrichment.xlsx', + 'state_behavior_frequency.xlsx', + 'state_transition_counts.xlsx', + 'state_transition_probabilities.xlsx', + 'state_behavior_occupancy.xlsx', + 'state_transition_summary.xlsx', + 'state_transition_map.png', + # legacy persistence artifacts from earlier STM drafts + 'state_transition_colors.json', + 'state_transition_layout.json', +}) + +# Drawing constants (static PNG readability). +_STM_NODE_SIZE_MIN = 2000.0 # scatter marker area; floor for legibility +_STM_NODE_SIZE_SPAN = 2800.0 # extra area at full occupancy +_STM_EDGE_LW_MIN = 0.7 +_STM_EDGE_LW_SPAN = 3.2 # previous max ~8.4 (0.4 + 8*sqrt); compressed +_STM_EDGE_SHRINK_PAD = 4.0 # points beyond node radius for endpoint trim +_STM_EDGE_MUTATION_SCALE = 28 # arrowhead size (linewidth independent) +_STM_EDGE_RAD_SINGLE = 0.12 # mild curve for one-direction edges +_STM_EDGE_RAD_BIDIR = 0.48 # stronger opposite bow for A↔B pairs +_STM_FIGSIZE_MAP = 11.5 # square map axes reference size (inches) +_STM_VIEW_PAD = 0.52 # data-space margin around fixed circular layout +# Obstacle-aware Arc3 routing. +_STM_ROUTE_SAMPLE_N = 48 +_STM_ROUTE_NODE_PAD_PT = 2.0 +# Reasonable Arc3 magnitudes only (no extreme bows just to dodge nodes). +_STM_ROUTE_INITIAL_MAGS = (0.12, 0.20, 0.28, 0.36, 0.48) +_STM_ROUTE_REASONABLE_MAX = 0.48 +# Bounds↔route reselection iterations (bounded deterministic convergence). +_STM_ROUTE_CONVERGENCE_MAX = 3 +_STM_ROUTE_LIMIT_EPS = 1e-9 +# Final selected geometry must fit active axes (data units). +_STM_ROUTE_BOUNDS_FIT_TOL = 1e-6 +# Minimum t-width for a detected pass-behind crossing (never drop micro-hits). +_STM_PASS_BEHIND_MIN_INTERVAL_DT = 1.0 / float(_STM_ROUTE_SAMPLE_N) +_STM_PASS_BEHIND_DASH_PT = 7.0 # dashed approach/exit length in typographic points +_STM_PASS_BEHIND_LEGEND = 'Dashed segment = edge passes behind a node.' +_STM_PASS_BEHIND_ZORDER = 1.5 +# Edge-label placement / callout fallback. +_STM_EDGE_LABEL_T = 0.55 # preferred fraction along curve (~50–60%) +_STM_EDGE_LABEL_MAX_ROTATION = 22.0 # restrained clamp (~±20–25°) for readability +_STM_EDGE_LABEL_BBOX_PAD = 0.48 +_STM_EDGE_LABEL_BBOX_EDGECOLOR = '#555555' +_STM_EDGE_LABEL_BBOX_LW = 0.5 +_STM_EDGE_LABEL_FONTSIZE = 8.0 +# Single-line on-map format: "T5 · 0.89 (8)" (U+00B7 middle dot with spaces). +_STM_EDGE_LABEL_MIDDOT = ' \u00b7 ' +_STM_EDGE_LABEL_T_CANDIDATES = (0.55, 0.50, 0.60, 0.45, 0.65, 0.40, 0.70) +_STM_LABEL_MIN_CLEARANCE_PT = 5.0 +_STM_CALLOUT_PERP_PT = (8.0, 12.0, 16.0, 22.0) +_STM_CALLOUT_ALONG_PT = (0.0, -4.0, 4.0, -8.0, 8.0) +_STM_EDGE_CASING_EXTRA = 2.2 # white underlay wider than black stroke (pt) +_STM_EDGE_CASING_ZORDER = 1 +_STM_EDGE_FOREGROUND_ZORDER = 2 +_STM_TITLE_FONTSIZE = 16.0 +_STM_TITLE_SUBTITLE_SCALE = 0.875 # ~87.5% of main title size +_STM_LEGEND_FONTSIZE = 7.5 +_STM_KEY_FONTSIZE = 8.5 +_STM_KEY_TITLE_FONTSIZE = 10.0 +_STM_KEY_LINE_SPACING = 1.20 +_STM_KEY_GAP_PT = 3.0 +_STM_KEY_TOP_MARGIN_PT = 4.0 +_STM_KEY_BOTTOM_MARGIN_PT = 6.0 +_STM_KEY_EXPLAIN = 'Values show: transition probability (count)' +_STM_LEGEND_TEXT = ( + 'Node size = time spent in each behavior\n' + ' (% of included frames)\n' + 'Edge width = probability of transitioning\n' + ' to the next behavior\n' + 'Edge label = T# and probability (count)\n' + 'Transition key lists each T# below' +) + + +def _stm_expand_micro_interval(t_enter, t_exit, min_dt): + '''Expand a near-zero [t_enter, t_exit] to at least min_dt, clamped to [0, 1].''' + t_enter = float(t_enter) + t_exit = float(t_exit) + if t_exit < t_enter: + t_enter, t_exit = t_exit, t_enter + min_dt = max(float(min_dt), 1e-9) + width = t_exit - t_enter + if width + 1e-12 >= min_dt: + return max(0.0, t_enter), min(1.0, t_exit) + mid = 0.5 * (t_enter + t_exit) + half = 0.5 * min_dt + t_enter = mid - half + t_exit = mid + half + if t_enter < 0.0: + t_enter = 0.0 + t_exit = min(1.0, t_enter + min_dt) + elif t_exit > 1.0: + t_exit = 1.0 + t_enter = max(0.0, t_exit - min_dt) + return t_enter, t_exit + + +def stm_marker_radius_points(marker_size): + '''Scatter marker radius in typographic points from marker area s.''' + return 0.5 * math.sqrt(max(float(marker_size), 1.0)) + + +def stm_edge_shrink_points(marker_size, pad=None): + '''FancyArrowPatch shrink (points) so the path meets the node boundary.''' + if pad is None: + pad = _STM_EDGE_SHRINK_PAD + return stm_marker_radius_points(marker_size) + float(pad) + + +def stm_arc3_quadratic_control(x1, y1, x2, y2, rad): + ''' + Control point for a matplotlib ConnectionStyle Arc3 quadratic Bezier. + + Matches FancyArrowPatch connectionstyle='arc3,rad=...'. + ''' + mid_x = (x1 + x2) / 2.0 + mid_y = (y1 + y2) / 2.0 + dx = x2 - x1 + dy = y2 - y1 + return mid_x + float(rad) * dy, mid_y - float(rad) * dx + + +def stm_arc3_point_and_tangent(x1, y1, x2, y2, rad, t): + '''Point and unit tangent on an Arc3 quadratic Bezier at parameter t.''' + t = max(0.0, min(1.0, float(t))) + rad = float(rad) + cx, cy = stm_arc3_quadratic_control(x1, y1, x2, y2, rad) + u = 1.0 - t + px = u * u * x1 + 2.0 * u * t * cx + t * t * x2 + py = u * u * y1 + 2.0 * u * t * cy + t * t * y2 + tx = 2.0 * u * (cx - x1) + 2.0 * t * (x2 - cx) + ty = 2.0 * u * (cy - y1) + 2.0 * t * (y2 - cy) + tlen = math.hypot(tx, ty) + if tlen < 1e-12: + tx, ty = (x2 - x1), (y2 - y1) + tlen = math.hypot(tx, ty) or 1.0 + return px, py, tx / tlen, ty / tlen + + +def stm_arc3_point_at_arclength(x1, y1, x2, y2, rad, target_len, from_end=False, n=64): + ''' + Point on an Arc3 curve after traveling target_len along the polyline sample. + + When from_end is True, travel backward from the destination. + ''' + pts = [] + for i in range(n + 1): + t = i / float(n) + px, py, _, _ = stm_arc3_point_and_tangent(x1, y1, x2, y2, rad, t) + pts.append((px, py, t)) + if from_end: + pts = list(reversed(pts)) + traveled = 0.0 + for i in range(len(pts) - 1): + x_a, y_a, _ = pts[i] + x_b, y_b, t_b = pts[i + 1] + seg = math.hypot(x_b - x_a, y_b - y_a) + if traveled + seg >= float(target_len): + remain = float(target_len) - traveled + if seg < 1e-18: + return x_a, y_a, pts[i][2] + u = remain / seg + return ( + x_a + u * (x_b - x_a), + y_a + u * (y_b - y_a), + t_b, + ) + traveled += seg + x_last, y_last, t_last = pts[-1] + return x_last, y_last, t_last + + +def stm_edge_label_rotation(tx, ty, max_deg=None): + ''' + Rotation (degrees) that follows the edge tangent but stays readable. + + Forces upright text (never upside down), then clamps to +/- max_deg. + ''' + if max_deg is None: + max_deg = _STM_EDGE_LABEL_MAX_ROTATION + max_deg = abs(float(max_deg)) + angle = math.degrees(math.atan2(float(ty), float(tx))) + # Choose the upright orientation in (-90, 90]. + if angle > 90.0: + angle -= 180.0 + elif angle < -90.0: + angle += 180.0 + if angle > max_deg: + angle = max_deg + elif angle < -max_deg: + angle = -max_deg + return angle + + +def stm_edge_label_placement(x1, y1, x2, y2, rad, t=None): + ''' + Anchor an edge label directly on its Arc3 curve (zero perpendicular offset). + + Collision handling may only vary ``t``. Returns (label_x, label_y, + rotation_deg) with |rotation| <= max clamp. + ''' + if t is None: + t = _STM_EDGE_LABEL_T + px, py, tx, ty = stm_arc3_point_and_tangent(x1, y1, x2, y2, rad, t) + return px, py, stm_edge_label_rotation(tx, ty) + + +def _stm_data_units_per_display_pixel(ax): + '''Approximate data units per display pixel (equal-aspect axes).''' + p0 = ax.transData.transform((0.0, 0.0)) + p1 = ax.transData.transform((1.0, 0.0)) + dist = math.hypot(float(p1[0] - p0[0]), float(p1[1] - p0[1])) + if dist < 1e-12: + return 0.01 + return 1.0 / dist + + +def _stm_data_units_per_point(ax): + '''Approximate data units per typographic point on equal-aspect axes.''' + return _stm_data_units_per_display_pixel(ax) * (float(ax.figure.dpi) / 72.0) + + +def _stm_node_radius_data(ax, marker_size): + '''Approximate scatter-marker radius in data units.''' + return stm_marker_radius_points(marker_size) * _stm_data_units_per_point(ax) + + +def _stm_sample_arc3_polyline(x1, y1, x2, y2, rad, n=18): + '''Sample Arc3 path as a polyline for proximity tests.''' + pts = [] + for i in range(n + 1): + t = i / float(n) + px, py, _, _ = stm_arc3_point_and_tangent(x1, y1, x2, y2, rad, t) + pts.append((px, py)) + return pts + + +def _stm_min_dist_to_polyline(x, y, polyline): + best = float('inf') + if not polyline: + return best + for i in range(len(polyline) - 1): + x1, y1 = polyline[i] + x2, y2 = polyline[i + 1] + dx = x2 - x1 + dy = y2 - y1 + den = dx * dx + dy * dy + if den < 1e-18: + d = math.hypot(x - x1, y - y1) + else: + u = max(0.0, min(1.0, ((x - x1) * dx + (y - y1) * dy) / den)) + d = math.hypot(x - (x1 + u * dx), y - (y1 + u * dy)) + if d < best: + best = d + return best + + +def stm_visible_edge_halfwidth_pt(linewidth_pt): + '''Outer half-width of the white casing (foreground + casing extra).''' + return 0.5 * (float(linewidth_pt) + _STM_EDGE_CASING_EXTRA) + + +def stm_edge_halfwidth_data(ax, halfwidth_pt): + '''Convert a stroke half-width in typographic points to data units.''' + return float(halfwidth_pt) * _stm_data_units_per_point(ax) + + +def _stm_rad_sign(rad): + if float(rad) < 0.0: + return -1 + return 1 + + +def _stm_unordered_pair_key(src, dst): + return tuple(sorted((src, dst))) + + +def stm_route_node_clearance( + polyline, + obstacle_centers, + obstacle_radii, + half_width_data, + pad_data, +): + ''' + Minimum clearance of a sampled curve against non-endpoint node obstacles. + + Clearance uses complete visible casing half-width plus node radius and pad. + ''' + if not obstacle_centers: + return float('inf') + best = float('inf') + hw = float(half_width_data) + pad = float(pad_data) + for px, py in polyline: + for name, (nx, ny) in obstacle_centers.items(): + r = float(obstacle_radii.get(name, 0.0)) + hw + pad + clearance = math.hypot(px - nx, py - ny) - r + if clearance < best: + best = clearance + return best + + +def _stm_orient(ax, ay, bx, by, cx, cy): + return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) + + +def _stm_segments_proper_intersect(a, b, c, d): + '''True when open segments ab and cd properly cross (not shared endpoints).''' + ax, ay = a + bx, by = b + cx, cy = c + dx, dy = d + o1 = _stm_orient(ax, ay, bx, by, cx, cy) + o2 = _stm_orient(ax, ay, bx, by, dx, dy) + o3 = _stm_orient(cx, cy, dx, dy, ax, ay) + o4 = _stm_orient(cx, cy, dx, dy, bx, by) + if o1 == 0 or o2 == 0 or o3 == 0 or o4 == 0: + return False + return (o1 > 0) != (o2 > 0) and (o3 > 0) != (o4 > 0) + + +def stm_polyline_segment_intersections(poly_a, poly_b): + '''Count proper open-segment crossings between two polylines.''' + if not poly_a or not poly_b: + return 0 + count = 0 + for i in range(len(poly_a) - 1): + for j in range(len(poly_b) - 1): + if _stm_segments_proper_intersect( + poly_a[i], + poly_a[i + 1], + poly_b[j], + poly_b[j + 1], + ): + count += 1 + return count + + +def stm_edge_route_signed_rads(magnitudes): + '''Expand magnitude list into fixed-order signed rad candidates (+m, -m).''' + seen = set() + out = [] + for mag in magnitudes: + m = abs(float(mag)) + if m < 1e-12 or m > _STM_ROUTE_REASONABLE_MAX + 1e-12: + continue + for signed in (m, -m): + key = round(signed, 12) + if key in seen: + continue + seen.add(key) + out.append(signed) + return out + + +def stm_edge_route_reasonable_rads(seed_magnitude): + '''Reasonable curvature candidates only (seed magnitude + mild ladder).''' + mags = [abs(float(seed_magnitude))] + for m in _STM_ROUTE_INITIAL_MAGS: + if abs(float(m) - mags[0]) > 1e-12: + mags.append(float(m)) + return stm_edge_route_signed_rads(mags) + + +def stm_route_crossed_nodes( + polyline, + obstacle_centers, + obstacle_radii, + half_width_data, + pad_data, +): + '''Names of unrelated nodes whose reserved disk is hit by the polyline.''' + crossed = [] + hw = float(half_width_data) + pad = float(pad_data) + for name, (nx, ny) in sorted(obstacle_centers.items()): + r = float(obstacle_radii.get(name, 0.0)) + hw + pad + for px, py in polyline: + if math.hypot(px - nx, py - ny) < r: + crossed.append(name) + break + return crossed + + +def stm_route_obstacle_t_intervals( + x1, + y1, + x2, + y2, + rad, + obstacle_centers, + obstacle_radii, + half_width_data, + pad_data, + n=None, +): + ''' + List of (node_name, t_enter, t_exit) for curve segments inside obstacle disks. + + Intervals sorted by t_enter; multiple unrelated nodes are supported. + Single-sample / near-zero hits are expanded to a minimum t-width so + pass-behind hide+dash never drops a detected crossing. + ''' + if n is None: + n = _STM_ROUTE_SAMPLE_N * 2 + hw = float(half_width_data) + pad = float(pad_data) + # At least one sample step and the global minimum hide window. + min_dt = max(_STM_PASS_BEHIND_MIN_INTERVAL_DT, 1.0 / float(max(n, 1))) + intervals = [] + for name, (nx, ny) in sorted(obstacle_centers.items()): + r = float(obstacle_radii.get(name, 0.0)) + hw + pad + inside = [] + for i in range(n + 1): + t = i / float(n) + px, py, _, _ = stm_arc3_point_and_tangent(x1, y1, x2, y2, rad, t) + inside.append(math.hypot(px - nx, py - ny) < r) + i = 0 + while i <= n: + if not inside[i]: + i += 1 + continue + start = i + while i <= n and inside[i]: + i += 1 + t_enter = start / float(n) + t_exit = (i - 1) / float(n) + t_enter, t_exit = _stm_expand_micro_interval(t_enter, t_exit, min_dt) + intervals.append((name, t_enter, t_exit)) + intervals.sort(key=lambda item: item[1]) + return intervals + + +def stm_pass_behind_path_pieces( + x1, + y1, + x2, + y2, + rad, + intervals, + dash_delta_t, + n=None, +): + ''' + Split an Arc3 into solid / dashed pieces around pass-behind intervals. + + For each crossing: solid ... [dash approach] [hidden under node] + [dash exit] solid ... + ''' + if n is None: + n = _STM_ROUTE_SAMPLE_N * 2 + dash = max(float(dash_delta_t), 1e-4) + # Collect hidden ranges and dash ranges along t in [0, 1]. + hidden = [] + dash_spans = [] + for _name, t_enter, t_exit in intervals: + hidden.append((t_enter, t_exit)) + dash_spans.append((max(0.0, t_enter - dash), t_enter)) + dash_spans.append((t_exit, min(1.0, t_exit + dash))) + + def covered(t, spans): + for a, b in spans: + if a - 1e-12 <= t <= b + 1e-12: + return True + return False + + # Sample and classify. + samples = [] + for i in range(n + 1): + t = i / float(n) + px, py, _, _ = stm_arc3_point_and_tangent(x1, y1, x2, y2, rad, t) + if covered(t, hidden): + kind = 'hidden' + elif covered(t, dash_spans): + kind = 'dash' + else: + kind = 'solid' + samples.append((t, px, py, kind)) + + pieces = [] + run = [] + run_kind = None + for t, px, py, kind in samples: + if kind == 'hidden': + if run: + pieces.append({'style': run_kind, 'points': run}) + run = [] + run_kind = None + continue + if run_kind is None: + run_kind = kind + run = [(px, py)] + elif kind == run_kind: + run.append((px, py)) + else: + pieces.append({'style': run_kind, 'points': run}) + run_kind = kind + run = [(px, py)] + if run: + pieces.append({'style': run_kind, 'points': run}) + return pieces + + +def stm_select_edge_route( + x1, + y1, + x2, + y2, + src, + dst, + seed_magnitude, + node_centers, + node_radii, + half_width_data, + pad_data, + selected_polylines, + paired_sign=None, + diag_context='', +): + ''' + Select a reasonable Arc3 rad for a directed transition. + + Prefers fully clear routes (casing-aware) ranked by fewer intersections, + milder |rad|, greater clearance, then ladder index. If no clear reasonable + route exists, returns the best deterministic fallback with pass_behind=True + (never raises). + ''' + del diag_context # retained for call-site compatibility + obstacles = { + name: center + for name, center in node_centers.items() + if name != src and name != dst + } + obst_radii = { + name: float(node_radii.get(name, 0.0)) for name in obstacles + } + rad_list = stm_edge_route_reasonable_rads(seed_magnitude) + + def evaluate_all(): + scored = [] + for idx, rad in enumerate(rad_list): + polyline = _stm_sample_arc3_polyline( + x1, y1, x2, y2, rad, n=_STM_ROUTE_SAMPLE_N, + ) + clearance = stm_route_node_clearance( + polyline, + obstacles, + obst_radii, + half_width_data, + pad_data, + ) + intersections = 0 + for other in selected_polylines: + intersections += stm_polyline_segment_intersections( + polyline, other, + ) + scored.append({ + 'rad': float(rad), + 'polyline': polyline, + 'clearance': float(clearance), + 'intersections': int(intersections), + 'index': idx, + }) + return scored + + def rank_pick(candidates, reciprocal_side_relaxed, pass_behind): + best = min( + candidates, + key=lambda c: ( + c['intersections'], + abs(c['rad']), + -c['clearance'], + c['index'], + ), + ) + crossed = [] + if pass_behind: + crossed = stm_route_crossed_nodes( + best['polyline'], + obstacles, + obst_radii, + half_width_data, + pad_data, + ) + return { + 'rad': best['rad'], + 'polyline': best['polyline'], + 'clearance': best['clearance'], + 'intersections': best['intersections'], + 'reciprocal_side_relaxed': bool(reciprocal_side_relaxed), + 'pass_behind': bool(pass_behind), + 'crossed_nodes': crossed, + } + + def filter_reciprocal(candidates): + if paired_sign is None: + return candidates, False + same_sign = [ + c for c in candidates + if _stm_rad_sign(c['rad']) == int(paired_sign) + ] + if same_sign: + return same_sign, False + return candidates, True + + all_scored = evaluate_all() + if not all_scored: + # Degenerate seed path (should not happen with non-empty ladder). + polyline = _stm_sample_arc3_polyline( + x1, y1, x2, y2, float(seed_magnitude) or _STM_EDGE_RAD_SINGLE, + n=_STM_ROUTE_SAMPLE_N, + ) + return { + 'rad': float(seed_magnitude) or _STM_EDGE_RAD_SINGLE, + 'polyline': polyline, + 'clearance': 0.0, + 'intersections': 0, + 'reciprocal_side_relaxed': False, + 'pass_behind': False, + 'crossed_nodes': [], + } + + clear = [c for c in all_scored if c['clearance'] >= 0.0] + if clear: + pool, relaxed = filter_reciprocal(clear) + return rank_pick(pool, relaxed, pass_behind=False) + + # No clear reasonable route: pass-behind fallback (never extreme rads). + pool, relaxed = filter_reciprocal(all_scored) + return rank_pick(pool, relaxed, pass_behind=True) + + +def stm_route_bounds_from_geometry(positions, observed, polylines, half_widths_data): + '''Data limits enclosing nodes and route samples padded by casing half-width.''' + xs = [positions[b][0] for b in observed] + ys = [positions[b][1] for b in observed] + xmin, xmax = min(xs), max(xs) + ymin, ymax = min(ys), max(ys) + for poly, half_w in zip(polylines, half_widths_data): + pad = float(half_w) + for px, py in poly: + xmin = min(xmin, px - pad) + xmax = max(xmax, px + pad) + ymin = min(ymin, py - pad) + ymax = max(ymax, py + pad) + return ( + xmin - _STM_VIEW_PAD, + xmax + _STM_VIEW_PAD, + ymin - _STM_VIEW_PAD, + ymax + _STM_VIEW_PAD, + ) + + +def stm_collect_reasonable_route_polylines(ordered_edges, positions, count_df): + ''' + Every deterministic reasonable Arc3 polyline for each transition edge. + + Used for conservative bounds envelopes when select/bounds iteration + does not converge. Order is by edge list then rad ladder index. + ''' + polylines = [] + halfwidth_pts = [] + for edge in ordered_edges: + src = edge['src'] + dst = edge['dst'] + x1, y1 = positions[src] + x2, y2 = positions[dst] + seed = stm_edge_rad(src, dst, count_df) + lw = float(edge.get('linewidth', _STM_EDGE_LW_MIN)) + hw_pt = stm_visible_edge_halfwidth_pt(lw) + for rad in stm_edge_route_reasonable_rads(seed): + polylines.append( + _stm_sample_arc3_polyline( + x1, y1, x2, y2, rad, n=_STM_ROUTE_SAMPLE_N, + ) + ) + halfwidth_pts.append(hw_pt) + return polylines, halfwidth_pts + + +def stm_route_conservative_envelope_bounds( + positions, + observed, + ordered_edges, + count_df, + units_per_point, + current_limits=None, +): + ''' + Deterministic axes bounds covering every reasonable route candidate plus + visible casing (scaled if the envelope grows the data span vs current limits). + ''' + polylines, halfwidth_pts = stm_collect_reasonable_route_polylines( + ordered_edges, positions, count_df, + ) + if not polylines: + # Nodes only (no transitions). + xs = [positions[b][0] for b in observed] + ys = [positions[b][1] for b in observed] + return ( + min(xs) - _STM_VIEW_PAD, + max(xs) + _STM_VIEW_PAD, + min(ys) - _STM_VIEW_PAD, + max(ys) + _STM_VIEW_PAD, + ) + # Geometry-only envelope of all candidates (no casing yet). + zero_hw = [0.0] * len(polylines) + geom = stm_route_bounds_from_geometry( + positions, observed, polylines, zero_hw, + ) + geom_span = max(geom[1] - geom[0], geom[3] - geom[2], 1e-12) + if current_limits is not None: + cx0, cx1, cy0, cy1 = current_limits + cur_span = max(float(cx1) - float(cx0), float(cy1) - float(cy0), 1e-12) + else: + cur_span = geom_span + # Expanding the view grows data-units-per-point; scale casing pads accordingly. + growth = max(1.0, geom_span / cur_span) + upt = float(units_per_point) * growth + halfs = [float(hw_pt) * upt for hw_pt in halfwidth_pts] + return stm_route_bounds_from_geometry( + positions, observed, polylines, halfs, + ) + + +def stm_selected_routes_fit_axes_bounds( + selected_edges, + half_widths_data, + limits, + tol=None, +): + ''' + True when every selected route sample expanded by casing fits in limits. + + limits: (xmin, xmax, ymin, ymax) + ''' + if tol is None: + tol = _STM_ROUTE_BOUNDS_FIT_TOL + xmin, xmax, ymin, ymax = (float(v) for v in limits) + tol = float(tol) + for edge, half_w in zip(selected_edges, half_widths_data): + pad = float(half_w) + for px, py in edge.get('polyline') or (): + if ( + px - pad < xmin - tol + or px + pad > xmax + tol + or py - pad < ymin - tol + or py + pad > ymax + tol + ): + return False + return True + + +def _stm_label_point_clearance( + lx, + ly, + node_centers, + node_radii, + other_polylines, + placed_centers, + label_half_w, + label_half_h, + arrow_xy=None, +): + label_r = 0.5 * math.hypot(2.0 * label_half_w, 2.0 * label_half_h) + node_margin = 1.05 * label_r + edge_extent = max(label_half_h, 0.5 * label_half_w) * 0.9 + label_sep = 1.7 * label_r + min_clearance = float('inf') + for name, (nx, ny) in node_centers.items(): + reserved = float(node_radii.get(name, 0.0)) + node_margin + clearance = math.hypot(lx - nx, ly - ny) - reserved + if clearance < min_clearance: + min_clearance = clearance + for poly in other_polylines: + clearance = _stm_min_dist_to_polyline(lx, ly, poly) - edge_extent + if clearance < min_clearance: + min_clearance = clearance + for px, py in placed_centers: + clearance = math.hypot(lx - px, ly - py) - label_sep + if clearance < min_clearance: + min_clearance = clearance + if arrow_xy is not None: + ah_x, ah_y = arrow_xy + ah_r = max(label_half_w, label_half_h) * 0.85 + clearance = math.hypot(lx - ah_x, ly - ah_y) - ah_r + if clearance < min_clearance: + min_clearance = clearance + return min_clearance + + +def stm_evaluate_oncurve_label_candidates( + x1, + y1, + x2, + y2, + rad, + node_centers, + node_radii, + other_polylines, + placed_centers, + label_half_w, + label_half_h, +): + '''Score every on-curve t by maximin clearance; return ordered results.''' + ah_x, ah_y, _, _ = stm_arc3_point_and_tangent(x1, y1, x2, y2, rad, 0.92) + results = [] + for t in _STM_EDGE_LABEL_T_CANDIDATES: + lx, ly, rot = stm_edge_label_placement(x1, y1, x2, y2, rad, t=t) + clearance = _stm_label_point_clearance( + lx, + ly, + node_centers, + node_radii, + other_polylines, + placed_centers, + label_half_w, + label_half_h, + arrow_xy=(ah_x, ah_y), + ) + results.append({ + 't': float(t), + 'x': lx, + 'y': ly, + 'rotation': rot, + 'clearance': float(clearance), + }) + return results + + +def stm_best_oncurve_label_candidate(candidates): + '''Best maximin on-curve candidate; central t only as exact clearance tie-break.''' + if not candidates: + return None + return min( + candidates, + key=lambda c: ( + -c['clearance'], + abs(c['t'] - _STM_EDGE_LABEL_T), + ), + ) + + +def stm_pick_edge_label_position( + x1, + y1, + x2, + y2, + rad, + node_centers, + node_radii, + other_polylines, + placed_centers, + label_half_w, + label_half_h, +): + ''' + Choose an on-curve edge-label center by maximizing minimum clearance. + + Returns (label_x, label_y, rotation_deg). Does not apply callout placement. + ''' + candidates = stm_evaluate_oncurve_label_candidates( + x1, + y1, + x2, + y2, + rad, + node_centers, + node_radii, + other_polylines, + placed_centers, + label_half_w, + label_half_h, + ) + best = stm_best_oncurve_label_candidate(candidates) + if best is None: + return stm_edge_label_placement(x1, y1, x2, y2, rad) + return best['x'], best['y'], best['rotation'] + + +def _stm_leader_samples(ax, ay, bx, by, n=12): + pts = [] + for i in range(n + 1): + u = i / float(n) + pts.append((ax + u * (bx - ax), ay + u * (by - ay))) + return pts + + +def _stm_callout_catalog_offsets(): + '''Fixed-order (perp_sign, perp_pt, along_pt) callout catalog.''' + catalog = [] + for perp_pt in _STM_CALLOUT_PERP_PT: + for perp_sign in (1.0, -1.0): + for along_pt in _STM_CALLOUT_ALONG_PT: + catalog.append((perp_sign, float(perp_pt), float(along_pt))) + return catalog + + +def stm_place_edge_label( + x1, + y1, + x2, + y2, + rad, + node_centers, + node_radii, + other_polylines, + placed_centers, + label_half_w, + label_half_h, + min_clearance_data, + units_per_point, +): + ''' + Place a full edge label on-curve when clearance allows; otherwise callout. + + Callout attachment is the best maximin on-curve candidate. Every fixed + catalog offset is scored by maximin over the callout box and full leader. + ''' + candidates = stm_evaluate_oncurve_label_candidates( + x1, + y1, + x2, + y2, + rad, + node_centers, + node_radii, + other_polylines, + placed_centers, + label_half_w, + label_half_h, + ) + best_on = stm_best_oncurve_label_candidate(candidates) + if best_on is None: + lx, ly, rot = stm_edge_label_placement(x1, y1, x2, y2, rad) + return { + 'mode': 'on_curve', + 'x': lx, + 'y': ly, + 'rotation': rot, + 'attach_x': lx, + 'attach_y': ly, + 'attach_t': _STM_EDGE_LABEL_T, + 'clearance': float('inf'), + 'leader_length': 0.0, + } + if best_on['clearance'] >= float(min_clearance_data): + return { + 'mode': 'on_curve', + 'x': best_on['x'], + 'y': best_on['y'], + 'rotation': best_on['rotation'], + 'attach_x': best_on['x'], + 'attach_y': best_on['y'], + 'attach_t': best_on['t'], + 'clearance': best_on['clearance'], + 'leader_length': 0.0, + } + + ax_pt, ay_pt = best_on['x'], best_on['y'] + _, _, tx, ty = stm_arc3_point_and_tangent( + x1, y1, x2, y2, rad, best_on['t'], + ) + nx, ny = -ty, tx + ah_x, ah_y, _, _ = stm_arc3_point_and_tangent(x1, y1, x2, y2, rad, 0.92) + + scored = [] + for idx, (perp_sign, perp_pt, along_pt) in enumerate( + _stm_callout_catalog_offsets() + ): + cx = ( + ax_pt + + perp_sign * perp_pt * units_per_point * nx + + along_pt * units_per_point * tx + ) + cy = ( + ay_pt + + perp_sign * perp_pt * units_per_point * ny + + along_pt * units_per_point * ty + ) + box_clear = _stm_label_point_clearance( + cx, + cy, + node_centers, + node_radii, + other_polylines, + placed_centers, + label_half_w, + label_half_h, + arrow_xy=(ah_x, ah_y), + ) + leader_clear = float('inf') + for sx, sy in _stm_leader_samples(ax_pt, ay_pt, cx, cy): + c = _stm_label_point_clearance( + sx, + sy, + node_centers, + node_radii, + other_polylines, + placed_centers, + label_half_w * 0.25, + label_half_h * 0.25, + arrow_xy=(ah_x, ah_y), + ) + if c < leader_clear: + leader_clear = c + min_clear = min(box_clear, leader_clear) + leader_len = math.hypot(cx - ax_pt, cy - ay_pt) + scored.append({ + 'index': idx, + 'x': cx, + 'y': cy, + 'clearance': min_clear, + 'leader_length': leader_len, + }) + + passing = [c for c in scored if c['clearance'] >= float(min_clearance_data)] + pool = passing if passing else scored + chosen = min( + pool, + key=lambda c: ( + -c['clearance'], + c['leader_length'], + c['index'], + ), + ) + return { + 'mode': 'callout', + 'x': chosen['x'], + 'y': chosen['y'], + 'rotation': 0.0, + 'attach_x': ax_pt, + 'attach_y': ay_pt, + 'attach_t': best_on['t'], + 'clearance': chosen['clearance'], + 'leader_length': chosen['leader_length'], + } + + +def stm_key_region_height_inches(n_body_lines): + '''Key axes height (inches) from font/gap packing so the body is unclipped.''' + n = max(int(n_body_lines), 1) + total_pt = ( + _STM_KEY_TOP_MARGIN_PT + + _STM_KEY_TITLE_FONTSIZE * _STM_KEY_LINE_SPACING + + _STM_KEY_GAP_PT + + _STM_KEY_FONTSIZE * _STM_KEY_LINE_SPACING + + _STM_KEY_GAP_PT + + n * _STM_KEY_FONTSIZE * _STM_KEY_LINE_SPACING + + _STM_KEY_BOTTOM_MARGIN_PT + ) + return total_pt / 72.0 + + +def stm_key_pack_y_positions(n_body_lines, axes_height_inches=None): + ''' + Axes-fraction y positions (va=top) for title, explain, and body. + + Gaps between blocks are controlled in typographic points (_STM_KEY_GAP_PT). + ''' + if axes_height_inches is None: + axes_height_inches = stm_key_region_height_inches(n_body_lines) + h = max(float(axes_height_inches), 1e-9) + + def frac(pt): + return (float(pt) / 72.0) / h + + y = 1.0 - frac(_STM_KEY_TOP_MARGIN_PT) + y_title = y + y -= frac(_STM_KEY_TITLE_FONTSIZE * _STM_KEY_LINE_SPACING + _STM_KEY_GAP_PT) + y_explain = y + y -= frac(_STM_KEY_FONTSIZE * _STM_KEY_LINE_SPACING + _STM_KEY_GAP_PT) + y_body = y + return { + 'title': y_title, + 'explain': y_explain, + 'body': y_body, + 'gap_pt': _STM_KEY_GAP_PT, + 'height_inches': h, + } + + +def stm_edge_rad(src, dst, count_df): + '''Preferred Arc3 magnitude seed (single vs reciprocal); not the drawn rad.''' + if src == dst: + return _STM_EDGE_RAD_SINGLE + exists_ij = int(count_df.loc[src, dst]) >= 1 + exists_ji = int(count_df.loc[dst, src]) >= 1 + if exists_ij and exists_ji: + return _STM_EDGE_RAD_BIDIR + return _STM_EDGE_RAD_SINGLE + +def stm_ordered_transition_edges(observed, count_df, prob_df): + ''' + Directed transitions with count >= 1, ordered by (src_index, dst_index). + + ``observed`` must already be in the deterministic display order. + ''' + edges = [] + for src in observed: + for dst in observed: + raw_count = int(count_df.loc[src, dst]) + if raw_count < 1: + continue + edge_value = float(prob_df.loc[src, dst]) + if np.isnan(edge_value) or edge_value <= 0: + continue + edges.append({ + 'src': src, + 'dst': dst, + 'count': raw_count, + 'value': edge_value, + }) + return edges + + +def stm_assign_edge_identifiers(edges): + '''Attach deterministic T1, T2, ... identifiers (T = transition) in list order.''' + out = [] + for i, edge in enumerate(edges, start=1): + item = dict(edge) + item['edge_id'] = 'T%d' % i + out.append(item) + return out + + +def stm_format_transition_key_lines(entries): + '''Format transition-key lines: T#: source → destination: probability (count).''' + lines = [] + for entry in entries: + lines.append( + '%s: %s \u2192 %s: %.2f (%d)' % ( + entry['edge_id'], + entry['src'], + entry['dst'], + float(entry['value']), + int(entry['count']), + ) + ) + return lines + + +def stm_circular_layout(behavior_names, radius=1.0): + '''Place behaviors evenly on a circle (fresh deterministic layout each run).''' + names = list(behavior_names) + if len(names) == 0: + return {} + angles = np.linspace( + np.pi / 2, + np.pi / 2 - 2 * np.pi, + len(names), + endpoint=False, + ) + return { + name: (float(radius * np.cos(angle)), float(radius * np.sin(angle))) + for name, angle in zip(names, angles) + } + + +def stm_session_colors(behavior_names, existing_colors=None): + ''' + Build hex colors for this session only (no disk persistence). + Uses existing_colors when provided; fills the rest with deterministic defaults. + ''' + names = list(behavior_names) + colors = {} + if existing_colors: + for b, c in existing_colors.items(): + if b not in names: + continue + if isinstance(c, str) and c.startswith('#') and len(c) == 7: + colors[b] = c + else: + colors[b] = stm_get_hex_color(c) + for i, b in enumerate(names): + if b not in colors: + colors[b] = stm_default_behavior_color(b, index=i) + return colors + + +def stm_remove_known_files(directory, known_filenames): + '''Remove exact known filenames that exist as files under directory.''' + if not os.path.isdir(directory): + return + for name in known_filenames: + path = os.path.join(directory, name) + if os.path.isfile(path): + try: + os.remove(path) + except OSError: + pass + + +def stm_cleanup_stale_animal_folder(animal_dir): + ''' + Safe cleanup of a stale per-animal package directory. + + Removes only known STM-generated artifacts. Does not delete unknown files + or nested directories. Removes the folder itself only if empty afterward. + + Returns: + 'removed' — directory deleted (only known artifacts were present) + 'preserved' — directory kept because non-STM content remained + 'missing' — path was not a directory + ''' + if not os.path.isdir(animal_dir): + return 'missing' + + stm_remove_known_files(animal_dir, _STM_ANIMAL_KNOWN_FILES) + + try: + remaining = os.listdir(animal_dir) + except OSError: + return 'preserved' + + if len(remaining) == 0: + try: + os.rmdir(animal_dir) + return 'removed' + except OSError: + return 'preserved' + + return 'preserved' + + +def _stm_dir_has_known_animal_files(directory): + '''True if directory contains any known per-animal STM output files.''' + if not os.path.isdir(directory): + return False + for name in _STM_ANIMAL_KNOWN_FILES: + if os.path.isfile(os.path.join(directory, name)): + return True + return False + + +def stm_cleanup_obsolete_artifacts(stm_dir, current_animal_folder_names): + ''' + Clean stale STM artifacts inside stm_dir only: + - exact known obsolete root filenames + - known artifacts inside per-animal folders no longer present + + Per-animal folders are ID-only (e.g. "0", "1"). Legacy packages named + animal_* are also cleaned. ID-only directories are treated as packages only + when they contain known STM-generated files (unrelated numeric user folders + without STM artifacts are left alone). + + Never recursively deletes animal folders that still contain unknown content. + + Returns a list of animal folder basenames that were preserved because + non-STM content remained after known-artifact removal. + ''' + preserved_stale_animals = [] + if not os.path.isdir(stm_dir): + return preserved_stale_animals + + stm_remove_known_files(stm_dir, _STM_ROOT_OBSOLETE_FILES) + + current = set(current_animal_folder_names) + for entry in os.listdir(stm_dir): + full = os.path.join(stm_dir, entry) + if not os.path.isdir(full): + continue + if entry in current: + continue + if not stm_is_animal_package_dirname(entry): + continue + # Legacy animal_* always eligible; ID-only only when STM outputs present. + if not entry.startswith('animal_') and not _stm_dir_has_known_animal_files(full): + continue + outcome = stm_cleanup_stale_animal_folder(full) + if outcome == 'preserved': + preserved_stale_animals.append(entry) + + return preserved_stale_animals + + +def stm_clear_animal_metric_files(animal_dir): + '''Remove known metric/map files when an animal package becomes empty-only.''' + stm_remove_known_files(animal_dir, _STM_ANIMAL_KNOWN_FILES) + + +# Node-label typography only (does not affect layout/node geometry). +_STM_NODE_LABEL_MAX_CHARS = 9 # ~8–9 chars/line for balanced multi-word names +# Default matplotlib linespacing is ~1.2; a modest bump aids multi-line scanability +# without expanding the block enough to crowd node borders. +_STM_NODE_LABEL_LINESPACING = 1.45 + + +def stm_wrap_behavior_name(name, max_line_chars=None): + ''' + Deterministic wrap of a behavior name for node labels. + + Prefers breaks near ~8–9 characters (default max_line_chars) so multi-word + names form balanced lines. Breaks on spaces when possible; hard-splits only + when a single token exceeds the limit. + ''' + if max_line_chars is None: + max_line_chars = _STM_NODE_LABEL_MAX_CHARS + name = str(name).strip() + if not name: + return [''] + if max_line_chars < 4: + max_line_chars = 4 + + def hard_chunks(token): + if len(token) <= max_line_chars: + return [token] + return [ + token[i:i + max_line_chars] + for i in range(0, len(token), max_line_chars) + ] + + words = name.split() + if not words: + return hard_chunks(name) + + # Soft target slightly under the hard max encourages more even lines + # (e.g. "behind" / "the wheel" rather than a packed first line + short tail). + target = max(4, min(max_line_chars, 9)) + soft = max(4, target - 1) # prefer ~8 when max is 9 + + lines = [] + current = '' + for word in words: + pieces = hard_chunks(word) + for piece in pieces: + if not current: + current = piece + continue + proposed = current + ' ' + piece + # Stay under hard max; prefer not to exceed soft width when the + # next piece could start a cleaner subsequent line. + if len(proposed) <= soft: + current = proposed + elif len(proposed) <= max_line_chars and len(current) < soft: + # Fill toward the hard max only when current line is still short. + current = proposed + else: + lines.append(current) + current = piece + if current: + lines.append(current) + return lines + + +def stm_format_occupancy_percent(occupancy): + '''Display occupancy percent; positive values below 1% become "<1%".''' + occ = float(occupancy) + if occ <= 0.0: + return '0%' + if occ < 0.01: + return '<1%' + return str(int(round(100.0 * occ))) + '%' + + +def stm_format_node_label(behavior_name, occupancy): + '''Return (label_text, fontsize) for a node.''' + name_lines = stm_wrap_behavior_name(behavior_name) + # Name lines first; occupancy kept on its own final line (visual association). + lines = list(name_lines) + [stm_format_occupancy_percent(occupancy)] + n = len(lines) + if n <= 2: + fontsize = 9 + elif n == 3: + fontsize = 8 + else: + fontsize = 7 + return '\n'.join(lines), fontsize + + +def stm_node_marker_size(occupancy): + '''Scatter marker area from occupancy with a legibility floor.''' + occ = max(0.0, min(1.0, float(occupancy))) + return _STM_NODE_SIZE_MIN + _STM_NODE_SIZE_SPAN * occ + + +def stm_edge_linewidth(probability): + '''Fixed-scale linewidth from row-normalized probability in [0, 1].''' + p = max(0.0, min(1.0, float(probability))) + return _STM_EDGE_LW_MIN + _STM_EDGE_LW_SPAN * p + + +def stm_format_edge_label(probability, count, edge_id=None): + '''On-map edge label: single-line "T# · probability (count)" when id is set.''' + body = '%.2f (%d)' % (float(probability), int(count)) + if edge_id: + return '%s%s%s' % (edge_id, _STM_EDGE_LABEL_MIDDOT, body) + return body + + +def stm_edge_label_half_extents_pt(label_text=None, fontsize=None): + ''' + Half-width / half-height of a single-line on-map edge label bbox in points. + + Includes approximate glyph span and the white bbox pad. Uses a + representative long label when label_text is omitted. + ''' + if fontsize is None: + fontsize = _STM_EDGE_LABEL_FONTSIZE + if label_text is None: + label_text = stm_format_edge_label(0.99, 999, edge_id='T99') + # Proportional sans-serif approx (no figure/renderer required). + char_em = 0.55 * float(fontsize) + pad = float(_STM_EDGE_LABEL_BBOX_PAD) * float(fontsize) + full_w = len(label_text) * char_em + 2.0 * pad + # Single line: text height + pad (no multi-line stack). + full_h = float(fontsize) * 1.15 + 2.0 * pad + return 0.5 * full_w, 0.5 * full_h + + +def stm_edge_label_half_extents_data(ax, label_text=None, fontsize=None): + '''Convert single-line edge-label bbox half-extents to data coordinates.''' + half_w_pt, half_h_pt = stm_edge_label_half_extents_pt(label_text, fontsize) + scale = ( + (float(ax.figure.dpi) / 72.0) * _stm_data_units_per_display_pixel(ax) + ) + return half_w_pt * scale, half_h_pt * scale + + +def _stm_draw_polyline_stroke(ax, points, linewidth, color, alpha, zorder, linestyle='-'): + '''Draw a polyline stroke (white casing or black foreground).''' + if len(points) < 2: + return + xs = [p[0] for p in points] + ys = [p[1] for p in points] + ax.plot( + xs, + ys, + color=color, + linewidth=linewidth, + alpha=alpha, + zorder=zorder, + linestyle=linestyle, + solid_capstyle='round', + solid_joinstyle='round', + dash_capstyle='round', + ) + + +def _stm_draw_edge_path( + ax, + edge, + occupancy, + node_centers, + node_radii, + half_width_data, + pad_data, + dash_delta_t, +): + ''' + Draw one directed edge with shared casing/FG geometry. + + Clear routes use FancyArrowPatch. Pass-behind routes use solid segments + with dashed approach/exit and a terminal arrowhead; interior under nodes + is omitted so the edge appears to continue behind. + ''' + from matplotlib.patches import FancyArrowPatch + + x1, y1 = edge['x1'], edge['y1'] + x2, y2 = edge['x2'], edge['y2'] + rad = edge['rad'] + lw = edge['linewidth'] + casing_lw = lw + _STM_EDGE_CASING_EXTRA + shrink_a = stm_edge_shrink_points(stm_node_marker_size(occupancy[edge['src']])) + shrink_b = stm_edge_shrink_points(stm_node_marker_size(occupancy[edge['dst']])) + + if not edge.get('pass_behind'): + common = dict( + arrowstyle='-|>', + mutation_scale=_STM_EDGE_MUTATION_SCALE, + shrinkA=shrink_a, + shrinkB=shrink_b, + connectionstyle='arc3,rad=%s' % rad, + ) + ax.add_patch(FancyArrowPatch( + (x1, y1), + (x2, y2), + linewidth=casing_lw, + color='white', + alpha=1.0, + zorder=_STM_EDGE_CASING_ZORDER, + **common + )) + ax.add_patch(FancyArrowPatch( + (x1, y1), + (x2, y2), + linewidth=lw, + color='black', + alpha=0.75, + zorder=_STM_EDGE_FOREGROUND_ZORDER, + **common + )) + return + + obstacles = { + name: center + for name, center in node_centers.items() + if name != edge['src'] and name != edge['dst'] + } + obst_radii = {name: float(node_radii.get(name, 0.0)) for name in obstacles} + intervals = stm_route_obstacle_t_intervals( + x1, y1, x2, y2, rad, + obstacles, obst_radii, half_width_data, pad_data, + ) + pieces = stm_pass_behind_path_pieces( + x1, y1, x2, y2, rad, intervals, dash_delta_t, + ) + for piece in pieces: + style = piece['style'] + pts = piece['points'] + ls = '--' if style == 'dash' else '-' + _stm_draw_polyline_stroke( + ax, pts, casing_lw, 'white', 1.0, _STM_EDGE_CASING_ZORDER, ls, + ) + _stm_draw_polyline_stroke( + ax, pts, lw, 'black', 0.75, _STM_PASS_BEHIND_ZORDER, ls, + ) + # Terminal arrowhead on the last free fragment approaching destination. + tip_pts = None + for piece in reversed(pieces): + if len(piece['points']) >= 2: + tip_pts = piece['points'] + break + if tip_pts is None: + px, py, _, _ = stm_arc3_point_and_tangent(x1, y1, x2, y2, rad, 0.92) + tip_pts = [(px, py), (x2, y2)] + ax.add_patch(FancyArrowPatch( + tip_pts[-2], + (x2, y2), + arrowstyle='-|>', + mutation_scale=_STM_EDGE_MUTATION_SCALE, + linewidth=lw, + color='black', + alpha=0.75, + shrinkA=0.0, + shrinkB=shrink_b, + connectionstyle='arc3,rad=0.0', + zorder=_STM_EDGE_FOREGROUND_ZORDER, + )) + + +def _stm_draw_animal_map( + animal_dir, + animal_id, + metrics, + positions, + behavior_colors, + dpi=300, +): + '''Draw one animal state transition map PNG from computed metrics.''' + observed = metrics['observed_behaviors'] + occupancy = metrics['occupancy'] + count_df = metrics['count_matrix'] + prob_df = metrics['probability_matrix'] + + ordered = stm_assign_edge_identifiers( + stm_ordered_transition_edges(observed, count_df, prob_df) + ) + key_lines = stm_format_transition_key_lines(ordered) + n_key_body = max(len(key_lines), 1) + key_height = stm_key_region_height_inches(n_key_body) + key_pack = stm_key_pack_y_positions(n_key_body, key_height) + + fig_w = _STM_FIGSIZE_MAP + fig_h = _STM_FIGSIZE_MAP + key_height + fig = plt.figure(figsize=(fig_w, fig_h)) + gs = fig.add_gridspec( + 2, + 1, + height_ratios=[_STM_FIGSIZE_MAP, key_height], + hspace=0.12, + ) + ax = fig.add_subplot(gs[0, 0]) + ax_key = fig.add_subplot(gs[1, 0]) + ax.set_aspect('equal') + ax.axis('off') + ax_key.axis('off') + + pad = _STM_VIEW_PAD + xs = [positions[b][0] for b in observed] + ys = [positions[b][1] for b in observed] + ax.set_xlim(min(xs) - pad, max(xs) + pad) + ax.set_ylim(min(ys) - pad, max(ys) + pad) + fig.canvas.draw() + + node_centers = {b: positions[b] for b in observed} + + # Route selection under axes transform with bounded bounds↔select convergence. + # Each iteration fully reselects reasonable rads (pass-behind only when no + # clear alternative). If ordinary convergence hits its limit, apply a + # deterministic conservative envelope of *all* reasonable candidates once, + # then finalize selection under that fixed transform (no residual mismatch). + def _route_all_edges(): + units_per_pt = _stm_data_units_per_point(ax) + pad_data = _STM_ROUTE_NODE_PAD_PT * units_per_pt + node_radii = { + b: _stm_node_radius_data(ax, stm_node_marker_size(occupancy[b])) + for b in observed + } + selected = [] + pair_signs = {} + half_widths = [] + for edge in ordered: + src = edge['src'] + dst = edge['dst'] + x1, y1 = positions[src] + x2, y2 = positions[dst] + linewidth = stm_edge_linewidth(edge['value']) + half_w_pt = stm_visible_edge_halfwidth_pt(linewidth) + half_w = stm_edge_halfwidth_data(ax, half_w_pt) + half_widths.append(half_w) + seed = stm_edge_rad(src, dst, count_df) + pair_key = _stm_unordered_pair_key(src, dst) + paired_sign = pair_signs.get(pair_key) + route = stm_select_edge_route( + x1, + y1, + x2, + y2, + src, + dst, + seed, + node_centers, + node_radii, + half_w, + pad_data, + [e['polyline'] for e in selected], + paired_sign=paired_sign, + ) + if src != dst and pair_key not in pair_signs: + pair_signs[pair_key] = _stm_rad_sign(route['rad']) + selected.append({ + 'src': src, + 'dst': dst, + 'edge_id': edge['edge_id'], + 'rad': route['rad'], + 'x1': x1, + 'y1': y1, + 'x2': x2, + 'y2': y2, + 'value': edge['value'], + 'count': edge['count'], + 'linewidth': linewidth, + 'polyline': route['polyline'], + 'clearance': route['clearance'], + 'reciprocal_side_relaxed': route['reciprocal_side_relaxed'], + 'pass_behind': route['pass_behind'], + 'crossed_nodes': list(route['crossed_nodes']), + }) + return selected, half_widths + + def _limits_close(a, b): + return all(abs(x - y) <= _STM_ROUTE_LIMIT_EPS for x, y in zip(a, b)) + + def _active_limits(): + return ( + float(ax.get_xlim()[0]), + float(ax.get_xlim()[1]), + float(ax.get_ylim()[0]), + float(ax.get_ylim()[1]), + ) + + def _apply_limits(limits): + xmin, xmax, ymin, ymax = limits + ax.set_xlim(xmin, xmax) + ax.set_ylim(ymin, ymax) + + drawn_edges = [] + converged = False + for _it in range(_STM_ROUTE_CONVERGENCE_MAX): + fig.canvas.draw() + limits_before = _active_limits() + selected, half_widths = _route_all_edges() + xmin, xmax, ymin, ymax = stm_route_bounds_from_geometry( + positions, + observed, + [e['polyline'] for e in selected], + half_widths, + ) + bounds_after = (float(xmin), float(xmax), float(ymin), float(ymax)) + _apply_limits(bounds_after) + drawn_edges = selected + if _limits_close(limits_before, bounds_after): + converged = True + break + + if not converged: + # Deterministic conservative fallback: envelope every reasonable candidate + # (with casing growth against current span), apply once, final select. + fig.canvas.draw() + # Need linewidths on edge records for envelope halfwidth_pt. + edge_specs = [] + for edge in ordered: + item = dict(edge) + item['linewidth'] = stm_edge_linewidth(edge['value']) + edge_specs.append(item) + limits_now = _active_limits() + envelope = stm_route_conservative_envelope_bounds( + positions, + observed, + edge_specs, + count_df, + _stm_data_units_per_point(ax), + current_limits=limits_now, + ) + _apply_limits(envelope) + fig.canvas.draw() + drawn_edges, half_widths = _route_all_edges() + final_limits = _active_limits() + if not stm_selected_routes_fit_axes_bounds( + drawn_edges, half_widths, final_limits, + ): + raise RuntimeError( + 'STM route bounds fallback failed: final selected routes and ' + 'casing exceed the conservative envelope applied to the axes. ' + 'envelope=%s geometry_bounds=%s' % ( + final_limits, + stm_route_bounds_from_geometry( + positions, + observed, + [e['polyline'] for e in drawn_edges], + half_widths, + ), + ) + ) + else: + # Ordinary convergence: selected geometry must still fit active bounds. + fig.canvas.draw() + half_widths = [ + stm_edge_halfwidth_data( + ax, stm_visible_edge_halfwidth_pt(e['linewidth']), + ) + for e in drawn_edges + ] + final_limits = _active_limits() + if not stm_selected_routes_fit_axes_bounds( + drawn_edges, half_widths, final_limits, + ): + raise RuntimeError( + 'STM route bounds converged but selected geometry still exceeds ' + 'active axes limits. limits=%s' % (final_limits,) + ) + + units_per_pt = _stm_data_units_per_point(ax) + pad_data = _STM_ROUTE_NODE_PAD_PT * units_per_pt + dash_data = _STM_PASS_BEHIND_DASH_PT * units_per_pt + node_radii = { + b: _stm_node_radius_data(ax, stm_node_marker_size(occupancy[b])) + for b in observed + } + min_label_clear = _STM_LABEL_MIN_CLEARANCE_PT * units_per_pt + + any_pass_behind = False + for edge in drawn_edges: + # Per-edge dash Δt from total arc length estimate. + poly = edge['polyline'] + arc_len = 0.0 + for i in range(len(poly) - 1): + arc_len += math.hypot( + poly[i + 1][0] - poly[i][0], + poly[i + 1][1] - poly[i][1], + ) + if arc_len < 1e-9: + edge_dash_dt = 0.05 + else: + edge_dash_dt = min(0.2, max(0.02, dash_data / arc_len)) + half_w = stm_edge_halfwidth_data( + ax, stm_visible_edge_halfwidth_pt(edge['linewidth']) + ) + _stm_draw_edge_path( + ax, + edge, + occupancy, + node_centers, + node_radii, + half_w, + pad_data, + edge_dash_dt, + ) + if edge.get('pass_behind'): + any_pass_behind = True + + polylines = [e['polyline'] for e in drawn_edges] + placed_centers = [] + for i, edge in enumerate(drawn_edges): + other = [polylines[j] for j in range(len(polylines)) if j != i] + label_text = stm_format_edge_label( + edge['value'], + edge['count'], + edge_id=edge['edge_id'], + ) + label_half_w, label_half_h = stm_edge_label_half_extents_data( + ax, label_text, + ) + placement = stm_place_edge_label( + edge['x1'], + edge['y1'], + edge['x2'], + edge['y2'], + edge['rad'], + node_centers, + node_radii, + other, + placed_centers, + label_half_w, + label_half_h, + min_label_clear, + units_per_pt, + ) + if placement['mode'] == 'callout': + ax.plot( + [placement['attach_x'], placement['x']], + [placement['attach_y'], placement['y']], + color='#333333', + linewidth=0.7, + zorder=3.5, + solid_capstyle='round', + ) + ax.scatter( + [placement['attach_x']], + [placement['attach_y']], + s=12, + c='#111111', + zorder=3.6, + linewidths=0, + ) + ax.text( + placement['x'], + placement['y'], + label_text, + fontsize=_STM_EDGE_LABEL_FONTSIZE, + ha='center', + va='center', + rotation=placement['rotation'], + rotation_mode='anchor', + zorder=4, + bbox=dict( + boxstyle='round,pad=%.2f' % _STM_EDGE_LABEL_BBOX_PAD, + facecolor='white', + edgecolor=_STM_EDGE_LABEL_BBOX_EDGECOLOR, + linewidth=_STM_EDGE_LABEL_BBOX_LW, + alpha=1.0, + ), + ) + placed_centers.append((placement['x'], placement['y'])) + + for behavior_name in observed: + x, y = positions[behavior_name] + occ = occupancy[behavior_name] + node_size = stm_node_marker_size(occ) + node_color = stm_get_hex_color(behavior_colors.get(behavior_name, '#4C72B0')) + ax.scatter( + x, + y, + s=node_size, + c=node_color, + alpha=1.0, + edgecolors='black', + linewidths=1.5, + zorder=5, + ) + label, fontsize = stm_format_node_label(behavior_name, occ) + ax.text( + x, + y, + label, + ha='center', + va='center', + multialignment='center', + fontsize=fontsize, + color=stm_node_label_color(node_color), + linespacing=_STM_NODE_LABEL_LINESPACING, + zorder=6, + ) + + ax.text( + 0.5, + 1.065, + 'State Transition Map', + transform=ax.transAxes, + ha='center', + va='bottom', + fontsize=_STM_TITLE_FONTSIZE, + zorder=10, + ) + ax.text( + 0.5, + 1.012, + stm_figure_id_subtitle(animal_id), + transform=ax.transAxes, + ha='center', + va='bottom', + fontsize=_STM_TITLE_FONTSIZE * _STM_TITLE_SUBTITLE_SCALE, + zorder=10, + ) + legend_text = _STM_LEGEND_TEXT + if any_pass_behind: + legend_text = legend_text + '\n' + _STM_PASS_BEHIND_LEGEND + ax.text( + 0.02, + 0.02, + legend_text, + transform=ax.transAxes, + ha='left', + va='bottom', + fontsize=_STM_LEGEND_FONTSIZE, + color='#444444', + linespacing=1.35, + zorder=9, + bbox=dict( + boxstyle='round,pad=0.40', + facecolor='white', + edgecolor='#cccccc', + linewidth=0.4, + alpha=0.92, + ), + ) + + key_body = '\n'.join(key_lines) if key_lines else '(no transitions)' + ax_key.text( + 0.0, + key_pack['title'], + 'Transition key', + transform=ax_key.transAxes, + ha='left', + va='top', + fontsize=_STM_KEY_TITLE_FONTSIZE, + fontweight='bold', + color='#222222', + linespacing=_STM_KEY_LINE_SPACING, + clip_on=False, + wrap=False, + ) + ax_key.text( + 0.0, + key_pack['explain'], + _STM_KEY_EXPLAIN, + transform=ax_key.transAxes, + ha='left', + va='top', + fontsize=_STM_KEY_FONTSIZE, + color='#333333', + linespacing=_STM_KEY_LINE_SPACING, + clip_on=False, + wrap=False, + ) + ax_key.text( + 0.0, + key_pack['body'], + key_body, + transform=ax_key.transAxes, + ha='left', + va='top', + fontsize=_STM_KEY_FONTSIZE, + color='#222222', + linespacing=_STM_KEY_LINE_SPACING, + clip_on=False, + wrap=False, + ) + plt.savefig( + os.path.join(animal_dir, 'state_transition_map.png'), + dpi=dpi, + bbox_inches='tight', + pad_inches=0.4, + ) + plt.close(fig) + + +def plot_state_transition_map( + stm_dir, + event_probability, + behavior_to_include, + behavior_colors=None, + input_path=None, + excluded_behaviors=None, + draw_maps=True, + map_dpi=300, +): + ''' + Generate one State Transition Map package per animal (V1 product). + + stm_dir: stable results folder + /state_transition_map/ + event_probability: animal_id -> list of [hard_label, probability] + behavior_to_include: included behavior names after exclusions + behavior_colors: optional session dict behavior -> hex (not persisted) + + Returns a result dict for the GUI: + status: 'success' | 'warning_partial' | 'warning_no_maps' | 'error' + maps_written, empty_animals, ok_animals, stm_dir, + animal_statuses, message, ... + ''' + print('Exporting state transition maps (per animal)...') + print(datetime.datetime.now()) + + if behavior_to_include is None or behavior_to_include == ['all']: + included = [] + if behavior_colors: + included = list(behavior_colors.keys()) + else: + seen = set() + for animal_id in event_probability: + for event in event_probability[animal_id]: + name = event[0] if isinstance(event, (list, tuple)) and event else 'NA' + if name != 'NA': + seen.add(name) + included = sorted(seen) + else: + included = list(behavior_to_include) + + if len(included) == 0: + return { + 'status': 'error', + 'maps_written': 0, + 'empty_animals': 0, + 'ok_animals': 0, + 'stm_dir': stm_dir, + 'animal_statuses': {}, + 'message': 'No behaviors remain after exclusion.', + 'preserved_stale_animal_folders': [], + } + + os.makedirs(stm_dir, exist_ok=True) + colors = stm_session_colors(included, existing_colors=behavior_colors) + + # ----- pass 1: compute per-animal metrics ----- + computed = {} + animal_statuses = {} + union_observed = set() + folder_by_id = {} + + for animal_id in event_probability: + folder = stm_safe_animal_folder_name(animal_id) + folder_by_id[animal_id] = folder + hard = stm_hard_labels(event_probability[animal_id]) + metrics = stm_compute_animal_metrics(hard, included) + computed[animal_id] = metrics + animal_statuses[animal_id] = metrics['status'] + if metrics['status'] == 'ok': + union_observed.update(metrics['observed_behaviors']) + + # ----- stale cleanup ----- + preserved_stale_animals = stm_cleanup_obsolete_artifacts( + stm_dir, set(folder_by_id.values()) + ) + + # Fresh deterministic layout every run (no disk persistence). + ordered_union = sorted(union_observed) + positions = stm_circular_layout(ordered_union) + + # ----- pass 2: write packages / draw ----- + maps_written = 0 + empty_animals = 0 + ok_animals = 0 + + for animal_id in event_probability: + metrics = computed[animal_id] + animal_dir = os.path.join(stm_dir, folder_by_id[animal_id]) + os.makedirs(animal_dir, exist_ok=True) + + if metrics['status'] == 'empty': + empty_animals += 1 + stm_clear_animal_metric_files(animal_dir) + pd.DataFrame( + [{ + 'animal_id': animal_id, + 'status': 'empty', + 'included_frame_total': 0, + 'bout_total': 0, + 'transition_total': 0, + 'note': 'No included behavior frames for this animal.', + }] + ).to_excel( + os.path.join(animal_dir, 'state_transition_summary.xlsx'), + index=False, + ) + continue + + ok_animals += 1 + observed = metrics['observed_behaviors'] + metrics['count_matrix'].to_excel( + os.path.join(animal_dir, 'state_transition_counts.xlsx'), + index_label='from/to', + ) + metrics['probability_matrix'].to_excel( + os.path.join(animal_dir, 'state_transition_probabilities.xlsx'), + float_format='%.6f', + index_label='from/to', + ) + occ_rows = [] + for b in observed: + occ_rows.append({ + 'behavior': b, + 'frame_count': metrics['frame_counts'][b], + 'occupancy': metrics['occupancy'][b], + }) + pd.DataFrame(occ_rows).to_excel( + os.path.join(animal_dir, 'state_behavior_occupancy.xlsx'), + float_format='%.6f', + index=False, + ) + undefined_sources = [] + for b in observed: + row_sum = int(metrics['count_matrix'].loc[b].sum()) + if row_sum == 0: + undefined_sources.append(b) + pd.DataFrame( + [{ + 'animal_id': animal_id, + 'status': 'ok', + 'included_frame_total': metrics['included_frame_total'], + 'bout_total': metrics['bout_total'], + 'transition_total': metrics['transition_total'], + 'observed_behaviors': ','.join(observed), + 'undefined_probability_rows': ','.join(undefined_sources), + }] + ).to_excel( + os.path.join(animal_dir, 'state_transition_summary.xlsx'), + index=False, + ) + + if draw_maps: + animal_positions = {b: positions[b] for b in observed} + _stm_draw_animal_map( + animal_dir, + animal_id, + metrics, + animal_positions, + colors, + dpi=map_dpi, + ) + maps_written += 1 + + # run summary + summary_rows = [] + for animal_id, status in animal_statuses.items(): + summary_rows.append({ + 'animal_id': animal_id, + 'status': status, + 'folder': folder_by_id[animal_id], + 'input_path': str(input_path) if input_path else '', + 'excluded_behaviors': ';'.join(excluded_behaviors or []), + 'included_behaviors': ';'.join(included), + 'maps_written_total': None, + 'empty_animals_total': None, + 'preserved_stale_animal_folders': None, + }) + if summary_rows: + summary_rows[0]['maps_written_total'] = maps_written + summary_rows[0]['empty_animals_total'] = empty_animals + summary_rows[0]['preserved_stale_animal_folders'] = ';'.join( + preserved_stale_animals + ) if preserved_stale_animals else '' + elif preserved_stale_animals: + summary_rows.append({ + 'animal_id': '', + 'status': 'note', + 'folder': '', + 'input_path': str(input_path) if input_path else '', + 'excluded_behaviors': ';'.join(excluded_behaviors or []), + 'included_behaviors': ';'.join(included), + 'maps_written_total': maps_written, + 'empty_animals_total': empty_animals, + 'preserved_stale_animal_folders': ';'.join(preserved_stale_animals), + }) + pd.DataFrame(summary_rows).to_excel( + os.path.join(stm_dir, 'run_summary.xlsx'), + index=False, + ) + + if maps_written == 0: + status = 'warning_no_maps' + message = ( + 'No included behavior frames were available for any animal. ' + 'No maps were generated. Run summary written to:\n' + str(stm_dir) + ) + elif empty_animals > 0: + status = 'warning_partial' + message = ( + 'Generated maps for {ok} animal(s); {empty} animal(s) had no included frames ' + '(summary only).\nResults updated in:\n{path}' + ).format(ok=maps_written, empty=empty_animals, path=stm_dir) + else: + status = 'success' + message = ( + 'Generated maps for {ok} animal(s).\nResults updated in:\n{path}' + ).format(ok=maps_written, path=stm_dir) + + if preserved_stale_animals: + message = ( + message + + '\nPreserved stale animal folder(s) with non-STM content: ' + + ', '.join(preserved_stale_animals) + ) + + print(message) + print('The state transition maps are stored in: ' + str(stm_dir)) + + return { + 'status': status, + 'maps_written': maps_written, + 'empty_animals': empty_animals, + 'ok_animals': ok_animals, + 'stm_dir': stm_dir, + 'animal_statuses': animal_statuses, + 'message': message, + 'behavior_colors': colors, + 'positions': positions, + 'metrics': computed, + 'preserved_stale_animal_folders': list(preserved_stale_animals), + } def extract_frames(path_to_video,out_path,framewidth=None,start_t=0,duration=0,skip_redundant=1000): diff --git a/docs/installation/windows.md b/docs/installation/windows.md index 0725af3c..147d4879 100644 --- a/docs/installation/windows.md +++ b/docs/installation/windows.md @@ -57,4 +57,3 @@ Launch LabGym: ```pwsh-session __main__.main() ``` - diff --git a/noxfile.py b/noxfile.py index e960e264..cf058bdc 100644 --- a/noxfile.py +++ b/noxfile.py @@ -25,6 +25,22 @@ EXTRAS_WX_URL = "https://extras.wxpython.org/wxPython4/extras/linux/gtk3/ubuntu-22.04" +# macOS native GUI frameworks can abort during interpreter +# teardown when repeated real-wx.App lifecycle modules are alphabetically +# interleaved with the rest of the native-importing suite. Isolate those +# modules in a separate pytest process for Darwin only; they are not +# skipped. Add any future test module that creates/manages a real wx.App +# fixture to this list. +MACOS_REAL_APP_TEST_FILES = ( + "LabGym/tests/test_categorizer_class_mismatch.py", + "LabGym/tests/test_diagnostics_cm_colors.py", + "LabGym/tests/test_interactive_results_checkbox.py", + "LabGym/tests/test_triage_guards.py", + "LabGym/tests/test_mywx.py", + "LabGym/tests/test_registration.py", + "LabGym/tests/test_userdata_survey.py", +) + @nox.session(python=['3.9','3.10']) def tests(session:nox.Session): @@ -48,14 +64,34 @@ def tests(session:nox.Session): "torchvision==0.23.0+cpu", "torchaudio==2.8.0+cpu", ) - + elif platform.system() == "Windows": + # Verified Windows CPU family; editable install below enforces numpy<=1.26.4 + session.install( + "--no-cache-dir", + "--index-url", "https://download.pytorch.org/whl/cpu", + "torch==2.8.0", + "torchvision==0.23.0", + "torchaudio==2.8.0", + ) # package and test dependencies session.install("-e", ".") session.install("pytest") - - session.run("pytest", "-q") + # Darwin: isolate real-wx.App lifecycle modules in process 1. + if platform.system() == "Darwin": + session.run("pytest", "-q", *MACOS_REAL_APP_TEST_FILES) + ignore_args = [f"--ignore={path}" for path in MACOS_REAL_APP_TEST_FILES] + session.run( + "pytest", + "-q", + "LabGym/tests", + *ignore_args, + "tests/test_load.py", + "tests/test_main.py", + ) + else: + session.run("pytest", "-q") @nox.session(reuse_venv=True) diff --git a/pyproject.toml b/pyproject.toml index 3d386147..89c5ff14 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -30,11 +30,15 @@ dependencies=[ 'packaging', 'requests', 'numpy<=1.26.4', - 'torch', - 'torchvision', - 'torchaudio', + 'torch==2.8.0;platform_system=="Windows"', + 'torchvision==0.23.0;platform_system=="Windows"', + 'torchaudio==2.8.0;platform_system=="Windows"', + 'torch;platform_system!="Windows"', + 'torchvision;platform_system!="Windows"', + 'torchaudio;platform_system!="Windows"', 'PyYAML', 'tomli', + 'reportlab>=5.0.0', 'Pillow>=7.1', 'matplotlib', 'pycocotools>=2.0.2',