Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
ea604d3
tests: calculate and return confusion matrix and report
AL3XPI Mar 10, 2026
4fc05a8
gui: render automated diagnostics dialog with MSV confusion matrix an…
AL3XPI Mar 10, 2026
15ff95d
gui: add safety checks to automated diagnostics table and matrix
AL3XPI Mar 11, 2026
63a9d05
gui: add normalized and raw data toggle to confusion matrix
AL3XPI Mar 11, 2026
161214c
gui: implement clickable confusion matrix cells and cross-platform ex…
AL3XPI Mar 11, 2026
bf3f617
gui: heatmap and threshold dropdown
AL3XPI Mar 25, 2026
7c76313
add NLP html base
AL3XPI Apr 28, 2026
8083fc8
NLP tabs and clickable entries
AL3XPI Apr 30, 2026
1c9ac17
training module GUI
AL3XPI May 11, 2026
4473caf
fix uncontrolled ranking logic creep
AL3XPI May 11, 2026
30b9c97
Implement Differential Diagnosis UI and immutable dataset cloning engine
AL3XPI May 12, 2026
2c40f3b
merge visualization
AL3XPI May 12, 2026
7d4c24e
feat: complete triage action plan pdf and h3 variance references
AL3XPI Jun 23, 2026
e77cf3b
feat: complete centroid calc
AL3XPI Jun 24, 2026
2603c44
cleaned up major conf
AL3XPI Jul 5, 2026
ffc0e4d
reportlab and toml
AL3XPI Aug 2, 2026
2576cb2
feat(categorizer): add interactive diagnostics
btmlnsn Aug 13, 2026
0123ee7
fix(categorizer): defer analyzer imports
btmlnsn Aug 13, 2026
e56c9a4
fix(windows): constrain PyTorch compatibility
btmlnsn Aug 13, 2026
10a87e5
fix(tests): read AC source files as UTF-8
btmlnsn Aug 13, 2026
3ecf256
fix(diagnostic): prevent matrix value clipping
btmlnsn Aug 13, 2026
11f9e4b
refactor(tests): use semantic diagnostics names
btmlnsn Aug 13, 2026
7d5e02b
fix(diagnostics): avoid native DC finalization
btmlnsn Aug 13, 2026
9c19544
style: remove trailing whitespace from diagnostics
btmlnsn Sep 23, 2026
f70cf53
fix(categorizer): remove duplicate diagnostics return block
btmlnsn Sep 23, 2026
540701e
fix(gui): restore accepted training module layout
btmlnsn Sep 23, 2026
40c716b
fix(gui): avoid Windows-only curses import
btmlnsn Sep 24, 2026
1099daa
fix(ci): avoid macOS native teardown crash
btmlnsn Sep 24, 2026
9784ab1
fix(ci): pin macOS GUI test dependencies
btmlnsn Sep 24, 2026
6fbbb41
ci(nox): isolate macOS 3.9 wx.App tests
btmlnsn Aug 14, 2026
6102323
fix(ci): isolate macOS wx.App test lifecycles
btmlnsn Sep 24, 2026
cd0142e
ci(pytest): remove unused coverage filters
btmlnsn Aug 14, 2026
ec37729
docs: restore Windows installation guidance
btmlnsn Sep 24, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
152 changes: 95 additions & 57 deletions LabGym/categorizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
from scipy import ndimage
from skimage import exposure,transform
from skimage.transform import AffineTransform
from sklearn.metrics import classification_report
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer
import tensorflow as tf
Expand Down Expand Up @@ -223,6 +223,20 @@ def __getitem__(self,idx):



class CategorizerClassMismatchError(Exception):
"""Raised when ground-truth folder names do not match Categorizer classes."""

def __init__(self, unrecognized_folders, missing_classes):
self.unrecognized_folders = sorted(unrecognized_folders)
self.missing_classes = sorted(missing_classes)
parts = [
'Behavior folder names must exactly match the Categorizer classes.',
f'Unrecognized behavior folders: {self.unrecognized_folders}.',
f'Model classes absent from the fixture: {self.missing_classes}.',
]
super().__init__(' '.join(parts))


class Categorizers():

