-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.py
executable file
·1408 lines (1227 loc) · 47.5 KB
/
app.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
# all the imports
from __future__ import print_function
import os
import sqlite3
import time
import sys
import datetime
import re
import subprocess
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash
import sys
import atexit
from operator import itemgetter
import string
ALLOWED_EXTENSIONS = set(['csv'])
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
app = Flask(__name__) # create the application instance :)
app.config.from_object(__name__) # load config from this file
queueProcessor = 'beginning'
#this is used so that the system knows the queue processor script has not been started yet.
InitCommand = 0 #Hacky variable so that we don't try to kill the queue-processor when initialise the database, creating an error message which would scare users
# Database configuration
app.config.update(
dict(
DATABASE=os.path.join(app.root_path, 'plasmotron.db'),
SECRET_KEY='development key',
USERNAME='admin',
PASSWORD='default',
DEBUG=True))
app.config.from_envvar('PLASMOTRON_SETTINGS', silent=True)
# local instance configuration: if a file
# local_config.cfg exists, it is read. This can be
# used to set the instance name for example
localConfigFilePath="local_config.cfg"
if os.path.isfile( localConfigFilePath ):
app.config.from_pyfile('local_config.cfg')
numberstoletters = dict(enumerate(string.ascii_uppercase,
1)) #Used in function below
def reverseRowColumn(cell):
"""Converts battleships-style cell references to numeric.
"A1" -> (0,0)
"""
cell = cell.lower()
# generate matched object via regex (groups grouped by parentheses)
############################################################################
# [a-z] matches a character that is a lower-case letter
# [0-9] matches a character that is a number
# The + means there must be at least one and repeats for the character it matches
# the parentheses group the objects (useful with .group())
m = re.match('([a-z]+)([0-9]+)', cell)
# if m is None, then there was no match
if m is None:
# let's tell the user that there was no match because it was an invalid cell
from sys import stderr
print('Invalid cell: {}'.format(cell), file=stderr)
return (None)
else:
# we have a valid cell!
# let's grab the row and column from it
var1 = 0
# run through all of the characters in m.group(1) (the letter part)
for ch in m.group(1):
# ord('a') == 97, so ord(ch) - 96 == 1
var1 += ord(ch) - 96
var2 = int(m.group(2))
row = var1 - 1
col = var2 - 1
return ((row, col))
def formatRowColumn(Row, Column):
"""Converts numeric indices to battleships-style cell-references.
Args:
Row: 0-indexed row index
Column: 0-indexed column index
Returns:
String representation in battleships-style.
0,0 -> "A1"
"""
if Row == None:
newrow = ''
else:
newrow = numberstoletters[Row + 1]
if Column == None:
newcol = ''
else:
newcol = Column + 1
return (newrow + str(newcol))
def displayTime(timer):
"""Generates a formatted time from an integer UNIX timestamp."""
value = datetime.datetime.fromtimestamp(timer)
return (value.strftime('%Y-%m-%d %H:%M:%S'))
def renderCellStyle(parasitaemia):
# This function generates a colour value for cell backgrounds, proportional to parasitaemia (0-100)
if parasitaemia is None:
return ('')
else:
val = float(min([float(parasitaemia), 10])) / 10
startr = 255
startg = 255
startb = 255
endr = 255
endg = 0
endb = 0
red = startr + val * (endr - startr)
green = startg + val * (endg - startg)
blue = startb + val * (endb - startb)
style = 'background-color:rgb(' + str(int(red)) + ', ' + str(
int(green)) + ', ' + str(int(blue)) + ')'
return (style)
def renderParasitaemiaText(parasitaemia):
"""Generates a nicely formatted textual version of a parasitaemia (0-100)."""
if parasitaemia is None:
return ('')
else:
return ('(' + str(parasitaemia) + '%)')
#Load these helper functions:
app.jinja_env.globals.update(
formatRowColumn=formatRowColumn,
displayTime=displayTime,
renderParasitaemiaText=renderParasitaemiaText,
renderCellStyle=renderCellStyle)
def connect_db():
"""Connects to the specific database."""
rv = sqlite3.connect(app.config['DATABASE'], timeout=30)
#rv.execute('PRAGMA journal_mode=wal')
rv.row_factory = sqlite3.Row
return rv
def get_db():
"""Opens a new database connection if there is none yet for the
current application context.
"""
if not hasattr(g, 'sqlite_db'):
g.sqlite_db = connect_db()
return g.sqlite_db
@app.teardown_appcontext
def close_db(error):
"""Closes the database again at the end of the request."""
if hasattr(g, 'sqlite_db'):
g.sqlite_db.close()
def init_db():
global InitCommand
InitCommand = 1
db = get_db()
with app.open_resource('model.mysql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
@app.cli.command('initdb')
def initdb_command():
"""Initializes the database."""
init_db()
print('Initialized the database.')
@app.route('/')
def show_plates():
db = get_db()
cur = db.execute(
'select Plates.PlateID, Plates.PlateName, COUNT(PlatePositions.Row) AS count, PlatePurpose, PlateFinished from Plates LEFT JOIN PlatePositions ON PlatePositions.PlateID=Plates.PlateID GROUP BY Plates.PlateID order by Plates.PlatePurpose, Plates.PlateID DESC'
)
entries = cur.fetchall()
return render_template('showPlates.html', entries=entries)
def getMachineProperties():
db = get_db()
cur = db.execute('SELECT * FROM MachineStatusProperties')
properties = {}
entries = cur.fetchall()
for entry in entries:
properties[entry['name']] = entry['value']
return (properties)
@app.route('/plate/<plateID>')
def show_plate(plateID):
db = get_db()
cur = db.execute(
'select * FROM Plates INNER JOIN PlateClasses ON Plates.PlateClass= PlateClasses.PlateClassID WHERE PlateID= ?',
[plateID])
plate = cur.fetchone()
# cur = db.execute('select * FROM Cultures INNER JOIN PlatePositions ON Cultures.CultureID = PlatePositions.CultureID WHERE PlateID= ?',[plateID])
if plate['PlatePurpose'] == 2:
cur = db.execute(
' SELECT * FROM PlatePositions LEFT JOIN Measurements ON PlatePositions.Row=Measurements.Row AND PlatePositions.Column=Measurements.Column AND PlatePositions.PlateID = Measurements.PlateID INNER JOIN Cultures ON Cultures.CultureID=PlatePositions.CultureID WHERE PlatePositions.PlateID= ?',
[plateID])
else:
cur = db.execute(
'SELECT * FROM Cultures INNER JOIN PlatePositions ON Cultures.CultureID = PlatePositions.CultureID INNER JOIN Plates ON Plates.PlateID=PlatePositions.PlateID AND Plates.PlatePurpose=1 LEFT JOIN ( SELECT MAX(timeSampled),* FROM Measurements INNER JOIN PlatePositions ON PlatePositions.Row=Measurements.Row AND PlatePositions.Column=Measurements.Column AND PlatePositions.PlateID = Measurements.PlateID GROUP BY CultureID ) latestparasitaemia ON Cultures.CultureID=latestparasitaemia.CultureID WHERE PlatePositions.PlateID= ?',
[plateID])
entries = cur.fetchall()
dimx = plate['PlateRows']
dimy = plate['PlateCols']
rows = [[{'name': '', 'id': -1} for i in range(dimy)] for j in range(dimx)]
for entry in entries:
rows[entry['Row']][entry['Column']] = entry
machineproperties = getMachineProperties()
return render_template(
'viewPlate.html',
plate=plate,
rows=rows,
machineproperties=machineproperties)
@app.route('/culture/<cultureID>')
def show_culture(cultureID):
db = get_db()
cur = db.execute(
'select * FROM Cultures INNER JOIN PlatePositions ON Cultures.CultureID = PlatePositions.CultureID INNER JOIN Plates ON PlatePositions.PlateID=Plates.PlateID WHERE Plates.PlatePurpose=1 AND Cultures.CultureID= ?',
[cultureID])
culture = cur.fetchone()
cur = db.execute(
'select * FROM CommandQueue WHERE PlateID = ? AND Row = ? AND Column = ?',
[culture['PlateID'], culture['Row'], culture['Column']])
history = cur.fetchall()
cur = db.execute(
'select * FROM Actions WHERE PlateID = ? AND Row = ? AND Column = ?',
[culture['PlateID'], culture['Row'], culture['Column']])
actions = cur.fetchall()
cur = db.execute(
'select * FROM Cultures INNER JOIN PlatePositions ON Cultures.CultureID = PlatePositions.CultureID INNER JOIN Plates ON PlatePositions.PlateID=Plates.PlateID INNER JOIN Measurements ON Measurements.PlateID=Plates.PlateID AND Measurements.Row=PlatePositions.Row AND Measurements.Column=PlatePositions.Column WHERE Plates.PlatePurpose=2 AND Cultures.CultureID= ?',
[cultureID])
measurements = cur.fetchall()
return render_template(
'viewCulture.html',
culture=culture,
history=history,
actions=actions,
measurements=measurements)
@app.route('/addculture', methods=['POST'])
def add_culture():
"""Process form for adding a new culture to a plate.
By default we put it in the well after the furthest well across the plate.
But if the user specifies a location this is used in preference.
Duplicated locations will raise a database error.
"""
db = get_db()
cur = db.execute(
'SELECT PlateRows,PlateCols FROM Plates INNER JOIN PlateClasses ON Plates.PlateClass= PlateClasses.PlateClassID WHERE PlateID= ?',
[request.form['plateID']])
platestats = cur.fetchone()
cur = db.execute(
'SELECT MAX(Column) AS maxCol FROM PlatePositions WHERE PlateID= ?',
[request.form['plateID']])
posresults = cur.fetchone()
if posresults['maxCol'] is None:
currentRow = -1
currentCol = 0
else:
currentCol = posresults['maxCol']
cur = db.execute(
'SELECT MAX(Row) AS maxRow FROM PlatePositions WHERE PlateID= ? AND Column = ?',
[request.form['plateID'], currentCol])
posresults = cur.fetchone()
currentRow = posresults['maxRow']
currentRow = currentRow + 1
if currentRow == platestats['PlateRows']:
currentRow = 0
currentCol = currentCol + 1
if request.form['row'] is not '' and request.form['col'] is not '':
currentRow = int(request.form['row'])
currentCol = int(request.form['col'])
if currentRow >= platestats['PlateRows'] or currentCol >= platestats[
'PlateCols']:
flash('Culture was attempted to be created outside bounds of plate')
return redirect(url_for('show_plate', plateID=request.form['plateID']))
if request.form['title'] == '':
return ('Error: please enter a name for the culture')
db.execute('insert into Cultures (CultureName) values (?)',
[request.form['title']])
db.execute(
'insert into PlatePositions (CultureID,PlateID,Row,Column) values (last_insert_rowid(),?,?,?)',
[request.form['plateID'], currentRow, currentCol])
db.commit()
flash('New culture successfully created and added to the plate')
return redirect(url_for('show_plate', plateID=request.form['plateID']))
@app.route('/addplate', methods=['POST'])
def add_plate():
db = get_db()
title = request.form['title'].strip()
if len(title) > 0:
db.execute(
'insert into Plates (PlateName,PlateClass,PlateFinished,PlatePurpose) values (?,?,0,1)',
[request.form['title'], request.form['class']])
db.commit()
flash('New plate was successfully added')
else:
flash('Please enter a name for your plate.')
return redirect(url_for('show_plates'))
@app.route('/addmanualaction', methods=['POST'])
def add_manual_action():
timestamp = int(time.time())
db = get_db()
db.execute(
'insert into Actions (PlateID,Row,Column,TypeOfOperation,ActionText,ActionTime) values (?,?,?,?,?,?)',
[
request.form['plateid'], request.form['row'], request.form['col'],
'custom', request.form['text'], timestamp
])
db.commit()
flash('The action was successfully added')
return redirect(url_for('show_culture', cultureID=request.form['cultureid']))
@app.route('/addmanualactionforchechcalib', methods=['POST'])
def add_manual_action_for_check_calib():
doAction = request.form['doAction']
usePipette = request.form['usePipette']
useContainer = None
if 'useContainer' in request.form and request.form['useContainer']:
useContainer = request.form['useContainer']
useRow = None
if 'useRow' in request.form and request.form['useRow']:
useRow = request.form['useRow']
useCol = None
if 'useCol' in request.form and request.form['useCol']:
useCol = request.form['useCol']
useVolume = None
if 'useVolume' in request.form and request.form['useVolume']:
useVolume = request.form['useVolume']
db = get_db()
db.execute(
'insert into CommandQueue (Command,Pipette,Labware,Row,Column,Volume,queued) values (?,?,?,?,?,?,?)',
[
doAction, usePipette, useContainer, useRow,useCol,useVolume,1
])
db.commit()
return redirect(url_for('checkCalibration'))
@app.route('/processplate', methods=['POST'])
def process_plate():
tipcounter = [int(request.form['tips1000']), int(request.form['tips200'])]
maxtips = [96, 12]
dimensions = [[12, 8], [12, 1]]
pipettenames = ['p1000', 'p200x8']
tipracks = ['p1000rack', 'p200rack']
MeasurementPlate = None
MeasurementAvailableWells = []
def getTip(pipette):
nonlocal tipcounter
nonlocal db
if tipcounter[pipette] == maxtips[pipette]:
email(
request.form['email'],
"Please load more tips! <br> <img src='http://phenoplasm.org/sadtips.jpg'>"
)
cur = db.execute('INSERT INTO CommandQueue (Command) VALUES ("MoreTips")')
tipcounter[pipette] = 0
col, row = divmod(tipcounter[pipette], dimensions[pipette][1])
onexecute = 'UPDATE MachineStatusProperties SET value = ' + str(
tipcounter[pipette] +
1) + ' WHERE name = "' + 'tipsusedpipette' + str(pipette) + '"'
print(onexecute)
cur = db.execute(
'INSERT INTO CommandQueue (Command, Pipette, Labware, Row, Column, OnCompletion) VALUES ("GetTips",?,?,?,?,?)',
[pipettenames[pipette], tipracks[pipette], row, col, onexecute])
tipcounter[pipette] = tipcounter[pipette] + 1
def dropTip(pipette):
cur = db.execute(
'INSERT INTO CommandQueue (Command, Pipette, Labware) VALUES ("DropTip",?,"trash")',
[pipettenames[pipette]])
def email(email, message):
cur = db.execute(
'INSERT INTO CommandQueue (Command,email, message) VALUES (?,?,?)',
['Email', email, message])
def aspirate(pipette, labware, volume, row=None, col=None, plateid=None):
cur = db.execute(
'INSERT INTO CommandQueue (Command, Pipette, Volume, Labware, Row, Column, PlateID) VALUES ("Aspirate",?,?,?,?,?,?)',
[pipettenames[pipette], volume, labware, row, col, plateid])
def dispense(pipette,
labware,
volume,
row=None,
col=None,
oncompletion=None,
plateid=None,
bottom=False):
if (bottom == True):
cur = db.execute(
'INSERT INTO CommandQueue (Command, Pipette, Volume, Labware, Row, Column,OnCompletion,PlateID) VALUES ("DispenseBottom",?,?,?,?,?,?,?)',
[
pipettenames[pipette], volume, labware, row, col, oncompletion,
plateid
])
else:
cur = db.execute(
'INSERT INTO CommandQueue (Command, Pipette, Volume, Labware, Row, Column,OnCompletion,PlateID) VALUES ("Dispense",?,?,?,?,?,?,?)',
[
pipettenames[pipette], volume, labware, row, col, oncompletion,
plateid
])
def resuspendReservoir(pipette, labware):
cur = db.execute(
'INSERT INTO CommandQueue (Command, Pipette, Labware) VALUES (?,?,?)',
['ResuspendReservoir', pipettenames[pipette], labware])
def resuspend(pipette,
labware,
volume,
row=None,
col=None,
plateid=None,
double=False):
if double == False:
Command = 'Resuspend'
else:
Command = 'ResuspendDouble'
cur = db.execute(
'INSERT INTO CommandQueue (Command, Pipette, Volume, Labware, Row, Column,PlateID) VALUES (?,?,?,?,?,?,?)',
[Command, pipettenames[pipette], volume, labware, row, col, plateid])
def airgap(pipette):
cur = db.execute(
'INSERT INTO CommandQueue (Command, Pipette) VALUES ("AirGap",?)',
[pipettenames[pipette]])
def home():
dropTip(0)
dropTip(1)
cur = db.execute('INSERT INTO CommandQueue (Command) VALUES (?)', ['Home'])
def createOnExecute(action, plateid, platerow, platecol, actionValue=None):
if actionValue is None:
onexecute = ('INSERT INTO Actions '
'(PlateID,Row,Column,TypeOfOperation,ActionTime) VALUES ('
) + str(plateid) + ',' + str(platerow) + ',' + str(
platecol) + ",'" + action + "'," + '<time>)'
else:
onexecute = (
'INSERT INTO Actions '
'(PlateID,Row,Column,TypeOfOperation,ActionTime,ValueOfOperation)'
' VALUES ('
) + str(plateid) + ',' + str(platerow) + ',' + str(
platecol) + ",'" + action + "'," + '<time>,' + str(actionValue) + ')'
return (onexecute)
def generateMultiDispense(source, destwells):
curvol = 0
getTip(0)
for well in destwells:
(plate, row, col) = well
if curvol < 200:
cur = aspirate(0, 'TubSybr', 1000)
curvol = 1000
cur = dispense(0, 'AliquotPlate', 200, row, col)
curvol = curvol - 200
airgap(0)
dropTip(0)
def getNextMeasurementWell():
nonlocal MeasurementAvailableWells
nonlocal MeasurementPlate
if (len(MeasurementAvailableWells) == 0):
cur = db.execute(
'SELECT * FROM Plates WHERE PlatePurpose=2 AND PlateFinished=0')
plates = cur.fetchall()
for one in plates:
MeasurementPlate = one['PlateID']
MeasurementAvailableWells = []
for y in range(12):
for x in range(8):
MeasurementAvailableWells.append((x, y))
cur2 = db.execute('SELECT * FROM PlatePositions WHERE PlateID=?',
[one['PlateID']])
wells = cur2.fetchall()
for well in wells:
indices = [
i for i, tupl in enumerate(MeasurementAvailableWells)
if tupl[0] == well['Row'] and tupl[1] == well['Column']
]
MeasurementAvailableWells.pop(indices[0])
if len(MeasurementAvailableWells) > 0:
break
if len(MeasurementAvailableWells) == 0:
#flash('No measurement plates available')
return (-1, -1, -1)
(row, col) = MeasurementAvailableWells[0]
MeasurementAvailableWells.pop(0)
return (MeasurementPlate, row, col)
db = get_db()
cur = db.execute('SELECT * FROM CommandQueue WHERE doneAt IS NULL')
if (cur.fetchone() != None):
flash('Please clear the queue first')
return redirect(url_for('view_refreshed'))
home()
cur = db.execute(
'SELECT PlateRows,PlateCols,PlateClass FROM Plates INNER JOIN PlateClasses ON Plates.PlateClass= PlateClasses.PlateClassID WHERE PlateID= ?',
[request.form['plateid']])
platestats = cur.fetchone()
if platestats['PlateClass'] == 0:
cur = db.execute(
'INSERT INTO CommandQueue (Command, Labware, LabwareType,Slot) VALUES ("InitaliseLabware","CulturePlate","96-flat","B1")'
)
feedVolume = 200
extraRemoval = 5
aliquotvol = 40
resuspvol = 150
elif platestats['PlateClass'] == 1:
cur = db.execute(
'INSERT INTO CommandQueue (Command, Labware, LabwareType,Slot) VALUES ("InitaliseLabware","CulturePlate","24-well-plate","B1")'
)
feedVolume = 900
extraRemoval = 15
aliquotvol = 20
resuspvol = 800
fullVolume = 1000
else:
raise Exception('Undefined plate class?')
cur = db.execute(
'select * FROM Cultures INNER JOIN PlatePositions ON Cultures.CultureID = PlatePositions.CultureID INNER JOIN Plates ON PlatePositions.PlateID=Plates.PlateID WHERE Plates.PlateID=? AND (PlatePositions.Status IS NULL OR PlatePositions.Status != 10) ORDER BY Column, Row',
[request.form['plateid']])
cultures = cur.fetchall()
tipnumber = 0
email(
'Started processing a new plate with command: ' + request.form['manual'])
if request.form['manual'] == 'split':
cur = db.execute(
'SELECT *, PlatePositions.Row AS Row, PlatePositions.Column AS Column FROM Cultures INNER JOIN PlatePositions ON Cultures.CultureID = PlatePositions.CultureID INNER JOIN Plates ON Plates.PlateID=PlatePositions.PlateID AND Plates.PlatePurpose=1 INNER JOIN ( SELECT MAX(timeSampled),* FROM Measurements INNER JOIN PlatePositions ON PlatePositions.Row=Measurements.Row AND PlatePositions.Column=Measurements.Column AND PlatePositions.PlateID = Measurements.PlateID GROUP BY CultureID ) latestparasitaemia ON Cultures.CultureID=latestparasitaemia.CultureID WHERE PlatePositions.PlateID = ?',
[request.form['plateid']])
splitcultures = cur.fetchall()
splitcultures = calcExpectedParasitaemas(splitcultures)
desiredParasitaemia = float(request.form['parasitaemia'])
if not (desiredParasitaemia > 0 and desiredParasitaemia < 101):
return ('Error, enter reasonable parasitaemia')
addback = []
for culture in splitcultures:
if culture['expectednow'] > desiredParasitaemia:
factor = desiredParasitaemia / culture['expectednow']
amountToRemove = (1 - factor) * fullVolume
getTip(0)
cur = resuspend(
0,
'CulturePlate',
resuspvol,
culture['Row'],
culture['Column'],
plateid=request.form['plateid'],
double=True)
cur = aspirate(
0,
'CulturePlate',
amountToRemove,
culture['Row'],
culture['Column'],
plateid=request.form['plateid'])
airgap(0)
dropTip(0)
addback.append([
amountToRemove, culture['Row'], culture['Column'],
request.form['plateid'], factor
])
getTip(0)
resuspendReservoir(0, 'TubBlood')
for item in addback:
cur = aspirate(0, 'TubBlood', item[0])
onexec = createOnExecute('split', request.form['plateid'], item[1],
item[2], item[4])
cur = dispense(
0, 'CulturePlate', item[0], item[1], item[2], onexec, plateid=item[3])
dropTip(0)
elif request.form['manual'] == 'splittonewplate':
cur = db.execute(
'SELECT *, PlatePositions.Row AS Row, PlatePositions.Column AS Column FROM Cultures INNER JOIN PlatePositions ON Cultures.CultureID = PlatePositions.CultureID INNER JOIN Plates ON Plates.PlateID=PlatePositions.PlateID AND Plates.PlatePurpose=1 INNER JOIN ( SELECT MAX(timeSampled),* FROM Measurements INNER JOIN PlatePositions ON PlatePositions.Row=Measurements.Row AND PlatePositions.Column=Measurements.Column AND PlatePositions.PlateID = Measurements.PlateID GROUP BY CultureID ) latestparasitaemia ON Cultures.CultureID=latestparasitaemia.CultureID WHERE PlatePositions.PlateID = ?',
[request.form['plateid']])
splitcultures = cur.fetchall()
splitcultures = calcExpectedParasitaemas(splitcultures)
desiredParasitaemia = float(request.form['parasitaemia'])
if not (desiredParasitaemia > 0 and desiredParasitaemia < 101):
return ('Error, enter reasonable parasitaemia')
addback = []
getTip(0)
resuspendReservoir(0, 'TubBlood')
for culture in splitcultures:
if culture['expectednow'] > desiredParasitaemia:
factor = desiredParasitaemia / culture['expectednow']
amountToTransfer = (factor) * fullVolume
amountOfNewBlood = (1 - factor) * fullVolume
cur = aspirate(0, 'TubBlood', amountOfNewBlood)
cur = dispense(
0,
'CulturePlate2',
amountOfNewBlood,
culture['Row'],
culture['Column'],
plateid=request.form['plateid'])
addback.append([
amountToTransfer, culture['Row'], culture['Column'],
request.form['plateid'], factor
])
else:
factor = 1
amountToTransfer = (factor) * fullVolume
amountOfNewBlood = (1 - factor) * fullVolume
addback.append([
amountToTransfer, culture['Row'], culture['Column'],
request.form['plateid'], factor
])
dropTip(0)
for item in addback:
getTip(0)
cur = resuspend(
0, 'CulturePlate', item[0], item[1], item[2], plateid=item[3])
cur = aspirate(
0, 'CulturePlate', item[0], item[1], item[2], plateid=item[3])
onexec = createOnExecute('split', request.form['plateid'], culture['Row'],
culture['Column'], item[4])
cur = dispense(
0,
'CulturePlate2',
item[0],
item[1],
item[2],
onexec,
plateid=item[3],
bottom=True)
dropTip(0)
elif request.form['manual'] == 'dilutenewplate':
desiredParasitaemia = float(request.form['parasitaemia'])
if not (desiredParasitaemia > 0 and desiredParasitaemia < 101):
return ('Error, enter reasonable parasitaemia')
addback = []
getTip(0)
resuspendReservoir(0, 'TubBlood')
for culture in cultures:
if 100 > desiredParasitaemia:
factor = desiredParasitaemia / 100
amountToTransfer = (factor) * fullVolume
amountOfNewBlood = (1 - factor) * fullVolume
cur = aspirate(0, 'TubBlood', amountOfNewBlood)
cur = dispense(
0,
'CulturePlate2',
amountOfNewBlood,
culture['Row'],
culture['Column'],
plateid=request.form['plateid'])
addback.append([
amountToTransfer, culture['Row'], culture['Column'],
request.form['plateid'], factor
])
else:
factor = 1
amountToTransfer = (factor) * fullVolume
amountOfNewBlood = (1 - factor) * fullVolume
addback.append([
amountToTransfer, culture['Row'], culture['Column'],
request.form['plateid'], factor
])
dropTip(0)
for item in addback:
getTip(0)
cur = resuspend(
0, 'CulturePlate', item[0], item[1], item[2], plateid=item[3])
cur = aspirate(
0, 'CulturePlate', item[0], item[1], item[2], plateid=item[3])
onexec = createOnExecute('split', request.form['plateid'], culture['Row'],
culture['Column'], item[4])
cur = dispense(
0,
'CulturePlate2',
item[0],
item[1],
item[2],
onexec,
plateid=item[3],
bottom=True)
dropTip(0)
elif request.form['manual'] == 'dispense-sybr-green':
getTip(0)
curvol = 0
for x in range(8):
for y in range(6):
if curvol < 200:
cur = aspirate(0, 'TubSybr', 1000)
curvol = 1000
cur = dispense(0, 'AliquotPlate', 200, x, y)
curvol = curvol - 200
dropTip(0)
elif request.form['manual'] == 'dispense-sybr-green2':
getTip(1)
for x in range(4):
cur = aspirate(1, 'TubSybr', 200)
cur = dispense(1, 'AliquotPlate', 200, 0, x)
dropTip(1)
elif request.form['manual'] == 'feed':
if platestats['PlateClass'] == 1:
for culture in cultures:
getTip(0)
cur = aspirate(
0,
'CulturePlate',
feedVolume + extraRemoval,
culture['Row'],
culture['Column'],
plateid=request.form['plateid'])
# cur = db.execute('INSERT INTO CommandQueue (Command, Volume, Labware) VALUES ("Dispense",?,"Trash")',[feedVolume+extraRemoval])
dropTip(0)
getTip(0)
for culture in cultures:
cur = aspirate(0, 'TubMedia', feedVolume)
onexec = createOnExecute('feed', request.form['plateid'],
culture['Row'], culture['Column'])
cur = dispense(
0,
'CulturePlate',
feedVolume,
culture['Row'],
culture['Column'],
onexec,
plateid=request.form['plateid'])
dropTip(0)
cur = db.execute('INSERT INTO CommandQueue (Command) VALUES ("Home")')
elif platestats['PlateClass'] == 0:
rows = {}
for culture in cultures:
row = culture['Column']
rows[row] = 1
rows = rows.keys()
for row in rows:
getTip(1)
cur = aspirate(1, 'CulturePlate96', feedVolume, 0, row)
cur = dispense(1, 'trash', feedVolume)
dropTip(1)
getTip(1)
for row in rows:
cur = aspirate(1, 'TubMedia', feedVolume)
cur = dispense(1, 'CulturePlate96', feedVolume, 0, row)
dropTip(1)
cur = db.execute('INSERT INTO CommandQueue (Command) VALUES ("Home")')
elif request.form['manual'] == 'dispenseXtoall':
if platestats['PlateClass'] == 1:
getTip(0)
for culture in cultures:
feedVolume = request.form['parasitaemia']
cur = aspirate(0, 'TubMedia', feedVolume)
onexec = createOnExecute('feed', request.form['plateid'],
culture['Row'], culture['Column'])
cur = dispense(
0,
'CulturePlate',
feedVolume,
culture['Row'],
culture['Column'],
onexec,
plateid=request.form['plateid'])
dropTip(0)
cur = db.execute('INSERT INTO CommandQueue (Command) VALUES ("Home")')
elif request.form['manual'] == 'feedandaliquot' or request.form[
'manual'] == 'justaliquot':
cur = db.execute(
'INSERT INTO CommandQueue (Command, Labware, LabwareType,Slot) VALUES ("InitaliseLabware","AliquotPlate","96-flat","C1")'
)
alwells = []
culwells = []
for culture in cultures:
(alplate, alrow, alcol) = getNextMeasurementWell()
alwells.append([alplate, alrow, alcol])
culwells.append([culture['Row'], culture['Column'], culture['CultureID']])
generateMultiDispense('TubSybr', alwells)
for i in range(len(culwells)):
culwell = culwells[i]
(alplate, alrow, alcol) = alwells[i]
getTip(0)
if request.form['manual'] == 'feedandaliquot':
cur = aspirate(0, 'CulturePlate', feedVolume + extraRemoval, culwell[0],
culwell[1], request.form['plateid'])
airgap(0)
dropTip(0)
getTip(0)
cur = aspirate(0, 'TubMedia', feedVolume)
onexec = createOnExecute('feed', request.form['plateid'], culwell[0],
culwell[1])
cur = dispense(
0,
'CulturePlate',
feedVolume,
culwell[0],
culwell[1],
onexec,
plateid=request.form['plateid'],
bottom=True)
cur = resuspend(
0,
'CulturePlate',
resuspvol,
culwell[0],
culwell[1],
plateid=request.form['plateid'])
cur = aspirate(
0,
'CulturePlate',
aliquotvol,
culwell[0],
culwell[1],
plateid=request.form['plateid'])
if (alplate == -1):
flash('Please add a new measurement plate')
return redirect(url_for('show_plates'))
onexecute = ('INSERT INTO PlatePositions '
'(PlateID,Row,Column,CultureID,timeSampled) VALUES ('
) + str(alplate) + ',' + str(alrow) + ',' + str(
alcol) + ',' + str(culwell[2]) + ',' + '<time>)'
cur = dispense(
0,
'AliquotPlate',
aliquotvol,
alrow,
alcol,
onexecute,
alplate,
bottom=True)
cur = aspirate(0, 'AliquotPlate', 100, alrow, alcol, plateid=alplate)
cur = dispense(
0, 'AliquotPlate', 100, alrow, alcol, plateid=alplate, bottom=True)
airgap(0)
dropTip(0)
cur = db.execute('INSERT INTO CommandQueue (Command) VALUES ("Home")')
elif request.form['manual'] == 'feedandkeepx':
propToKeep = float(request.form['parasitaemia'])
if not (propToKeep > 0 and propToKeep < 101):
return ('Error, enter reasonable value for X')
amountToRemove = 1000 * (1 - propToKeep / 100)
cur = db.execute(
'INSERT INTO CommandQueue (Command, Labware, LabwareType,Slot) VALUES ("InitaliseLabware","AliquotPlate","96-flat","C1")'
)
for culture in cultures:
getTip(0)
cur = aspirate(
0,
'CulturePlate',
feedVolume + extraRemoval,
culture['Row'],
culture['Column'],
plateid=request.form['plateid'])
airgap(0)
dropTip(0)
getTip(0)
cur = aspirate(0, 'TubMedia', feedVolume)
cur = dispense(
0,
'CulturePlate',
feedVolume,
culture['Row'],
culture['Column'],
plateid=request.form['plateid'],
bottom=True)
cur = resuspend(
0,
'CulturePlate',
resuspvol,
culture['Row'],
culture['Column'],
plateid=request.form['plateid'])
cur = aspirate(
0,
'CulturePlate',
amountToRemove,
culture['Row'],
culture['Column'],
plateid=request.form['plateid'])
airgap(0)
dropTip(0)
getTip(0)
resuspendReservoir(0, 'TubBlood')
vol = 0
for culture in cultures:
if vol < amountToRemove:
cur = aspirate(0, 'TubBlood', 1000 - vol)
vol = 1000
cur = dispense(
0,
'CulturePlate',
amountToRemove,
culture['Row'],
culture['Column'],
plateid=request.form['plateid'])
vol = vol - amountToRemove
dropTip(0)
cur = db.execute('INSERT INTO CommandQueue (Command) VALUES ("Home")')
elif request.form['manual'] == 'feedanddiscard50':
cur = aspirate(0, 'TubMedia', 1500)
cur = db.execute(
'INSERT INTO CommandQueue (Command, Labware, LabwareType,Slot) VALUES ("InitaliseLabware","AliquotPlate","96-flat","C1")'
)
for culture in cultures:
getTip(0)
cur = aspirate(
0,
'CulturePlate',
feedVolume + extraRemoval,
culture['Row'],
culture['Column'],
plateid=request.form['plateid'])
airgap(0)
dropTip(0)
getTip(0)
cur = aspirate(0, 'TubMedia', feedVolume)
cur = dispense(
0,
'CulturePlate',
feedVolume,
culture['Row'],