-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.py
More file actions
1690 lines (1302 loc) · 52.8 KB
/
Copy pathapp.py
File metadata and controls
1690 lines (1302 loc) · 52.8 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
from flask import Flask, render_template, url_for, jsonify, send_file, Response, session
from flask_cors import CORS, cross_origin
from flask import request
import pandas as pd
import scripts
import json
import random
from models import db, GrowthData, TraitData,KineticData
import numpy as np
from sqlalchemy import asc
import os
from flask import Flask, request, render_template, redirect, url_for
import csv
import openpyxl
from io import StringIO, BytesIO
from werkzeug.utils import secure_filename
import utils
import uuid
from datetime import timedelta
import shutil
from urllib.parse import urlencode, quote
import zipfile
import io
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = Flask(__name__,template_folder='templates',static_url_path='/static')
CORS(app, resources={r"/*": {"origins": "*"}})
app.config['CORS_HEADERS'] = 'Content-Type'
app.secret_key = 'sbrg_omnilog'
PMKBASE_BASE_URL = "https://pmkbase.com"
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///growth_data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['MAX_CONTENT_LENGTH'] = 10000*1024*1024
db.init_app(app)
# with app.app_context():
# db.create_all()
def ingest_data(specie):
"""
Ingests growth curve data for a given species from a CSV file and adds it to the database.
Args:
specie (str): The species name.
Returns:
None
Side Effects:
Reads 'static/{specie}/data/plate_summary.csv'.
Adds GrowthData entries to the database.
"""
csv_path = f'static/{specie}/data/plate_summary.csv'
growth_curves = pd.read_csv(csv_path)
time_scale = list(np.arange(0,48.25,0.25))
for _, row in growth_curves.iterrows():
signal_columns = [str(w)+'hrs' for w in time_scale]
signal_data = row[signal_columns].tolist()
entry = GrowthData(
plateid=row['Plate IDs'],
specie=specie,
well=row['Well'],
#plate = row['Plate'],
compound=row['Compound'],
replicates=row['Replicates'],
signal_data=signal_data
)
db.session.add(entry)
db.session.commit()
def ingest_trait_data(specie):
"""
Ingests trait data for a given species from a CSV file and adds it to the database.
Args:
specie (str): The species name.
Returns:
None
Side Effects:
Reads 'static/{specie}/data/growth_summary.csv'.
Adds TraitData entries to the database.
"""
csv_path = f'static/{specie}/data/growth_summary.csv'
growth_calls = pd.read_csv(csv_path)
for _, row in growth_calls.iterrows():
entry = TraitData(
plateid=row['Plate IDs'],
strainid = row['Strain ID'],
specie=specie,
metadata_mods = row['Metadata/Modifications'],
project = row['Project'],
well=row['Well'],
plate = row['Plate'],
media = row['Media'],
growth = row['Growth'],
compound=row['Compound'],
desc = row['Description'],
strain = row['Strain'],
phylo = row['Phylogroup/Genome Cluster'],
mlst = row['MLST']
)
db.session.add(entry)
db.session.commit()
def ingest_kinetic_data(specie):
"""
Ingests kinetic data for a given species from a CSV file and adds it to the database.
Args:
specie (str): The species name.
Returns:
None
Side Effects:
Reads 'static/{specie}/data/kinetic_summary.csv'.
Adds KineticData entries to the database.
"""
csv_path = f'static/{specie}/data/kinetic_summary.csv'
kinetics = pd.read_csv(csv_path)
for _, row in kinetics.iterrows():
entry = KineticData(
plateid=row['Plate IDs'],
strainid = row['Strain ID'],
strain = row['Strain'],
specie=specie,
metadata_mods = row['Metadata/Modifications'],
project = row['Project'],
well=row['Well'],
plate = row['Plate'],
media = row['Media'],
replicates=row['Replicates'],
compound=row['Compound'],
keggid=row['KEGG ID'],
casid=row['CAS ID'],
maxresp = row['Max Resp'],
maxresprate = row['Max Resp Rate'],
timetill = row['Time till max resp rate'],
auc = row['AUC'],
growth = row['Growth'],
mlst = row['MLST'],
phylo = row['Phylogroup/Genome Cluster']
)
db.session.add(entry)
db.session.commit()
@app.route('/download/all_sequences')
def download_all_sequences():
"""
Downloads a zip file containing all sequence files.
Returns:
Response: Sends 'static/all_sequences.zip' as an attachment.
"""
zip_path = os.path.join('static', 'all_sequences.zip')
return send_file(zip_path, as_attachment=True, download_name='all_sequences.zip')
@app.route('/download/all_pmdata')
def download_all_pmdata():
"""
Downloads a zip file containing all phenotype microarray data.
Returns:
Response: Sends 'static/all_PM_data.zip' as an attachment.
"""
zip_path = os.path.join('static', 'all_PM_data.zip')
return send_file(zip_path, as_attachment=True, download_name='allPMdata.zip')
@app.route('/download/all_specie_sequences')
def download_all_specie_sequences():
"""
Downloads a zip file containing all sequence files for a specific species.
Query Parameters:
specie (str): The species name.
Returns:
Response: Sends '{specie}/sequences.zip' as an attachment.
"""
specie=request.args.get('specie')
# Define the path for the zip file
zip_path = os.path.join('static', specie, 'sequences.zip')
return send_file(zip_path, as_attachment=True, download_name=specie+'_sequences.zip')
@app.route('/download/all_specie_pmdata')
def download_all_specie_pmdata():
"""
Downloads a zip file containing all PM data for a specific species.
Query Parameters:
specie (str): The species name.
Returns:
Response: Sends '{specie}/data.zip' as an attachment.
"""
specie=request.args.get('specie')
# Define the path for the zip file
zip_path = os.path.join('static', specie, 'data.zip')
return send_file(zip_path, as_attachment=True, download_name=specie+'_allPMdata.zip')
@app.route('/download/mainstrain_specie_sequences')
def download_mainstrain_specie_sequences():
"""
Downloads the sequence file for a specific strain of a given species.
Query Parameters:
specie (str): The species name.
strain (str): The strain name.
Returns:
Response: Sends the sequence file (.fna) as an attachment.
404: If the file is not found.
Side Effects:
Reads files from the static directory.
Raises:
FileNotFoundError: If the sequence file does not exist.
"""
specie= request.args.get('specie')
strain = request.args.get('strain')
for filename in os.listdir(os.path.join('static', specie, 'sequences')):
if filename.startswith(strain):
file_path = os.path.join('static', specie, 'sequences',filename)
break
return send_file(file_path, as_attachment=True, download_name=specie+'_'+strain+'.fna')
@app.route('/download/mainstrain_specie_growthdata')
def download_mainstrain_specie_growthdata():
"""
Downloads growth summary data for a specific strain and plate of a species.
Query Parameters:
specie (str): The species name.
plateid (str): The plate ID.
strain (str): The strain name.
Returns:
Response: Sends filtered growth summary CSV as an attachment.
"""
specie= request.args.get('specie')
plateid = request.args.get('plateid')
strain = request.args.get('strain')
growth = pd.read_csv('static/'+specie+'/data/growth_summary.csv',index_col='Plate IDs')
growth_filtered = growth.loc[plateid]
# Convert the filtered dataframe to a CSV
csv_string = growth_filtered.to_csv()
# Create a response object and set the appropriate headers
response = Response(
csv_string,
mimetype='text/csv',
headers={
'Content-Disposition': f'attachment;filename={specie}_{strain}_growth_data.csv'
}
)
return response
@app.route('/download/mainstrain_specie_kineticdata')
def download_mainstrain_specie_kineticdata():
"""
Downloads kinetic summary data for a specific strain and plate of a species.
Query Parameters:
specie (str): The species name.
plateid (str): The plate ID.
strain (str): The strain name.
Returns:
Response: Sends filtered kinetic summary CSV as an attachment.
"""
specie= request.args.get('specie')
plateid = request.args.get('plateid')
strain = request.args.get('strain')
growth = pd.read_csv('static/'+specie+'/data/kinetic_summary.csv',index_col='Plate IDs')
growth_filtered = growth.loc[plateid]
# Convert the filtered dataframe to a CSV
csv_string = growth_filtered.to_csv()
# Create a response object and set the appropriate headers
response = Response(
csv_string,
mimetype='text/csv',
headers={
'Content-Disposition': f'attachment;filename={specie}_{strain}_kinetic_data.csv'
}
)
return response
@app.route('/download/mainstrain_specie_rawdata')
def download_mainstrain_specie_rawdata():
"""
Downloads raw plate summary data for a specific strain and plate of a species.
Query Parameters:
specie (str): The species name.
plateid (str): The plate ID.
strain (str): The strain name.
Returns:
Response: Sends filtered plate summary CSV as an attachment.
"""
specie= request.args.get('specie')
plateid = request.args.get('plateid')
strain = request.args.get('strain')
growth = pd.read_csv('static/'+specie+'/data/plate_summary.csv',index_col='Plate IDs')
growth_filtered = growth.loc[plateid]
# Convert the filtered dataframe to a CSV
csv_string = growth_filtered.to_csv()
# Create a response object and set the appropriate headers
response = Response(
csv_string,
mimetype='text/csv',
headers={
'Content-Disposition': f'attachment;filename={specie}_{strain}_raw_data.csv'
}
)
return response
@app.route('/')
@app.route('/index')
def index():
"""
Renders the main index page with trait summary data.
Returns:
Rendered HTML template 'index.html' with trait and category data.
"""
traits,categories = scripts.get_trait_summary()
return render_template('index.html',series=traits,categories=categories)
@app.route('/dashboard')
def dashboard():
"""
Renders the dashboard page.
Returns:
Rendered HTML template 'index.html'.
"""
return render_template('index.html')
@app.route('/tree')
def tree():
"""
Renders the species tree page with summary statistics.
Query Parameters:
specie (str): The species name.
Returns:
Rendered HTML template 'tree.html' with tree and compound data.
"""
specie=request.args.get('specie')
specie_summary = pd.read_csv('static/'+specie+'/metadata/summary.csv',index_col='Plate IDs')
plates = specie_summary['Plate'].unique()
comps = scripts.get_compounds_from_plates(plates)
spe_mash = scripts.calculate_specie_inter_cluster_mash_dist(specie)
spe_mash = [w for w in spe_mash if w!=0]
std_dev = np.var(spe_mash)#np.std(spe_mash, ddof=1)
specie_inter_mash = np.median(spe_mash)
lb = specie_inter_mash - std_dev
ub = specie_inter_mash + std_dev
specie_mash_min = min(spe_mash, key=lambda x: abs(x - ub))
specie_mash_max = min(spe_mash, key=lambda x: abs(x - lb))
return render_template('tree.html',specie=specie,comps=comps,specie_inter_mash=specie_inter_mash,spe_min = specie_mash_min,spe_max = specie_mash_max,
specie_individual_points = spe_mash)
@app.route('/tree_json')
def get_tree():
"""
Returns the species tree data in JSON format, annotated with cluster information.
Query Parameters:
specie (str): The species name.
Returns:
JSON: Tree data with cluster annotations.
"""
specie=request.args.get('specie')
with open("static/"+specie+"/tree.json", "r") as f:
tree_data = json.load(f)
cluster_data = scripts.load_cluster_data(specie)
def add_clusters(node):
if 'name' in node:
node['cluster'] = cluster_data.get(node['name'], None)
if 'children' in node:
for child in node['children']:
add_clusters(child)
return node
tree_data = add_clusters(tree_data)
return jsonify(tree_data)
@app.route('/track_tree_json',methods=['GET'])
def get_track_tree():
"""
Returns tracked tree data and phenotype/kinetic statistics for a given plate and well.
Query Parameters:
specie (str): The species name.
plate (str): The plate name (default 'PM01').
well (str): The well name (default 'H12').
Returns:
JSON: Tree data, phenotype mash statistics, kinetic means/errors, and strain lists.
"""
from scipy.stats import ttest_ind
specie=request.args.get('specie')
plate = request.args.get('plate', 'PM01')
well = request.args.get('well', 'H12')
with open("static/"+specie+"/tree.json", "r") as f:
tree_data = json.load(f)
cluster_data,growth_strains,nogrowth_strains = scripts.get_tracking_growth_data(specie,plate,well)
kinetic_means,kinetic_errors,categories = scripts.get_tracking_kinetic_params(nogrowth_strains,specie,plate,well,growth_strains,param='Max Resp')
spe_mash = scripts.calculate_specie_inter_cluster_mash_dist(specie)
spe_mash = [w for w in spe_mash if w!=0]
if(len(growth_strains)>2):
phen_mash = scripts.calculate_phenotype_median_mash(specie,growth_strains)
phen_mash = [w for w in phen_mash if w!=0]
phenotype_mash = np.median(phen_mash)
std_dev = np.std(phen_mash, ddof=0)#np.var(phen_mash)#np.std(phen_mash, ddof=1)
lb = phenotype_mash - std_dev
ub = phenotype_mash + std_dev
phenotype_mash_min = min(phen_mash, key=lambda x: abs(x - lb))
phenotype_mash_max = min(phen_mash, key=lambda x: abs(x - ub))
_, p_value = ttest_ind(spe_mash, phen_mash, equal_var=False)
elif(len(growth_strains)==2):
phen_mash = scripts.calculate_phenotype_median_mash(specie,growth_strains)
phen_mash = [w for w in phen_mash if w!=0]
phenotype_mash = np.median(phen_mash)
phenotype_mash_min = phenotype_mash
phenotype_mash_max = phenotype_mash
p_value = 'null (only 2 strains grow)'#ttest_ind(spe_mash, phen_mash, equal_var=False)
elif(len(growth_strains)==1):
phen_mash = scripts.calculate_phenotype_median_mash(specie,growth_strains)
phenotype_mash = np.median(phen_mash)
phenotype_mash_min = phenotype_mash
phenotype_mash_max = phenotype_mash
p_value = 'null (only 1 strain grows)'#ttest_ind(spe_mash, phen_mash, equal_var=False)
else:
phen_mash = []
phenotype_mash = 'null'
phenotype_mash_min = 'null'
phenotype_mash_max = 'null'
p_value='null (no strains grow)'
def add_clusters(node):
if 'name' in node:
node['cluster'] = cluster_data.get(node['name'], None)
if 'children' in node:
for child in node['children']:
add_clusters(child)
return node
tree_data = add_clusters(tree_data)
return jsonify({
"tree_data": tree_data,
"phe_mash": phenotype_mash,
"phe_min": phenotype_mash_min ,
"phe_max": phenotype_mash_max,
"phe_individual_points":phen_mash,
"kinetic_means":kinetic_means,
"kinetic_errors":kinetic_errors,
"all_strains":categories,
"pval": p_value,
"growth_strains":growth_strains,
"nogrowth_strains":nogrowth_strains
})
@app.route('/signal')
def signal():
"""
Renders the signal page showing growth curves for a given plate, species, and well.
Query Parameters:
pltid (str): Plate ID.
strn (str): Species name.
well (str): Well name.
Returns:
Rendered HTML template 'signal.html' with growth data and time scale.
"""
plateid = request.args.get('pltid')
specie = request.args.get('strn')
well = request.args.get('well')
growth_data_entries = GrowthData.query.filter_by(plateid=plateid, specie=specie, well=well).all()
growth_data = [
{'name': f"{entry.compound} {entry.replicates}", 'data': entry.signal_data}
for entry in growth_data_entries
]
time_scale = list(range(0, 49, 1))
#growth_data,time_scale = scripts.get_all_growth_curves(plateid,specie,well=well)
return render_template('signal.html',growth_data=growth_data,time_scale=time_scale)
@app.route('/about',methods=['GET', 'POST'])
def about():
"""
Renders the about page with control and growth well distributions.
Returns:
Rendered HTML template 'about.html' with control and growth well data.
"""
control_wells,growth_wells=scripts.get_control_well_dist('pputida')
#control_wells = random.sample(control_wells, 100)
return render_template('about.html',control_wells = control_wells,growth_wells=growth_wells)
@app.route('/plates')
def plates():
"""
Renders the plates page.
Returns:
Rendered HTML template 'plates.html'.
"""
return render_template('plates.html')
@app.route('/ticket' ,methods=['GET', 'POST'])
def ticket():
"""
Handles user support ticket submissions.
POST:
Receives name, email, and message from form and sends an email.
GET:
Renders the ticket submission form.
Returns:
Success message or rendered HTML template 'ticket.html'.
"""
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
message = request.form['message']
scripts.send_email(name, email, message)
return 'Message sent successfully!'
return render_template('ticket.html')
@app.route('/explore',methods=['GET', 'POST'])
def explore():
"""
Renders the comparative analysis page for selected strains and compounds.
POST:
Processes selected strains and compound, returns comparative analysis.
GET:
Renders the explore page with available entries and options.
Returns:
Rendered HTML template 'comparative_analysis.html' or 'explore.html'.
"""
if request.method == 'POST':
# selected_entries = request.form.getlist('selected_entries')
chosen_option = request.form.get('selected_option')
selected_entries = request.form.getlist('selected_entries[]')
plate,well = scripts.get_plate_well_from_compound(chosen_option)
plateids = scripts.get_plateid_from_strain(selected_entries,plate)
xlabels = scripts.get_strain_names(selected_entries)
ylabels = [chosen_option]
growth_calls,series,time = scripts.get_growth_calls_from_plateids(plateids,well,xlabels)
return render_template('comparative_analysis.html',growth_calls=growth_calls,xlabels=xlabels,ylabels=ylabels,series=series,time=time)
options = scripts.get_all_compounds_in_all_wells()
entries = scripts.combine_specie_summaries()
return render_template('explore.html',entries=entries,options=options)
@app.route('/plate_descriptions/json', methods=['GET'])
def plate_descriptions_json():
"""
Returns plate descriptions in JSON format.
Query Parameters:
strain (str): Strain name.
Returns:
JSON: Plate description data.
"""
strain = request.args.get('strain')
plate_desc = pd.read_csv('./static/'+'plate_desc/platedesc.csv')
out2 = []
for i in plate_desc.index:
plate = plate_desc.loc[i,'Plate']
well = plate_desc.loc[i,'Well']
compound = plate_desc.loc[i,'Compound']
description = plate_desc.loc[i,'Description']
kegg_id = plate_desc.loc[i,'KEGG ID']
cas_id = plate_desc.loc[i,'CAS ID']
out2.append([
#str(plateid),
str(plate),
str(well),
str(compound),
str(description),
# str(kegg_id),
"<a href=https://www.genome.jp/entry/"+str(kegg_id)+">"+str(kegg_id)+"</a>",
str(cas_id)])
#return jsonify(data=out)
return jsonify(data=out2)
@app.route('/species', methods=['GET'])
def species():
"""
Renders the species page with metadata and summary information.
Query Parameters:
specie (str): Species name.
Returns:
Rendered HTML template 'species.html' with metadata.
"""
specie = request.args.get('specie')
specie_name = specie[0].upper() +'. '+specie[1:]
samples,strains,available_plates,clusters,plates = scripts.load_specie_metadata(specie)
return render_template('species.html',specie=specie,specie_name=specie_name,samples=samples,strains=strains,available_plates=available_plates,
clusters=clusters,plates=plates)
# Define a sorting key function
def sort_key(compound):
"""
Sorting key for compounds based on well order.
Args:
compound (str): Compound string in format 'Well: Compound'.
Returns:
int: Index of the well in plate order.
"""
wells = []
for letter in range(ord('A'), ord('H') + 1):
for num in range(1, 13):
wells.append(chr(letter) + "{:02d}".format(num))
well = compound.split(':')[0]
return wells.index(well)
@app.route('/mainstraindata', methods=['GET'])
def mainstraindata():
"""
Renders the main strain data page for a given plate and strain.
Query Parameters:
pltid (str): Plate ID.
strn (str): Species name.
plate (str): Plate name.
strid (str): Strain ID.
metadata (str): Metadata.
media (str): Media.
strain (str): Strain name.
Returns:
Rendered HTML template 'mainstraindata.html' with kinetic and growth data.
"""
plateid = request.args.get('pltid')
specie = request.args.get('strn')
plate = request.args.get('plate')
strid = request.args.get('strid')
metadata = request.args.get('metadata')
media = request.args.get('media')
strain = request.args.get('strain')
categories_list, mean_data, error_data,param_name = scripts.get_kinetic_parameters(plateid,specie,param='Max Resp')
wells = []
for letter in range(ord('A'), ord('H') + 1):
for num in range(1, 13):
wells.append(chr(letter) + "{:02d}".format(num))
#growth_data,time_series,dropdown_names = scripts.get_all_growth_curves(plateid,specie,wells=['A01'])
growth_data_entries = GrowthData.query.filter_by(plateid=plateid, specie=specie, well='A01').all()
growth_data = [
{'name': f"{entry.compound} {entry.replicates}", 'data': entry.signal_data}
for entry in growth_data_entries
]
# # Corrected code for filtering by a list of wells
# growth_data_entries = GrowthData.query.filter(GrowthData.plateid == plateid,GrowthData.specie == specie,GrowthData.well.in_(wells)).all()
# dropdown_compounds = list(set([entry.well +': ' +entry.compound for entry in growth_data_entries]))
# dropdown_compounds = sorted(dropdown_compounds, key=sort_key)
dropdown_compounds = scripts.get_compound_drop_down(plate)
time_series = list(np.arange(0,48.25,0.25))
return render_template('mainstraindata.html',pltid=plateid,strn=specie,categories = categories_list,mean_data = mean_data,error_data =
error_data,param_name=param_name,growth_data=growth_data,time_series=time_series,dropdown_compounds=dropdown_compounds,
strid=strid,media=media,metadata=metadata,plate=plate,strain=strain)
@app.route('/update_chart', methods=['GET'])
def update_chart():
"""
Returns updated kinetic chart data for a given plate, species, and parameter.
Query Parameters:
pltid (str): Plate ID.
strn (str): Species name.
param (str): Kinetic parameter.
Returns:
JSON: Chart categories, mean data, error data, and parameter name.
"""
plateid = request.args.get('pltid')
specie = request.args.get('strn')
param = request.args.get('param')
categories, mean_data, error_data,param_name = scripts.get_kinetic_parameters(plateid, specie, param=param)
return jsonify(categories=categories, mean_data=mean_data, error_data=error_data,param_name=param)
@app.route('/update_tracking_kinetics_chart', methods=['POST'])
def update_tracking_kinetics_chart():
"""
Returns updated tracking kinetics chart data for selected strains and parameter.
POST Data:
growth_strains (list): List of strains with growth.
no_growth_strains (list): List of strains without growth.
param (str): Kinetic parameter.
specie (str): Species name.
plate (str): Plate name.
well (str): Well name.
Returns:
JSON: Chart categories, mean data, error data, and parameter name.
"""
data = request.get_json()
growth_strains = data.get('growth_strains')
no_growth_strains = data.get('no_growth_strains')
param = data.get('param')
specie = data.get('specie')
plate = data.get('plate')
well = data.get('well')
mean_data,error_data,categories = scripts.get_tracking_kinetic_params(no_growth_strains, specie, plate, well, growth_strains, param)
return jsonify(categories=categories, mean_data=mean_data, error_data=error_data,param_name=param)
@app.route('/update_growth_curve', methods=['GET'])
def update_growth_curve():
"""
Returns updated growth curve data for a given plate, species, and compound.
Query Parameters:
pltid (str): Plate ID.
strn (str): Species name.
compound (str): Compound string.
Returns:
JSON: Growth curve data.
"""
plateid = request.args.get('pltid')
specie = request.args.get('strn')
compound = request.args.get('compound')
well = compound.split(':')[0]
growth_data_entries = GrowthData.query.filter_by(plateid=plateid, specie=specie, well=well).all()
growth_data = [
{'name': f"{entry.compound} {entry.replicates}", 'data': entry.signal_data}
for entry in growth_data_entries
]
return jsonify(growth_data=growth_data)
@app.route('/straindata', methods=['GET'])
def straindata():
"""
Renders the strain data heatmap page for a specific strain.
Returns:
Rendered HTML template 'straindata.html' with heatmap and compound data.
"""
growth_calls,well_char,well_id,compound_dict = scripts.get_strain_data('ECP120')
chart= {'type': 'heatmap','marginTop': 40,'marginBottom': 80,'plotBorderWidth': 1}
title= {'text': ''}
xAxis= {
'categories': well_id,
'labels':{'style':{'fontWeight':'bold','fontSize':'2em','fontFamily':'Monospace'}}
}
yAxis= {
'categories': well_char,
'title': 'null',
'reversed': 'true',
'labels':{'style':{'fontWeight':'bold','fontSize':'2em','fontFamily':'Monospace'}}
}
legend= {
'enabled':'false',
'align': 'right',
'layout': 'vertical',
'margin': 0,
'verticalAlign': 'top',
'y': 1,
'symbolHeight': 280
}
series= [{
'name': 'Growth(1)/No Growth(0)/Uncertain(0.5)',
'borderWidth': 2.5,
'borderColor':'#0a000f',
'data': growth_calls,
'dataLabels': {
'enabled': 'false',
'color': '#000000',
}
}]
return render_template('straindata.html',chartID='container', chart=chart, data=growth_calls,
title=title,legend = legend,xAxis = xAxis,yAxis=yAxis,compound_dict = compound_dict)
@app.route('/strain_kinetics/json', methods=['GET'])
def strain_kinetics_json():
"""
Returns kinetic parameters for a given plate and strain in JSON format.
Query Parameters:
spec (str): Strain name.
plate (str): Plate ID.
Returns:
JSON: Kinetic parameter data.
"""
strain = request.args.get('spec')
plateid = request.args.get('plate')
out2 = scripts.get_kinetic_parameters(plateid,strain)
return jsonify(data=out2)
@app.route('/strain_growth/json', methods=['GET'])
def strain_growth_json():
"""
Returns growth table for a given plate and strain in JSON format.
Query Parameters:
spec (str): Strain name.
plate (str): Plate ID.
Returns:
JSON: Growth table data.
"""
strain = request.args.get('spec')
plateid = request.args.get('plate')
out2 = scripts.get_growth_table(plateid,strain)
return jsonify(data=out2)
@app.route('/get_growth_curves/json',methods=['POST'])
def get_growth_curves():
"""
Returns growth curves for a given well, plate, and species.
POST Data:
well (str): Well name.
plateid (str): Plate ID.
specie (str): Species name.
Returns:
JSON: Chart data for growth curves.
"""
well = request.form['well']
plateid = request.form['plateid']
specie = request.form['specie']
chart_data = scripts.get_growth_curves(well,plateid,specie)
return jsonify(chart_data)
@app.route('/strains/json', methods=['GET'])
def strains_json():
"""
Returns strain metadata in JSON format.
Query Parameters:
strain (str): Strain name.
Returns:
JSON: Strain metadata.
"""
strain = request.args.get('strain')
strain_data = pd.read_csv('./static/'+strain+'/metadata/updated_summary.csv')
out2 = []
for i in strain_data.index:
plateid = strain_data.loc[i,'Plate IDs']
id = strain_data.loc[i,'Strain ID']
plate = strain_data.loc[i,'Plate']
media = strain_data.loc[i,'Media']
strain = strain_data.loc[i,'Strain']
metadata = strain_data.loc[i,'Metadata/Modifications']
phylo = strain_data.loc[i,'Phylogroup/Genome Cluster']
mlst = strain_data.loc[i,'MLST']
project = strain_data.loc[i,'Project']
temperature = strain_data.loc[i,'Temperature']
respiration = strain_data.loc[i,'Respiration']
marker = strain_data.loc[i,'Selection Marker']
reader = strain_data.loc[i,'Plate Reader']
mode = strain_data.loc[i,'Detection mode']
replicates = strain_data.loc[i,'Replicates']
out2.append([
#"<a href="+url_for('mainstraindata',pltid=str(plateid),strn=request.args.get('strain'))+">"+str(plateid)+"</a>",
str(plateid),
#str(plateid),
str(id),
str(plate),
str(media),
str(strain),
str(metadata),
str(phylo),
str(mlst),
str(project),
str(temperature),
str(respiration),
str(marker),