-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFISH2_peripherals.py
1468 lines (1290 loc) · 57.6 KB
/
FISH2_peripherals.py
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
#Python 3 package to manage Peripheral functions of FISH system 2.
#Date: 14 October 2016
#Author: Lars E. Borm
#E-mail: [email protected] or [email protected]
#Python version: 3.5.1
#Used by both the User program and the Excecute FISH program.
## CONTENT ###
# FISH_logger class
# Sending messages using Pushbullet
# Managing .yaml files
# Managing sqlite3 database
# Transport data from .yaml datafile to database
# User add new data to .yaml datafile and transport to database
# Remove experiment from .yaml datafile and database
#=============================================================================
# Dependencies
#=============================================================================
#Logger
import logging
import time
import os
#Sending messages
from pushbullet import Pushbullet
#handle .yaml files
import yaml
#Use ruamel.yaml to dynamically update files (https://yaml.readthedocs.io)
import ruamel.yaml
from ruamel.yaml.util import load_yaml_guess_indent
import collections
#Database
import sqlite3
#User update
from tkinter import *
#=============================================================================
# System specific input, change if needed.
#=============================================================================
#File indicating if a sample can be imaged.
#If not present please make a text file with a single "0" in it.
#Put the full path to the folder and file here:
start_imaging_file_path = "C:\\Users\\Nikon\\Desktop\\FISH_Sys_2\\FISH_database\\Start_Imaging_File.txt"
#=============================================================================
# Logger
#=============================================================================
class FISH_logger():
# Based on the code of Josina A. van Lunteren (2016)
"""Logger for FISH System 2"""
def __init__(self, verbose = True, folder_name = 'log_files', system_name =
'ROBOFISH', log_level = logging.INFO, console_level = logging.INFO):
"""
Input:
`verbose`(bool): If True, prints that is made the logger.
`folder_name` (str): Folder name (not path) to store the log files.
`system_name`(str): Name of system used
`log_level`(logging.___): level to logg, default "logging.DEBUG"
`console_level`(logging.___): level to print, default "logging.INFO"
"""
# Redirect warnings to logger
logging.captureWarnings(True)
# Create logger
self.logger = logging.getLogger()
self.logger.setLevel(log_level)
formatter_file = logging.Formatter('%(asctime)s - %(levelname)s: %(message)s')
formatter_con = logging.Formatter('%(message)s')
log_path = folder_name
# Create file
try:
os.stat(log_path)
except:
os.mkdir(log_path)
if os.name == 'posix':
os.chmod(log_path,0o777) #LINUX UNIX specific!
if not os.path.exists(log_path):
os.makedirs(log_path)
dateTag = time.strftime("%Y-%b-%d_%H-%M-%S")
self.logger_path = '{}/{}_{}.log'.format(log_path, dateTag, system_name)
self.fh = logging.FileHandler(self.logger_path, mode = 'w')
if verbose == True:
print('Logger created. path: ', self.logger_path)
# Set logger properties
self.fh.setLevel(log_level)
self.fh.setFormatter(formatter_file)
self.logger.addHandler(self.fh)
# Print logging to console
ch = logging.StreamHandler()
ch.setLevel(console_level)
ch.setFormatter(formatter_con)
self.logger.addHandler(ch)
#=============================================================================
# Sending / receiving Push messages
#=============================================================================
# Prepare and send Push notification via Pushbullet
# Using https://www.pushbullet.com/ together with the python interface https://github.com/randomchars/pushbullet.py
def send_push(pushbullet_address_book, operator = 'lars', short_message = '', long_message = ''):
"""
Send a push messages to the operator using the Pushbullet service.
Input:
`pushbullet_address_book`(dict): Dictionary with the operator(s) and the
access tokens..
`operator`(str): name of the operator.
`short_message`(str): message title
`long_message`(str): full message
To add operators add their name and Pushbullet Access token to the
pushbullet_address_book. Make an account on: https://www.pushbullet.com/,
goto settings, create and add."
"""
address = pushbullet_address_book[operator.lower()]
try:
pb = Pushbullet(address)
push = pb.push_note(short_message, long_message)
except Exception as e:
print ("Error, Unable to send push message. Error message: ", e)
def get_push(pushbullet_address_book, operator = 'lars', limit=1):
"""
Get the last X push messages from the operator.
Input:
`pushbullet_address_book`(dict): Dictionary with the operator(s) and the
access tokens.
`operator`(str): name of the operator.
`limit`(int): Number of last messages to receive
Returns:
`message body`(str): Retruns the message body. Take note that this is
the last message, it can be a message the user send to the computer,
but it can also be a previously send message if the user did not reply.
To add operators add their name and Pushbullet Access token to the
pushbullet_address_book. Make an account on: https://www.pushbullet.com/,
goto settings, create and add."
"""
address = pushbullet_address_book[operator.lower()]
try:
pb = Pushbullet(address)
return pb.get_pushes(limit=1)[0]['body']
except Exception as e:
print ("Error, Unable to receive push message. Error message: ", e)
#=============================================================================
# Managing .yaml files
#=============================================================================
def yamlMake(filepath, new={}):
"""
Make a .yaml file and dump a dictionary.
Input:
`filepath`(str): Full filepath with file name.
`new`(dict): New dictionary to dump to the file
"""
with open(filepath, 'w') as new_yaml_file:
ruamel.yaml.dump(new, new_yaml_file, default_flow_style=False)
def yamlLoader(filepath):
"""
Loads .yaml datafile into python dictionaries. (without comments)
Input:
`filepaht`(str): Path to .yaml datafile
"""
try:
with open(filepath, 'r') as file_descriptor:
data = yaml.load(file_descriptor, Loader=yaml.FullLoader)
return data
except Exception as e:
print('\nCould not correctly open the .yaml file')
print('''The file needs to be formatted consistently. There needs to
be a space between key and value: key:_value''')
print('Error code:\n', e)
def updateDict(dictionary, new):
"""
Update function for nested dictionaries.
Input:
`dictionary`(dict): dictionary to update
`new`(dict): value to update, including all layers of nested dict. Like:
{'Level1':{'Level2':{'Level3':{'key1':'new_value'}}}}
"""
#from: http://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth
for key, value in new.items():
if isinstance(value, collections.Mapping):
r = updateDict(dictionary.get(key, {}), value)
dictionary[key] = r
else:
dictionary[key] = new[key]
return dictionary
def yamlUpdate(filepath, new, file_extension=None):
"""
Update function for .yaml files with nested dictionaries.
Input:
`filepath`(str): Name of .yaml datafile.
`new`(dict): value to update, including all layers of nested dict. Like:
{'Level1':{'Level2':{'Level3':{'key1':'new_value'}}}}
`file_extension`(str):Optional file extension for new file.
"""
with open(filepath, "r") as yaml_file:
config, ind, bsi = load_yaml_guess_indent(yaml_file)
#use 'updateDict' function that can update one value in a nested dict.
updateDict(config, new)
if file_extension != None:
new_name = (filepath.split('.')[0] + file_extension +
'.' + filepath.split('.')[1])
else:
new_name = filepath
with open(new_name, 'w') as updated_yaml_file:
ruamel.yaml.round_trip_dump(config ,updated_yaml_file,
indent=ind, block_seq_indent=bsi)
def getFISHSystemMetadata(filename, table=None):
"""
Get metadata from .yaml datafile.
Input:
`filename`(str): Filename of .yamle datafile.
`table`(str) Optional: Specific table to return as dictionary.
Returns:
requested dictionary if table is provided
Else 10 dictionaries:
"Parameters", "Volumes", "Targets", "Ports", "Hybmix",
"Machines", "Machine_identification", "Fixed_USB_port", "Operator_address",
"Padding", "Alert_volume"
"""
try:
metadata = yamlLoader(filename)
except Exception as e:
print('Unable to load metadata file: {}'.format(filename))
if table == 'Parameters':
return metadata['FISHSystem']['Parameters']
elif table == 'Volumes':
return metadata['FISHSystem']['Volumes']
elif table == 'Targets':
return metadata['FISHSystem']['Targets']
elif table == 'Ports':
return metadata['FISHSystem']['Ports']
elif table == 'Hybmix':
return metadata['FISHSystem']['Hybmix']
elif table == 'Machines':
return metadata['FISHSystem']['Machines']
elif table == 'Machine_identification':
return metadata['FISHSystem']['Machine_identification']
elif table == 'Fixed_USB_port':
return metadata['FISHSystem']['Fixed_USB_port']
elif table == 'Operator_address':
return metadata['FISHSystem']['Operator_address']
elif table == 'Padding':
return metadata['FISHSystem']['Padding']
elif table == 'Alert_volume':
return metadata['FISHSystem']['Alert_volume']
else:
return (metadata['FISHSystem']['Parameters'],
metadata['FISHSystem']['Volumes'],
metadata['FISHSystem']['Targets'],
metadata['FISHSystem']['Ports'],
metadata['FISHSystem']['Hybmix'],
metadata['FISHSystem']['Machines'],
metadata['FISHSystem']['Machine_identification'],
metadata['FISHSystem']['Fixed_USB_port'],
metadata['FISHSystem']['Operator_address'],
metadata['FISHSystem']['Padding'],
metadata['FISHSystem']['Alert_volume'])
#=============================================================================
# Make a sqlite3 database for FISH2 System
#=============================================================================
def newFISHdb(db_name):
"""
Make a new database for the FISH2 system.
Creates tables for: Flags, Parameters, Volumes, Targets, Ports, Hybmix and
Padding. Fills them with empty values, and if the db already exists, it
deletes all values.
Input:
`db_name`(str): Name of the database.
Returns:
`FISH_db_path`(str): Path to the (newly created) database.
"""
#Check if db folder exists, otherwise create
cwd = os.getcwd() #Current working directory
FISH_db_folder = cwd + '\FISH_database' #Backslash for Windows
if not os.path.exists(FISH_db_folder):
os.makedirs(FISH_db_folder)
#Database name
if not db_name.endswith('.sqlite'):
db_name = db_name + '.sqlite'
#Check if FISH_exp_db exists, otherwise create
FISH_db_path = FISH_db_folder + '\\' + db_name
if not os.path.isfile(FISH_db_path):
print('No existing database found in location {}. New will be made...'.format(FISH_db_path))
conn = sqlite3.connect(FISH_db_path)
with conn:
cursor = conn.cursor()
#Flags
cursor.execute("""CREATE TABLE Flags
(Pause_flag INTEGER,
New_EXP_flag_1 INTEGER,
New_EXP_flag_2 INTEGER,
Parameters_flag INTEGER,
Volumes_flag INTEGER,
Targets_flag INTEGER,
Ports_flag INTEGER,
Hybmix_flag INTEGER,
Machines_flag INTEGER,
Machine_identification_flag INTEGER,
Fixed_USB_port_flag INTEGER,
Operator_address_flag INTEGER,
Padding_flag INTEGER,
Alert_volume_flag INTEGER,
RunningBuffer INTEGER,
P1 INTEGER,
P2 INTEGER,
P3 INTEGER,
P4 INTEGER,
P5 INTEGER,
P6 INTEGER,
P7 INTEGER,
P8 INTEGER,
P9 INTEGER,
P10 INTEGER,
P11 INTEGER,
P12 INTEGER,
P13 INTEGER,
P14 INTEGER,
P15 INTEGER,
P16 INTEGER,
P17 INTEGER,
P18 INTEGER,
P19 INTEGER,
P20 INTEGER)""")
cursor.execute("INSERT INTO Flags DEFAULT VALUES")
#Parameters
cursor.execute("""CREATE TABLE Parameters
(Operator TEXT,
Machine TEXT,
EXP_name_1 TEXT,
Description_1 TEXT,
Protocols_io_1 TEXT,
Start_date_1 TEXT,
Chamber_EXP_1 TEXT,
Hyb_time_1_A REAL,
Hyb_time_1_B REAL,
Hyb_time_1_C REAL,
Experiment_type_1 TEXT,
Target_cycles_1 INTEGER,
Barcode_1 TEXT,
Chemistry_1 TEXT,
Probes_FASTA_DAPI_1 TEXT,
Probes_FASTA_Atto425_1 TEXT,
Probes_FASTA_FITC_1 TEXT,
Probes_FASTA_Cy3_1 TEXT,
Probes_FASTA_TxRed_1 TEXT,
Probes_FASTA_Cy5_1 TEXT,
Probes_FASTA_Cy7_1 TEXT,
Probes_FASTA_Europium_1 TEXT,
Codebook_DAPI_1 TEXT,
Codebook_Atto425_1 TEXT,
Codebook_FITC_1 TEXT,
Codebook_Cy3_1 TEXT,
Codebook_TxRed_1 TEXT,
Codebook_Cy5_1 TEXT,
Codebook_Cy7_1 TEXT,
Codebook_Europium_1 TEXT,
Multicolor_barcode_1 TEXT,
Barcode_length_1 INTEGER,
Species_1 TEXT,
Strain_1 TEXT,
Sample_1 TEXT,
Age_1 TEXT,
Tissue_1 TEXT,
Orientation_1 TEXT,
RegionImaged_1 TEXT,
SectionID_1 TEXT,
Position_1 TEXT,
Stitching_type_1 TEXT,
StitchingChannel_1 TEXT,
Overlapping_percentage_1 TEXT,
roi_1 TEXT,
Pipeline_1 TEXT,
EXP_name_2 TEXT,
Description_2 TEXT,
Protocols_io_2 TEXT,
Start_date_2 TEXT,
Chamber_EXP_2 TEXT,
Hyb_time_2_A REAL,
Hyb_time_2_B REAL,
Hyb_time_2_C REAL,
Experiment_type_2 TEXT,
Target_cycles_2 INTEGER,
Barcode_2 TEXT,
Chemistry_2 TEXT,
Probes_FASTA_DAPI_2 TEXT,
Probes_FASTA_Atto425_2 TEXT,
Probes_FASTA_FITC_2 TEXT,
Probes_FASTA_Cy3_2 TEXT,
Probes_FASTA_TxRed_2 TEXT,
Probes_FASTA_Cy5_2 TEXT,
Probes_FASTA_Cy7_2 TEXT,
Probes_FASTA_Europium_2 TEXT,
Codebook_DAPI_2 TEXT,
Codebook_Atto425_2 TEXT,
Codebook_FITC_2 TEXT,
Codebook_Cy3_2 TEXT,
Codebook_TxRed_2 TEXT,
Codebook_Cy5_2 TEXT,
Codebook_Cy7_2 TEXT,
Codebook_Europium_2 TEXT,
Multicolor_barcode_2 TEXT,
Barcode_length_2 INTEGER,
Species_2 TEXT,
Strain_2 TEXT,
Sample_2 TEXT,
Age_2 TEXT,
Tissue_2 TEXT,
Orientation_2 TEXT,
RegionImaged_2 TEXT,
SectionID_2 TEXT,
Position_2 TEXT,
Stitching_type_2 TEXT,
StitchingChannel_2 TEXT,
Overlapping_percentage_2 TEXT,
roi_2 TEXT,
Pipeline_2 TEXT,
Program TEXT,
Hybmix_volume INTEGER,
Staining_temperature REAL,
Readout_temperature REAL,
Heatshock_temperature REAL,
Stripping_temperature REAL,
Imaging_temperature REAL)""")
cursor.execute("INSERT INTO Parameters DEFAULT VALUES")
#Buffer volumes
cursor.execute("""CREATE TABLE Volumes
(RunningBuffer REAL,
P1 REAL,
P2 REAL,
P3 REAL,
P4 REAL,
P5 REAL,
P6 REAL,
P7 REAL,
P8 REAL,
P9 REAL,
P10 REAL,
P11 REAL,
P12 REAL,
P13 REAL,
P14 REAL,
P15 REAL,
P16 REAL,
P17 REAL,
P18 REAL,
P19 REAL,
P20 REAL)""")
cursor.execute("INSERT INTO Volumes DEFAULT VALUES")
#Ports
cursor.execute("""CREATE TABLE Ports
(RunningBuffer TEXT,
P1 TEXT,
P2 TEXT,
P3 TEXT,
P4 TEXT,
P5 TEXT,
P6 TEXT,
P7 TEXT,
P8 TEXT,
P9 TEXT,
P10 TEXT,
P11 TEXT,
P12 TEXT,
P13 TEXT,
P14 TEXT,
P15 TEXT,
P16 TEXT,
P17 TEXT,
P18 TEXT,
P19 TEXT,
P20 TEXT)""")
cursor.execute("INSERT INTO Ports DEFAULT VALUES")
#Hyb mix, couples port code (PX) with Hybridization code (Cx_Y)X=chamber number, Y=cycle
cursor.execute("""CREATE TABLE Hybmix
(P1 TEXT,
P2 TEXT,
P3 TEXT,
P4 TEXT,
P5 TEXT,
P6 TEXT,
P7 TEXT,
P8 TEXT,
P9 TEXT,
P10 TEXT,
P11 TEXT,
P12 TEXT,
P13 TEXT,
P14 TEXT,
P15 TEXT,
P16 TEXT,
P17 TEXT,
P18 TEXT,
P19 TEXT,
P20 TEXT)""")
cursor.execute("INSERT INTO Hybmix DEFAULT VALUES")
#Targets, genes/channel
cursor.execute("""CREATE TABLE Targets
(Code TEXT,
Chamber INTEGER,
Hybridization TEXT,
DAPI TEXT,
Atto425 TEXT,
FITC TEXT,
Cy3 TEXT,
TxRed TEXT,
Cy5 TEXT,
Cy7 TEXT,
QDot TEXT,
BrightField TEXT,
Europium TEXT)""")
cursor.execute("INSERT INTO Targets DEFAULT VALUES")
#Machines
cursor.execute("""CREATE TABLE Machines
(CavroXE1000 INTEGER,
CavroXCalibur INTEGER,
MXValve1 INTEGER,
MXValve2 INTEGER,
Degassi INTEGER,
ThermoCube1 INTEGER,
ThermoCube2 INTEGER,
Oasis1 INTEGER,
Oasis2 INTEGER,
YoctoThermistor INTEGER,
TC720 INTEGER)""")
cursor.execute("INSERT INTO Machines DEFAULT VALUES")
#Machine_identification
cursor.execute("""CREATE TABLE Machine_identification
(CavroXE1000 TEXT,
CavroXCalibur TEXT,
MXValve1 TEXT,
MXValve2 TEXT,
Degassi TEXT,
ThermoCube1 TEXT,
ThermoCube2 TEXT,
Oasis1 TEXT,
Oasis2 TEXT,
YoctoThermistor TEXT,
TC720 TEXT)""")
cursor.execute("INSERT INTO Machine_identification DEFAULT VALUES")
#Fixed_USB_port
cursor.execute("""CREATE TABLE Fixed_USB_port
(CavroXE1000 TEXT,
CavroXCalibur TEXT,
MXValve1 TEXT,
MXValve2 TEXT,
Degassi TEXT,
ThermoCube1 TEXT,
ThermoCube2 TEXT,
Oasis1 TEXT,
Oasis2 TEXT,
YoctoThermistor TEXT,
TC720 TEXT)""")
cursor.execute("INSERT INTO Fixed_USB_port DEFAULT VALUES")
#Pushbullet address book
cursor.execute("""CREATE TABLE Operator_address
(lars TEXT,
alejandro TEXT,
simone TEXT,
operator4 TEXT,
operator5 TEXT,
operator6 TEXT,
operator7 TEXT,
operator8 TEXT,
operator9 TEXT,
operator10 TEXT)""")
cursor.execute("INSERT INTO Operator_address DEFAULT VALUES")
#Padding (distances between valve and component)
cursor.execute("""CREATE TABLE Padding
(Degass INTEGER,
P1 INTEGER,
P2 INTEGER,
P3 INTEGER,
P4 INTEGER,
P5 INTEGER,
P6 INTEGER,
P7 INTEGER,
P8 INTEGER,
P9 INTEGER,
P10 INTEGER,
P11 INTEGER,
P12 INTEGER,
P13 INTEGER,
P14 INTEGER,
P15 INTEGER,
P16 INTEGER,
P17 INTEGER,
P18 INTEGER,
P19 INTEGER,
P20 INTEGER)""")
cursor.execute("INSERT INTO Padding DEFAULT VALUES")
#Alert volume
cursor.execute("""CREATE TABLE Alert_volume
(RunningBuffer REAL,
P1 REAL,
P2 REAL,
P3 REAL,
P4 REAL,
P5 REAL,
P6 REAL,
P7 REAL,
P8 REAL,
P9 REAL,
P10 REAL,
P11 REAL,
P12 REAL,
P13 REAL,
P14 REAL,
P15 REAL,
P16 REAL,
P17 REAL,
P18 REAL,
P19 REAL,
P20 REAL,
Disk REAL)""")
cursor.execute("INSERT INTO Alert_volume DEFAULT VALUES")
print('New database created.')
else:
print('FISH DB already exists, all content will be deleted')
conn = sqlite3.connect(FISH_db_path)
with conn:
cursor = conn.cursor()
cursor.execute("DELETE FROM Flags")
cursor.execute("INSERT INTO Flags DEFAULT VALUES")
cursor.execute("DELETE FROM Parameters")
cursor.execute("INSERT INTO Parameters DEFAULT VALUES")
cursor.execute("DELETE FROM Volumes")
cursor.execute("INSERT INTO Volumes DEFAULT VALUES")
cursor.execute("DELETE FROM Targets")
cursor.execute("INSERT INTO Targets DEFAULT VALUES")
cursor.execute("DELETE FROM Ports")
cursor.execute("INSERT INTO Ports DEFAULT VALUES")
cursor.execute("DELETE FROM Hybmix")
cursor.execute("INSERT INTO Hybmix DEFAULT VALUES")
cursor.execute("DELETE FROM Machines")
cursor.execute("INSERT INTO Machines DEFAULT VALUES")
cursor.execute("DELETE FROM Machine_identification")
cursor.execute("INSERT INTO Machine_identification DEFAULT VALUES")
cursor.execute("DELETE FROM Fixed_USB_port")
cursor.execute("INSERT INTO Fixed_USB_port DEFAULT VALUES")
cursor.execute("DELETE FROM Operator_address")
cursor.execute("INSERT INTO Operator_address DEFAULT VALUES")
cursor.execute("DELETE FROM Padding")
cursor.execute("INSERT INTO Padding DEFAULT VALUES")
cursor.execute("DELETE FROM Alert_volume")
cursor.execute("INSERT INTO Alert_volume DEFAULT VALUES")
return FISH_db_path
def newRowDB(db_path, table, new_row):
"""
Insert a new row into a table of a SQLite3 database.
Input:
`db_path`(str): Full path to database.
`table`(str): Name of table to insert into.
`new_row`(tuple): Tuple of items to insert. Like: ('text1', 'text2', 3, 4)
WARNING: The function does not check if the input is valid and executed.
"""
conn = sqlite3.connect(db_path)
with conn:
cursor = conn.cursor()
q_marks = ('?,'* len(new_row))[:-1]
cursor.execute("INSERT INTO {} VALUES ({})".format(table, q_marks), new_row)
def returnRowDB(db_path, table, criteria_column=None, criteria=None):
"""
Return a (specific) row of a database table.
Input:
`db_path`(str): Full path to database.
`table`(str): Name of table to retrieve from.
Optional, select specific row:
`criteria_column`(str): Name of column to select row by. Example: 'ID'
`cirteria`: criteria value in the specified criteria_column. Example: '2' (where ID=2)
Returns:
Tuple of the retrieved row form selected table and selected row.
"""
conn = sqlite3.connect(db_path)
with conn:
cursor = conn.cursor()
if criteria_column is not None:
cursor.execute("SELECT * FROM {} WHERE {}='{}'".format(table,
criteria_column,
criteria))
else:
cursor.execute("SELECT * FROM {}".format(table))
row = cursor.fetchone()
return row
def returnValueDB(db_path, table, column, criteria_column, criteria):
"""
Return a single value from a database table.
Input:
`db_path`(str): Full path to database.
`table`(str): Name of table to retrieve from.
`column`(str): Column to retrieve from.
`criteria_column`(str): Name of column to select row by. Example: 'ID'
`cirteria`: criteria value in the specified column. Example: '2' (where ID=2)
Returns:
Retrieved value from selected table, column and row.
WARNING: The function does not check if the input is valid.
"""
conn = sqlite3.connect(db_path)
with conn:
cursor = conn.cursor()
cursor.execute("SELECT {} FROM {} WHERE {}='{}'".format(column,table,
criteria_column,
criteria))
try:
row = cursor.fetchone()[0]
return row
except Exception as e:
print('Error, could not select a valid value from sqlite3 db')
print('Error message: ', e)
def updateValueDB(db_path, table, column, new_value=None, criteria_column=None,
criteria=None, operation=None, value=None):
"""
Update a single value from a database table.
Input:
`db_path`(str): Full path to database.
`table`(str): Name of table to update.
`column`(str): Column to update.
`new_value`: new value.
`criteria_column`(str): Name of column to select row by. Example: 'ID'
`criteria`: criteria value in the specified column. Example: '2' (where ID=2)
`operation`(str): '+' or '-', add or substract from a value. (atomic)
`value`(int/flt): value to add or substract.
WARNING: The function does not check if the input is valid and executed.
"""
if returnRowDB(db_path, table) == None:
newRowDB(db_path, table, (None, None))
conn = sqlite3.connect(db_path)
with conn:
cursor = conn.cursor()
if operation == None and criteria == None:
cursor.execute("UPDATE {} SET {} = '{}'".format(table,
column,
new_value))
elif operation == None:
cursor.execute("UPDATE {} SET {} = '{}' WHERE {} = '{}'".format(
table,
column,
new_value,
criteria_column,
criteria))
elif operation != None:
cursor.execute("UPDATE {} SET {} = {} {} {}".format(table,
column,
column,
operation,
value))
def deleteRowDB(db_path, table, criteria_column, criteria, startswith=False):
"""
Delete row(s) where the criteria matches a row in the criteria_column.
The criteria can be the beginning of a string if "startswith"=True
Input:
`db_path`(str): Full path to database.
`table`(str): Name of table to update.
`criteria_column`(str): Name of column to select row by. Example: 'ID'
`criteria`: Value in the specified column. Example:'2' (where ID=2)
`startswith`(bool): If False uses full criteria. If True selects rows that
start with the criteria. Default = False
Example: 'Left_12' will be selected if criteria is 'Left'
WARNING: The function does not check if the input is valid and executed.
"""
conn = sqlite3.connect(db_path)
with conn:
cursor = conn.cursor()
if startswith==False:
cursor.execute("DELETE FROM {} WHERE {} = '{}'".format(table,
criteria_column,
criteria ))
elif startswith==True:
start = criteria + '%'
cursor.execute("DELETE FROM {} WHERE {} like '{}'".format(table,
criteria_column,
start ))
def setFlagDB(db_path, flag):
"""
Set a flag in the DB to indicate that data needs to be read and coppied.
"""
updateValueDB(db_path, 'Flags', flag, new_value=1)
def removeFlagDB(db_path, flag):
"""
Remove a flag in DB to indicate that data is read and coppied.
"""
updateValueDB(db_path, 'Flags', flag, new_value=0)
#=============================================================================
# Move data from .yaml file to database
#=============================================================================
def yamlToDB_Parameters(db_path, to_update='All'):
"""
Copy data from the Parameters dictionary of the yaml file to the database.
Input:
`db_path`(str): Full path to database.
`to_update` Options:
'All' - All variables
1 - Only variables of EXP 1
2 - Only variables of EXP 2
'optProg' - Operator and Program
Fixed input:
Working data file: 'FISH_System_datafile.yaml'
"""
Para_dict = getFISHSystemMetadata('FISH_System_datafile.yaml', table='Parameters')
if to_update == 'All':
for k in Para_dict:
updateValueDB(db_path, 'Parameters', k, new_value=Para_dict[k])
elif to_update == 1:
for k in Para_dict:
if k.endswith('1'):
updateValueDB(db_path, 'Parameters', k, new_value=Para_dict[k])
elif to_update == 2:
for k in Para_dict:
if k.endswith('2'):
updateValueDB(db_path, 'Parameters', k, new_value=Para_dict[k])
elif to_update == 'opProg':
updateValueDB(db_path, 'Parameters', 'Operator', new_value=Para_dict['Operator'])
setFlagDB(db_path, 'Parameters_flag')
def yamlToDB_Volumes(db_path):
"""
Copy data from the Volumes dictionary of the yaml file to the database.
Input:
`db_path`(str): Full path to database.
Fixed input:
Working data file: 'FISH_System_datafile.yaml'
"""
Buf_dict = getFISHSystemMetadata('FISH_System_datafile.yaml', table='Volumes')
for k in Buf_dict:
updateValueDB(db_path, 'Volumes', k, new_value=Buf_dict[k])
setFlagDB(db_path, 'Volumes_flag')
def yamlToDB_Targets(db_path):
"""
Copy data from the Targets dictionary of the yaml file to the database.
If row already exists it gets updated otherwise a new is made.
Input:
`db_path`(str): Full path to database.
Fixed input:
Working data file: 'FISH_System_datafile.yaml'
"""
Tar_dict = getFISHSystemMetadata('FISH_System_datafile.yaml', table='Targets')
# Iterate through levels: chamber, Hybridization & items
for chamber in Tar_dict:
for hybridization in Tar_dict[chamber]:
# Code to identify chamber and hybridization round
code = 'C{}H{}'.format(chamber[-1], hybridization[-2:])
# Check if row already exisits
if returnRowDB(db_path, 'Targets', criteria_column='Code', criteria=code) is not None:
# Update existing row
for item in Tar_dict[chamber][hybridization]:
updateValueDB(db_path, 'Targets', item, new_value=Tar_dict[chamber][hybridization][item], criteria_column='Code', criteria=code)
# New row
else:
new_row = [code,
int(chamber[-1]),
hybridization,
Tar_dict[chamber][hybridization]['DAPI'],
Tar_dict[chamber][hybridization]['Atto425'],
Tar_dict[chamber][hybridization]['FITC'],
Tar_dict[chamber][hybridization]['Cy3'],
Tar_dict[chamber][hybridization]['TxRed'],
Tar_dict[chamber][hybridization]['Cy5'],
Tar_dict[chamber][hybridization]['Cy7'],
Tar_dict[chamber][hybridization]['QDot'],
Tar_dict[chamber][hybridization]['BrightField'],
Tar_dict[chamber][hybridization]['Europium']]
newRowDB(db_path, 'Targets', new_row)
setFlagDB(db_path, 'Targets_flag')
def yamlToDB_Ports(db_path):
"""
Copy data from the Ports dictionary of the yaml file to the database.
Input:
`db_path`(str): Full path to database.
Fixed input:
Working data file: 'FISH_System_datafile.yaml'
"""
Por_dict = getFISHSystemMetadata('FISH_System_datafile.yaml', table='Ports')
for k in Por_dict:
updateValueDB(db_path, 'Ports', k, new_value=Por_dict[k])
setFlagDB(db_path, 'Ports_flag')
def yamlToDB_Hybmix(db_path):
"""
Copy data from the Hybmix dictionary of the yaml file to the database.
Input:
`db_path`(str): Full path to database.
Fixed input:
Working data file: 'FISH_System_datafile.yaml'
"""
Hyb_dict = getFISHSystemMetadata('FISH_System_datafile.yaml', table='Hybmix')
for k in Hyb_dict:
updateValueDB(db_path, 'Hybmix', k, new_value=Hyb_dict[k])
setFlagDB(db_path, 'Hybmix_flag')
def yamlToDB_Machines(db_path):
"""
Copy data from the Machines dictionary of the yaml file to the database.
Input:
`db_path`(str): Full path to database.
Fixed input:
Working data file: 'FISH_System_datafile.yaml'
"""
Machines_dict = getFISHSystemMetadata('FISH_System_datafile.yaml', table='Machines')
for k in Machines_dict:
updateValueDB(db_path, 'Machines', k, new_value=Machines_dict[k])
setFlagDB(db_path, 'Machines_flag')
def yamlToDB_Machine_identification(db_path):
"""
Copy data from the Machine_identification dictionary of the yaml file to the database.
Input: