-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathForaging.py
More file actions
7693 lines (7098 loc) · 310 KB
/
Copy pathForaging.py
File metadata and controls
7693 lines (7098 loc) · 310 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import csv
import json
import logging
import math
import os
import platform
import shutil
import socket
import subprocess
import sys
import threading
import time
import traceback
import webbrowser
from datetime import date, datetime, timedelta, timezone
from hashlib import md5
from pathlib import Path
from typing import Optional
import ldap3
import ms_active_directory
import concurrent.futures
import getpass
import harp
import logging_loki
import numpy as np
import pandas as pd
import requests
import serial
import yaml
import log_schema
from aind_auto_train.schema.task import TrainingStage
from aind_behavior_services.session import AindBehaviorSessionModel
from aind_data_schema.core.session import Session
from matplotlib.backends.backend_qt5agg import (
NavigationToolbar2QT as NavigationToolbar,
)
from pydantic import ValidationError
from pykeepass import PyKeePass
from pyOSC3.OSC3 import OSCStreamingClient
from PyQt5 import QtCore, QtGui, QtWidgets, uic
from PyQt5.QtCore import Qt, QThread, QThreadPool
from PyQt5.QtWidgets import (
QApplication,
QFileDialog,
QGridLayout,
QLabel,
QMainWindow,
QMessageBox,
QSizePolicy,
QVBoxLayout,
)
from scipy.io import loadmat, savemat
from StageWidget.main import get_stage_widget
import foraging_gui
import foraging_gui.rigcontrol as rigcontrol
from foraging_gui.bias_indicator import BiasIndicator
from foraging_gui.Dialogs import (
AutoTrainDialog,
CameraDialog,
LaserCalibrationDialog,
LickStaDialog,
MetadataDialog,
MouseSelectorDialog,
OptogeneticsDialog,
TimeDistributionDialog,
WaterCalibrationDialog,
OpticalTaggingDialog,
RandomRewardDialog,
get_curriculum_string
)
from foraging_gui.GenerateMetadata import generate_metadata
from foraging_gui.MyFunctions import (
EphysRecording,
GenerateTrials,
NewScaleSerialY,
TimerWorker,
Worker,
)
from foraging_gui.RigJsonBuilder import build_rig_json
from foraging_gui.settings_model import BonsaiSettingsModel, DFTSettingsModel
from foraging_gui.sound_button import SoundButton
from foraging_gui.stage import Stage
from foraging_gui.Visualization import (
PlotLickDistribution,
PlotTimeDistribution,
PlotV,
)
from foraging_gui.warning_widget import WarningWidget
import csv
logger = logging.getLogger(__name__)
logger.root.handlers.clear() # clear handlers so console output can be configured
logging.raiseExceptions = os.getenv("FORAGING_DEV_MODE", False)
class NumpyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.ndarray):
return obj.tolist() # Convert NumPy array to a list
if isinstance(obj, np.integer):
return int(obj) # Convert np.int32 to a regular int
if isinstance(obj, np.float64) and np.isnan(obj):
return "NaN" # Represent NaN as a string
return super(NumpyEncoder, self).default(obj)
class Window(QMainWindow):
Time = QtCore.pyqtSignal(int) # Photometry timer signal
def __init__(self, parent=None, box_number=1, start_bonsai_ide=True):
logging.info("Creating Window")
# create warning widget
self.warning_log_tag = (
"warning_widget" # TODO: How to set this or does it matter?
)
super().__init__(parent)
# Process inputs
self.box_number = box_number
mapper = {
1: "A",
2: "B",
3: "C",
4: "D",
}
self.box_letter = mapper[box_number]
self.start_bonsai_ide = start_bonsai_ide
# Load Settings that are specific to this computer
self.SettingFolder = os.path.join(
os.path.expanduser("~"), "Documents", "ForagingSettings"
)
self.SettingFile = os.path.join(
self.SettingFolder, "ForagingSettings.json"
)
self.SettingsBoxFile = os.path.join(
self.SettingFolder, "Settings_box" + str(self.box_number) + ".csv"
)
self._GetSettings()
self._LoadSchedule()
# Load Settings that are specific to this box
self.LaserCalibrationFiles = os.path.join(
self.SettingFolder, "LaserCalibration_{}.json".format(box_number)
)
self.WaterCalibrationFiles = os.path.join(
self.SettingFolder, "WaterCalibration_{}.json".format(box_number)
)
self.WaterCalibrationParFiles = os.path.join(
self.SettingFolder,
"WaterCalibrationPar_{}.json".format(box_number),
)
# Load Laser and Water Calibration Files
self._GetLaserCalibration()
self._GetWaterCalibration()
# Load Rig Json
self._LoadRigJson()
# Load User interface
self._LoadUI()
# create AINDBehaviorSession model to be used and referenced for session info
self.behavior_session_model = AindBehaviorSessionModel(
experiment=self.Task.currentText(),
experimenter=[self.Experimenter.text()],
date=datetime.now(), # update when folders are created
root_path="", # update when created
session_name="", # update when date and subject are filled in
subject=self.ID.text(),
experiment_version=foraging_gui.__version__,
notes=self.ShowNotes.toPlainText(),
commit_hash=subprocess.check_output(["git", "rev-parse", "HEAD"])
.decode("ascii")
.strip(),
allow_dirty_repo=subprocess.check_output(
["git", "diff-index", "--name-only", "HEAD"]
)
.decode("ascii")
.strip()
!= "",
skip_hardware_validation=True,
)
# add warning_widget to layout and set color
self.warning_widget = WarningWidget(
log_tag=self.warning_log_tag,
warning_color=self.default_warning_color,
)
self.scrollArea_6.setWidget(self.warning_widget)
# set window title
self.setWindowTitle(self.rig_name)
logging.info("Setting Window title: {}".format(self.rig_name))
# Set up parameters
self.StartANewSession = 1 # to decide if should start a new session
self.ToInitializeVisual = 1 # Should we visualize performance
self.FigureUpdateTooSlow = 0 # if the FigureUpdateTooSlow is true, using different process to update figures
self.ANewTrial = 1 # permission to start a new trial
self.UpdateParameters = 1 # permission to update parameters
# -1, logging is not started; 0, formal logging; 1, temporary logging
self.logging_type = -1
self.previous_backup_completed = 1 # permission to save backup data; 0, the previous saving has not finished, and it will not trigger the next saving; 1, it is allowed to save backup data
self.unsaved_data = False # Setting unsaved data to False
self.to_check_drop_frames = 1 # 1, to check drop frames during saving data; 0, not to check drop frames
self.session_run = (
False # flag to indicate if session has been run or not
)
# Stage Widget
self.stage_widget = None
try:
self._load_stage()
except IOError as e:
msg = (
"ERROR...<br>"
"Dear scientist, please perform the following to document this issue:<br>"
" 1) Create comment here: <a href=https://github.com/AllenNeuralDynamics/dynamic-foraging-task/issues/925>Github Link</a><br>"
" 2) In the comment list the following information:<br> "
" - Date and time of error<br>"
" - Box info (ex. 6D)<br>"
" - Attach logs (found in C:\\Users\\svc_aind_behavior\\Documents\\foraging_gui_logs). Please add the two most recent files<br>"
" - Short description of the last thing done on the GUI before the error. (ex. overnight bleaching, closed gui, opened gui - error)<br>"
"Thank you, with your efforts hopefully we can vanquish this error and never see it again...<br>"
)
show_msg_box(
"Stage Widget Error", "Stage Widget Error Diagnostic Help", msg
)
raise e
# Connect to Bonsai
self._InitializeBonsai()
# Set up threads
self.threadpool = QThreadPool() # get animal response
self.threadpool2 = QThreadPool() # get animal lick
self.threadpool3 = QThreadPool() # visualization
self.threadpool4 = QThreadPool() # for generating a new trial
self.threadpool5 = QThreadPool() # for starting the trial loop
self.threadpool6 = QThreadPool() # for saving data
self.threadpool_workertimer = QThreadPool() # for timing
# initialize thread lock
self.data_lock = threading.Lock()
# intialize behavior baseline time flag
self.behavior_baseline_period = threading.Event()
self.baseline_min_elapsed = 0
# create bias indicator
self.bias_n_size = 200
self.bias_indicator = BiasIndicator(
x_range=self.bias_n_size, data_lock=self.data_lock
)
self.bias_indicator.biasValue.connect(
self.bias_calculated
) # update dashboard value
self.bias_indicator.setSizePolicy(
QSizePolicy.Maximum, QSizePolicy.Maximum
)
self.bias_thread = threading.Thread() # dummy thread
# create sound button
self.sound_button = SoundButton(
attenuation=int(self.SettingsBox["AttenuationLeft"])
)
self.toolBar_3.addWidget(self.sound_button)
# Set up more parameters
self.FIP_started = False
self.OpenOptogenetics = 0
self.OpenWaterCalibration = 0
self.OpenLaserCalibration = 0
self.OpenCamera = 0
self.OpenMetadata = 0
self.OpenRandomReward = 0
self.OpenOpticalTagging = 0
self.NewTrialRewardOrder = 0
self.LickSta = 0
self.LickSta_ToInitializeVisual = 1
self.TimeDistribution = 0
self.TimeDistribution_ToInitializeVisual = 1
self.finish_Timer = 1 # for photometry baseline recordings
self.PhotometryRun = 0 # 1. Photometry has been run; 0. Photometry has not been carried out.
self.ignore_timer = (
False # Used for canceling the photometry baseline timer
)
self.give_left_volume_reserved = 0 # the reserved volume of the left valve (usually given after go cue)
self.give_right_volume_reserved = 0 # the reserved volume of the right valve (usually given after go cue)
self.give_left_time_reserved = 0 # the reserved open time of the left valve (usually given after go cue)
self.give_right_time_reserved = 0 # the reserved open time of the right valve (usually given after go cue)
self.load_tag = (
0 # 1, a session has been loaded; 0, no session has been loaded
)
# the volume of manual water given by the left valve each time
self.Other_manual_water_left_volume = []
# the valve open time of manual water given by the left valve each time
self.Other_manual_water_left_time = []
# the volume of manual water given by the right valve each time
self.Other_manual_water_right_volume = []
# the valve open time of manual water given by the right valve each time
self.Other_manual_water_right_time = []
self._Optogenetics() # open the optogenetics panel
self._LaserCalibration() # to open the laser calibration panel
self._WaterCalibration() # to open the water calibration panel
self._Camera()
self._OpticalTagging()
self._RandomReward()
self._InitializeMotorStage()
self._Metadata()
self.RewardFamilies = [
[[8, 1], [6, 1], [3, 1], [1, 1]],
[[8, 1], [1, 1]],
[
[1, 0],
[0.9, 0.1],
[0.8, 0.2],
[0.7, 0.3],
[0.6, 0.4],
[0.5, 0.5],
],
[[6, 1], [3, 1], [1, 1]],
]
self.WaterPerRewardedTrial = 0.005
self._ShowRewardPairs() # show reward pairs
self._GetTrainingParameters() # get initial training parameters
self.connectSignalsSlots()
self._Task()
self.keyPressEvent()
self._WaterVolumnManage2()
self._LickSta()
self._warmup()
self.CreateNewFolder = (
1 # to create new folder structure (a new session)
)
self.ManualWaterVolume = [0, 0]
self._StopPhotometry() # Make sure photoexcitation is stopped
# Initialize open ephys saving dictionary
self.open_ephys = []
# load the rig metadata
self._load_rig_metadata()
# setup life-cycle logger
self.lifecycle_logger = self.setup_lifecycle_logger()
# Initializes session log handler as None
self.session_log_handler = None
# show disk space
self._show_disk_space()
if not self.start_bonsai_ide:
"""
When starting bonsai without the IDE the connection is always unstable.
Reconnecting solves the issue
"""
self._ReconnectBonsai()
logging.info("Start up complete")
def setup_lifecycle_logger(self) -> logging.Logger:
"""
Creates logger for start, stop, and failure events with formatter adhering to aind log standards.
"""
# Ensure the directory exists
os.makedirs(Path(self.Settings["lifecycle_log_dir"]), exist_ok=True)
lifecycle_logger = logging.getLogger("lifecycle")
lifecycle_logger.setLevel(logging.INFO)
timestamp = datetime.now().strftime("%Y%m%dT%H%M%SZ")
filename = f"lifecycle_log_{timestamp}.jsonl"
file_handler = logging.FileHandler(os.path.join(self.Settings["lifecycle_log_dir"], filename), encoding="utf-8")
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(log_schema.DefaultFormatter())
lifecycle_logger.addHandler(file_handler)
return lifecycle_logger
def _load_rig_metadata(self):
"""Load the latest rig metadata"""
rig_json, rig_json_file = self._load_most_recent_rig_json()
self.latest_rig_metadata_file = rig_json_file
self.Metadata_dialog._SelectRigMetadata(self.latest_rig_metadata_file)
def _show_disk_space(self):
"""Show the disk space of the current computer"""
total, used, free = shutil.disk_usage(self.default_saveFolder)
self.diskspace.setText(
f"Used space: {used / 1024**3:.2f}GB Free space: {free / 1024**3:.2f}GB"
)
self.DiskSpaceProgreeBar.setValue(int(used / total * 100))
if free / 1024**3 < 100 or used / total > 0.9:
self.DiskSpaceProgreeBar.setStyleSheet(
f"QProgressBar::chunk {{background-color: {self.default_warning_color};}}"
)
logging.warning(
f"Low disk space Used space: {used / 1024**3:.2f}GB Free space: {free / 1024**3:.2f}GB"
)
else:
self.DiskSpaceProgreeBar.setStyleSheet(
"QProgressBar::chunk {background-color: green;}"
)
def _load_stage(self) -> None:
"""
Check whether newscale stage is defined in the config. If not, initialize and inject stage widget.
"""
if (
self.Settings["newscale_serial_num_box{}".format(self.box_number)]
== ""
):
widget_to_replace = (
"motor_stage_widget"
if self.default_ui == "ForagingGUI_Ephys.ui"
else "widget_2"
)
self._insert_stage_widget(widget_to_replace)
self.stage_widget.stage_model.initialize_stage()
else:
self._GetPositions()
def _insert_stage_widget(self, widget_to_replace: str) -> None:
"""
Given a widget name, replace all contents of that widget with the stage widget
Note: The UI file must be loaded or else it can't find the widget to replace
Also the widget to replace must contain a layout so it can hide all child widgets properly.
"""
logging.info("Inserting Stage Widget")
# Get QWidget object
widget = getattr(self, widget_to_replace, None)
if widget is not None:
layout = widget.layout()
# Hide all current items within widget being replaced
for i in reversed(range(layout.count())):
layout.itemAt(i).widget().setVisible(False)
# Insert new stage_widget
self.stage_widget = get_stage_widget()
layout.addWidget(self.stage_widget)
def _LoadUI(self):
"""
Determine which user interface to use
"""
uic.loadUi(self.default_ui, self)
if self.default_ui == "ForagingGUI.ui":
logging.info("Using ForagingGUI.ui interface")
self.label_date.setText(str(date.today()))
self.default_warning_color = "purple"
self.default_text_color = "purple"
self.default_text_background_color = "purple"
elif self.default_ui == "ForagingGUI_Ephys.ui":
logging.info("Using ForagingGUI_Ephys.ui interface")
self.Visualization.setTitle(str(date.today()))
self.default_warning_color = "red"
self.default_text_color = "red"
self.default_text_background_color = "red"
else:
logging.info("Using ForagingGUI.ui interface")
self.default_warning_color = "red"
self.default_text_color = "red"
self.default_text_background_color = "red"
def connectSignalsSlots(self):
"""Define callbacks"""
self.action_About.triggered.connect(self._about)
self.action_Camera.triggered.connect(self._Camera)
# create QTimer to deliver constant tone
self.beep_loop = QtCore.QTimer(timeout=self.play_beep, interval=10)
self.sound_button.toggled.connect(
lambda checked: (
self.beep_loop.start() if checked else self.beep_loop.stop()
)
)
self.sound_button.attenuationChanged.connect(self.change_attenuation)
self.actionMeta_Data.triggered.connect(self._Metadata)
self.actionOptical_Tagging.triggered.connect(self._OpticalTagging)
self.actionRandom_Reward.triggered.connect(self._RandomReward)
self.action_Optogenetics.triggered.connect(self._Optogenetics)
self.actionLicks_sta.triggered.connect(self._LickSta)
self.actionTime_distribution.triggered.connect(self._TimeDistribution)
self.action_Calibration.triggered.connect(self._WaterCalibration)
self.actionLaser_Calibration.triggered.connect(self._LaserCalibration)
self.action_Open.triggered.connect(self._Open)
self.action_Save.triggered.connect(self._Save)
self.actionForce_save.triggered.connect(self._ForceSave)
self.SaveAs.triggered.connect(self._SaveAs)
self.Save_continue.triggered.connect(self._Save_continue)
self.action_Exit.triggered.connect(self._Exit)
self.action_New.triggered.connect(self._NewSession)
self.action_Clear.triggered.connect(self._Clear)
self.action_Start.triggered.connect(self.Start.click)
self.action_NewSession.triggered.connect(self.NewSession.click)
self.actionConnectBonsai.triggered.connect(self._ConnectBonsai)
self.actionReconnect_bonsai.triggered.connect(self._ReconnectBonsai)
self.Load.clicked.connect(self._OpenLast)
self.Save.setCheckable(True)
self.Save.clicked.connect(self._Save)
self.Clear.clicked.connect(self._Clear)
self.Start.clicked.connect(self._Start)
self.GiveLeft.clicked.connect(self._GiveLeft)
self.GiveRight.clicked.connect(self._GiveRight)
self.NewSession.clicked.connect(self._NewSession)
self.AutoReward.clicked.connect(self._AutoReward)
self.StartFIP.clicked.connect(self._StartFIP)
self.StartExcitation.clicked.connect(self._StartExcitation)
self.StartBleaching.clicked.connect(self._StartBleaching)
self.NextBlock.clicked.connect(self._NextBlock)
self.OptogeneticsB.activated.connect(
self._OptogeneticsB
) # turn on/off optogenetics
self.OptogeneticsB.currentIndexChanged.connect(
lambda: self._QComboBoxUpdate(
"Optogenetics", self.OptogeneticsB.currentText()
)
)
self.PhotometryB.currentIndexChanged.connect(
lambda: self._QComboBoxUpdate(
"Photometry", self.PhotometryB.currentText()
)
)
self.FIPMode.currentIndexChanged.connect(
lambda: self._QComboBoxUpdate(
"FIPMode", self.FIPMode.currentText()
)
)
self.AdvancedBlockAuto.currentIndexChanged.connect(self._keyPressEvent)
self.AutoWaterType.currentIndexChanged.connect(self._keyPressEvent)
self.UncoupledReward.textChanged.connect(self._ShowRewardPairs)
self.UncoupledReward.returnPressed.connect(self._ShowRewardPairs)
# Connect to ID change in the mainwindow
self.ID.returnPressed.connect(
lambda: self.AutoTrain_dialog.update_auto_train_lock(engaged=False)
)
self.ID.returnPressed.connect(
lambda: self.AutoTrain_dialog.update_auto_train_fields(
subject_id=self.behavior_session_model.subject,
auto_engage=self.auto_engage,
)
)
self.AutoTrain.clicked.connect(self._auto_train_clicked)
self.pushButton_streamlit.clicked.connect(
self._open_mouse_on_streamlit
)
self.Task.currentIndexChanged.connect(self._ShowRewardPairs)
self.Task.currentIndexChanged.connect(self._Task)
self.AdvancedBlockAuto.currentIndexChanged.connect(
self._AdvancedBlockAuto
)
self.TargetRatio.textChanged.connect(self._UpdateSuggestedWater)
self.WeightAfter.textChanged.connect(self._PostWeightChange)
self.BaseWeight.textChanged.connect(self._UpdateSuggestedWater)
self.Randomness.currentIndexChanged.connect(self._Randomness)
self.actionTemporary_Logging.triggered.connect(
self._startTemporaryLogging
)
self.actionFormal_logging.triggered.connect(self._startFormalLogging)
self.actionOpen_logging_folder.triggered.connect(
self._OpenLoggingFolder
)
self.actionOpen_behavior_folder.triggered.connect(
self._OpenBehaviorFolder
)
self.actionOpenSettingFolder.triggered.connect(self._OpenSettingFolder)
self.actionOpen_rig_metadata_folder.triggered.connect(
self._OpenRigMetadataFolder
)
self.actionOpen_metadata_dialog_folder.triggered.connect(
self._OpenMetadataDialogFolder
)
self.actionOpen_video_folder.triggered.connect(self._OpenVideoFolder)
self.LeftValue.textChanged.connect(self._WaterVolumnManage1)
self.RightValue.textChanged.connect(self._WaterVolumnManage1)
self.LeftValue_volume.textChanged.connect(self._WaterVolumnManage2)
self.RightValue_volume.textChanged.connect(self._WaterVolumnManage2)
self.MoveXP.clicked.connect(self._MoveXP)
self.MoveYP.clicked.connect(self._MoveYP)
self.MoveZP.clicked.connect(self._MoveZP)
self.MoveXN.clicked.connect(self._MoveXN)
self.MoveYN.clicked.connect(self._MoveYN)
self.MoveZN.clicked.connect(self._MoveZN)
self.StageStop.clicked.connect(self._StageStop)
self.GetPositions.clicked.connect(self._GetPositions)
self.ShowNotes.setStyleSheet("background-color: #F0F0F0;")
self.warmup.currentIndexChanged.connect(self._warmup)
self.Sessionlist.currentIndexChanged.connect(self._session_list)
self.SessionlistSpin.textChanged.connect(self._session_list_spin)
self.StartEphysRecording.clicked.connect(self._StartEphysRecording)
self.SetReference.clicked.connect(self._set_reference)
self.Opto_dialog.laser_1_calibration_voltage.textChanged.connect(
self._toggle_save_color
)
self.Opto_dialog.laser_2_calibration_voltage.textChanged.connect(
self._toggle_save_color
)
self.Opto_dialog.laser_1_calibration_power.textChanged.connect(
self._toggle_save_color
)
self.Opto_dialog.laser_2_calibration_power.textChanged.connect(
self._toggle_save_color
)
# update parameters in behavior session model if widgets change
self.Task.currentTextChanged.connect(
lambda task: setattr(
self.behavior_session_model, "experiment", task
)
)
self.Experimenter.textChanged.connect(
lambda text: setattr(
self.behavior_session_model, "experimenter", [text]
)
)
self.Experimenter.returnPressed.connect(self.validate_experimenter)
self.ID.textChanged.connect(
lambda subject: setattr(
self.behavior_session_model, "subject", subject
)
)
self.ShowNotes.textChanged.connect(
lambda: setattr(
self.behavior_session_model,
"notes",
self.ShowNotes.toPlainText(),
)
)
# Set manual water volume to earned reward and trigger update if changed
for side in ["Left", "Right"]:
reward_volume_widget = getattr(self, f"{side}Value_volume")
manual_volume_widget = getattr(self, f"GiveWater{side[0]}_volume")
manual_volume_widget.setValue(reward_volume_widget.value())
reward_volume_widget.valueChanged.connect(
manual_volume_widget.setValue
)
reward_time_widget = getattr(self, f"{side}Value")
manual_time_widget = getattr(self, f"GiveWater{side[0]}")
manual_time_widget.setValue(reward_time_widget.value())
reward_time_widget.valueChanged.connect(
manual_time_widget.setValue
)
# check the change of all of the QLineEdit, QDoubleSpinBox and QSpinBox
for container in [
self.TrainingParameters,
self.centralwidget,
self.Opto_dialog,
self.Metadata_dialog,
]:
# Iterate over each child of the container that is a QLineEdit or QDoubleSpinBox
for child in container.findChildren(
(
QtWidgets.QLineEdit,
QtWidgets.QDoubleSpinBox,
QtWidgets.QSpinBox,
)
):
child.textChanged.connect(self._CheckTextChange)
for child in container.findChildren((QtWidgets.QComboBox)):
child.currentIndexChanged.connect(self.keyPressEvent)
# Opto_dialog can not detect natural enter press, so returnPressed is used here.
for container in [self.Opto_dialog, self.Metadata_dialog]:
# Iterate over each child of the container that is a QLineEdit or QDoubleSpinBox
for child in container.findChildren((QtWidgets.QLineEdit)):
child.returnPressed.connect(self.keyPressEvent)
def validate_experimenter(self):
"""Function to validate username and reset Experimentor textbox if invalide"""
try:
is_valid = validate_aind_username(self.Experimenter.text())
if not is_valid:
errorbox = QtWidgets.QMessageBox()
errorbox.setWindowTitle("Invalid Experimenter Name")
errorbox.setText(f"Experimenter name {self.Experimenter.text()} does not match any username in "
f"corp.alleninstitute.org. Please try again with your Allen Institute credentials. ")
errorbox.exec_()
self.Experimenter.clear()
except Exception as e:
errorbox = QtWidgets.QMessageBox()
errorbox.setWindowTitle("Error with Validation")
errorbox.setText(f"Cannot validate experimenter name.")
errorbox.exec_()
def _set_reference(self):
"""
set the reference point for lick spout position in the metadata dialog
"""
# get the current position of the stage
current_positions = self._GetPositions()
# set the reference point for lick spout position in the metadata dialog
if current_positions is not None:
self.Metadata_dialog._set_reference(current_positions)
def _StartEphysRecording(self):
"""
Start/stop ephys recording
"""
if self.open_ephys_machine_ip_address == "":
QMessageBox.warning(
self,
"Connection Error",
"Empty ip address for Open Ephys Computer. Please check the settings file.",
)
self.StartEphysRecording.setChecked(False)
self._toggle_color(self.StartEphysRecording)
return
if (
self.Start.isChecked() or self.ANewTrial == 0
) and self.StartEphysRecording.isChecked():
reply = QMessageBox.question(
self,
"",
"Behavior has started! Do you want to start ephys recording?",
QMessageBox.No | QMessageBox.No,
QMessageBox.Yes,
)
if reply == QMessageBox.Yes:
pass
elif reply == QMessageBox.No:
self.StartEphysRecording.setChecked(False)
self._toggle_color(self.StartEphysRecording)
return
EphysControl = EphysRecording(
open_ephys_machine_ip_address=self.open_ephys_machine_ip_address,
mouse_id=self.behavior_session_model.subject,
)
if self.StartEphysRecording.isChecked():
try:
if EphysControl.get_status()["mode"] == "RECORD":
QMessageBox.warning(
self,
"",
"Open Ephys is already recording! Please stop the recording first.",
)
self.StartEphysRecording.setChecked(False)
self._toggle_color(self.StartEphysRecording)
return
EphysControl.start_open_ephys_recording()
self.openephys_start_recording_time = str(datetime.now())
QMessageBox.warning(
self,
"",
f"Open Ephys has started recording!\n Recording type: {self.OpenEphysRecordingType.currentText()}",
)
except Exception:
logging.error(traceback.format_exc())
self.StartEphysRecording.setChecked(False)
QMessageBox.warning(
self,
"Connection Error",
"Failed to connect to Open Ephys. Please check: \n1) the correct ip address is included in the settings json file. \n2) the Open Ephys software is open.",
)
else:
try:
if EphysControl.get_status()["mode"] != "RECORD":
QMessageBox.warning(
self,
"",
"Open Ephys is not recording! Please start the recording first.",
)
self.StartEphysRecording.setChecked(False)
self._toggle_color(self.StartEphysRecording)
return
if self.Start.isChecked() or self.ANewTrial == 0:
reply = QMessageBox.question(
self,
"",
"The behavior hasn’t stopped yet! Do you want to stop ephys recording?",
QMessageBox.No | QMessageBox.No,
QMessageBox.Yes,
)
if reply == QMessageBox.Yes:
pass
elif reply == QMessageBox.No:
self.StartEphysRecording.setChecked(True)
self._toggle_color(self.StartEphysRecording)
return
self.openephys_stop_recording_time = str(datetime.now())
response = (
EphysControl.get_open_ephys_recording_configuration()
)
response["openephys_start_recording_time"] = (
self.openephys_start_recording_time
)
response["openephys_stop_recording_time"] = (
self.openephys_stop_recording_time
)
response["recording_type"] = (
self.OpenEphysRecordingType.currentText()
)
self.open_ephys.append(response)
self.unsaved_data = True
self.Save.setStyleSheet(
"color: white;background-color : mediumorchid;"
)
EphysControl.stop_open_ephys_recording()
QMessageBox.warning(
self,
"",
"Open Ephys has stopped recording! Please save the data again!",
)
except Exception:
logging.error(traceback.format_exc())
QMessageBox.warning(
self,
"Connection Error",
"Failed to stop Open Ephys recording. Please check: \n1) the open ephys software is still running",
)
self._toggle_color(self.StartEphysRecording)
def _toggle_color(
self,
widget,
check_color="background-color : green;",
unchecked_color="background-color : none",
):
"""
Toggle the color of the widget.
Parameters
----------
widget : QtWidgets.QWidget
If Checked, sets the color to green. If unchecked, sets the color to None.
Returns
-------
None
"""
if widget.isChecked():
widget.setStyleSheet(check_color)
else:
widget.setStyleSheet(unchecked_color)
def _manage_warning_labels(self, warning_labels, warning_text=""):
"""
Manage the warning labels.
If there is a warning, set the color to self.default_warning_color. If there is no warning, set the text to ''.
Parameters
----------
warning_label : single QtWidgets.QLabel or list of QtWidgets.QLabel
The warning label to manage
warning_text : str
The warning text to display
Returns
-------
None
"""
if not isinstance(warning_labels, list):
warning_labels = [warning_labels]
for warning_label in warning_labels:
warning_label.setText(warning_text)
warning_label.setStyleSheet(
f"color: {self.default_warning_color};"
)
def _session_list(self):
"""show all sessions of the current animal and load the selected session by drop down list"""
if not hasattr(self, "fname"):
return 0
# open the selected session
if self.Sessionlist.currentText() != "":
selected_index = self.Sessionlist.currentIndex()
fname = self.session_full_path_list[
self.Sessionlist.currentIndex()
]
self._Open(input_file=fname)
# set the selected index back to the current session
self._connect_Sessionlist(connect=False)
self.Sessionlist.setCurrentIndex(selected_index)
self.SessionlistSpin.setValue(int(selected_index + 1))
self._connect_Sessionlist(connect=True)
def _session_list_spin(self):
"""show all sessions of the current animal and load the selected session by spin box"""
if not hasattr(self, "fname"):
return 0
if self.SessionlistSpin.text() != "":
self._connect_Sessionlist(connect=False)
if int(self.SessionlistSpin.text()) > self.Sessionlist.count():
self.SessionlistSpin.setValue(int(self.Sessionlist.count()))
if int(self.SessionlistSpin.text()) < 1:
self.SessionlistSpin.setValue(1)
fname = self.session_full_path_list[
int(self.SessionlistSpin.text()) - 1
]
self.Sessionlist.setCurrentIndex(
int(self.SessionlistSpin.text()) - 1
)
self._connect_Sessionlist(connect=True)
self._Open(input_file=fname)
def _connect_Sessionlist(self, connect=True):
"""connect or disconnect the Sessionlist and SessionlistSpin"""
if connect:
self.Sessionlist.currentIndexChanged.connect(self._session_list)
self.SessionlistSpin.textChanged.connect(self._session_list_spin)
else:
self.Sessionlist.disconnect()
self.SessionlistSpin.disconnect()
def _show_sessions(self):
"""list all sessions of the current animal"""
if not hasattr(self, "fname"):
return 0
animal_folder = os.path.dirname(
os.path.dirname(os.path.dirname(self.fname))
)
session_full_path_list = []
session_path_list = []
for session_folder in os.listdir(animal_folder):
training_folder_old = os.path.join(
animal_folder, session_folder, "TrainingFolder"
)
training_folder_new = os.path.join(
animal_folder, session_folder, "behavior"
)
if os.path.exists(training_folder_old):
for file_name in os.listdir(training_folder_old):
if file_name.endswith(".json"):
session_full_path_list.append(
os.path.join(training_folder_old, file_name)
)
session_path_list.append(session_folder)
elif os.path.exists(training_folder_new):
for file_name in os.listdir(training_folder_new):
if file_name.endswith(".json"):
session_full_path_list.append(
os.path.join(training_folder_new, file_name)
)
session_path_list.append(session_folder)
sorted_indices = sorted(
enumerate(session_path_list), key=lambda x: x[1], reverse=True
)
sorted_dates = [date for index, date in sorted_indices]
# Extract just the indices
indices = [index for index, date in sorted_indices]
# Apply sorted index
self.session_full_path_list = [
session_full_path_list[index] for index in indices
]
self.session_path_list = sorted_dates
self._connect_Sessionlist(connect=False)
self.Sessionlist.clear()
self.Sessionlist.addItems(sorted_dates)
self._connect_Sessionlist(connect=True)
def _check_drop_frames(self, save_tag=1):
"""Check if there are any dropped frames in the video.
This function supports two folder structures inside `video_folder`:
1) Flat structure:
video_folder/
CameraA.avi
CameraA.csv
CameraB.avi
CameraB.csv
Here, CameraA and CameraB are camera names.
2) Nested structure:
video_folder/
CameraA/
video.mp4
metadata.csv
CameraB/
video.mp4
metadata.csv
Here, the subfolder name (e.g. 'CameraA') is the camera name, and
frame counts are taken from 'metadata.csv'.
"""
if self.to_check_drop_frames == 1:
return_tag = 0
# If we are loading from an existing object (save_tag == 0),