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/categorizer.py b/LabGym/categorizer.py index 5a0c8124..8e093548 100644 --- a/LabGym/categorizer.py +++ b/LabGym/categorizer.py @@ -2094,3 +2094,98 @@ def test_categorizer(self,groundtruth_path,model_path,result_path=None): pd.DataFrame(report).transpose().to_excel(os.path.join(result_path,'testing_reports.xlsx'),float_format='%.2f') print('Testing completed!') + + 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() + + return P \ No newline at end of file diff --git a/LabGym/gui_analyzer.py b/LabGym/gui_analyzer.py index 1a672d9f..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,14 @@ 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 @@ -1550,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_main.py b/LabGym/gui_main.py index b8483602..df033cc8 100644 --- a/LabGym/gui_main.py +++ b/LabGym/gui_main.py @@ -48,7 +48,7 @@ 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 @@ -328,6 +328,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.') @@ -366,7 +378,16 @@ 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 = { 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/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/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):