def __init__(self):
Expand Down Expand Up @@ -1951,6 +1965,7 @@ def test_categorizer(self,groundtruth_path,model_path,result_path=None):
animations=deque()
pattern_images=deque()
labels=deque()
test_files=[]

parameters=pd.read_csv(os.path.join(model_path,'model_parameters.txt'))

Expand Down Expand Up @@ -2018,82 +2033,105 @@ def test_categorizer(self,groundtruth_path,model_path,result_path=None):
if len(incorrect_classes)>0:
print('Unused behavior names in the Categorizer: '+str(incorrect_classes))

if len(incorrect_behaviors)==0 and len(incorrect_classes)==0:
if len(incorrect_behaviors)>0 or len(incorrect_classes)>0:
raise CategorizerClassMismatchError(incorrect_behaviors, incorrect_classes)

for behavior in behaviornames:

if network!=0:
filenames=[i for i in os.listdir(os.path.join(groundtruth_path,behavior)) if i.endswith('.avi')]
else:
filenames=[i for i in os.listdir(os.path.join(groundtruth_path,behavior)) if i.endswith('.jpg')]

for i in filenames:

for behavior in behaviornames:
test_files.append(os.path.join(groundtruth_path, behavior, i))

if network!=0:
filenames=[i for i in os.listdir(os.path.join(groundtruth_path,behavior)) if i.endswith('.avi')]
else:
filenames=[i for i in os.listdir(os.path.join(groundtruth_path,behavior)) if i.endswith('.jpg')]

for i in filenames:
path_to_animation=os.path.join(groundtruth_path,behavior,i)

if network!=0:
capture=cv2.VideoCapture(path_to_animation)
animation=deque()
frames=deque(maxlen=length)

path_to_animation=os.path.join(groundtruth_path,behavior,i)
while True:
retval,frame=capture.read()
if frame is None:
break
frames.append(frame)

capture=cv2.VideoCapture(path_to_animation)
animation=deque()
frames=deque(maxlen=length)
capture.release()

while True:
retval,frame=capture.read()
if frame is None:
break
frames.append(frame)
for frame in frames:
frame=np.uint8(exposure.rescale_intensity(frame,out_range=(0,255)))
if channel==1:
frame=cv2.cvtColor(np.uint8(frame),cv2.COLOR_BGR2GRAY)
frame=cv2.resize(frame,(dim_tconv,dim_tconv),interpolation=cv2.INTER_AREA)
frame=img_to_array(frame)
animation.append(frame)

capture.release()
animations.append(np.array(animation))

for frame in frames:
frame=np.uint8(exposure.rescale_intensity(frame,out_range=(0,255)))
if channel==1:
frame=cv2.cvtColor(np.uint8(frame),cv2.COLOR_BGR2GRAY)
frame=cv2.resize(frame,(dim_tconv,dim_tconv),interpolation=cv2.INTER_AREA)
frame=img_to_array(frame)
animation.append(frame)
if network!=1:

animations.append(np.array(animation))
path_to_pattern_image=os.path.splitext(os.path.join(groundtruth_path,behavior,i))[0]+'.jpg'
pattern_image=cv2.imread(path_to_pattern_image)
if behavior_mode==3:
if channel==1:
pattern_image=cv2.cvtColor(pattern_image,cv2.COLOR_BGR2GRAY)
pattern_image=cv2.resize(pattern_image,(dim_conv,dim_conv),interpolation=cv2.INTER_AREA)
pattern_images.append(img_to_array(pattern_image))

if network!=1:
labels.append(classnames.index(behavior))

path_to_pattern_image=os.path.splitext(os.path.join(groundtruth_path,behavior,i))[0]+'.jpg'
pattern_image=cv2.imread(path_to_pattern_image)
if behavior_mode==3:
if channel==1:
pattern_image=cv2.cvtColor(pattern_image,cv2.COLOR_BGR2GRAY)
pattern_image=cv2.resize(pattern_image,(dim_conv,dim_conv),interpolation=cv2.INTER_AREA)
pattern_images.append(img_to_array(pattern_image))
if network!=0:
animations=np.array(animations,dtype='float32')/255.0
pattern_images=np.array(pattern_images,dtype='float32')/255.0

labels.append(classnames.index(behavior))
labels=np.array(labels)

if network!=0:
animations=np.array(animations,dtype='float32')/255.0
pattern_images=np.array(pattern_images,dtype='float32')/255.0
model=load_model(model_path)

labels=np.array(labels)
from keras.models import Model
multi_model = Model(inputs=model.inputs, outputs=[model.layers[-2].output, model.output])

model=load_model(model_path)
if network==0:
embeddings, predictions = multi_model.predict(pattern_images,batch_size=32)
elif network==1:
embeddings, predictions = multi_model.predict(animations,batch_size=32)
else:
embeddings, predictions = multi_model.predict([animations,pattern_images],batch_size=32)

if network==0:
predictions=model.predict(pattern_images,batch_size=32)
elif network==1:
predictions=model.predict(animations,batch_size=32)
else:
predictions=model.predict([animations,pattern_images],batch_size=32)

if len(classnames)==2:
predictions=[round(i[0]) for i in predictions]
print(classification_report(labels,predictions,target_names=classnames))
report=classification_report(labels,predictions,target_names=classnames,output_dict=True)
else:
print(classification_report(labels,predictions.argmax(axis=1),target_names=classnames))
report=classification_report(labels,predictions.argmax(axis=1),target_names=classnames,output_dict=True)
if len(classnames)==2:
predictions=[round(i[0]) for i in predictions]
flat_predictions = predictions
print(classification_report(labels,predictions,target_names=classnames))
report=classification_report(labels,predictions,target_names=classnames,output_dict=True)
cm=confusion_matrix(labels,predictions)
else:
flat_predictions = predictions.argmax(axis=1)
print(classification_report(labels,flat_predictions,target_names=classnames))
report=classification_report(labels,flat_predictions,target_names=classnames,output_dict=True)
cm=confusion_matrix(labels,flat_predictions)

if result_path is not None:
pd.DataFrame(report).transpose().to_excel(os.path.join(result_path,'testing_reports.xlsx'),float_format='%.2f')
pd.DataFrame(cm, index=classnames, columns=classnames).to_csv(os.path.join(result_path,'confusion_matrix.csv'))

example_map = {}
embedding_map = {}
for t_label_idx, p_label_idx, f_path, emb in zip(labels, flat_predictions, test_files, embeddings):
key = (classnames[t_label_idx], classnames[p_label_idx])
if key not in example_map:
example_map[key] = []
example_map[key].append(f_path)
embedding_map[f_path] = emb

if result_path is not None:
pd.DataFrame(report).transpose().to_excel(os.path.join(result_path,'testing_reports.xlsx'),float_format='%.2f')
print('Testing completed!')

print('Testing completed!')
return report, cm, example_map, embedding_map

def generate_probability_matrix(self, path_to_video, path_to_model, output_folder, batch_size=32):
"""
Expand Down Expand Up @@ -2188,4 +2226,4 @@ def generate_probability_matrix(self, path_to_video, path_to_model, output_folde
plt.savefig(os.path.join(output_folder, "probability_heatmap.png"), dpi=200)
plt.close()

return P
return P
7 changes: 6 additions & 1 deletion LabGym/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,10 @@
# tomllib is included in the Python Standard Library since version 3.11
import tomllib # type: ignore
except ModuleNotFoundError:
import tomli as tomllib # A lil' TOML parser
try:
import tomli as tomllib # A lil' TOML parser
except ModuleNotFoundError:
tomllib = None

# Related third party imports.
import yaml # PyYAML, YAML parser and emitter for Python
Expand Down Expand Up @@ -121,6 +124,8 @@ def get_config_from_configfile(configfile: Path) -> dict:
parser = configparser.ConfigParser()
result = parser.read(configfile)
elif configfile.name.endswith('.toml'):
if tomllib is None:
raise ModuleNotFoundError("TOML support requires Python >= 3.11 or the 'tomli' package. Please install it with: pip install tomli")
with open(configfile, 'rb') as f:
result = tomllib.load(f)
elif configfile.name.endswith('.yaml'):
Expand Down
1 change: 0 additions & 1 deletion LabGym/gui_analyzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@


# Standard library imports.
from curses.panel import panel
import json
import logging
import os
Expand Down
Loading
Loading