/
views.py
7566 lines (7043 loc) · 313 KB
/
views.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
import math
import json
import datetime
import csv
import os
import zipfile
import tempfile
import numpy as np
from numpy.lib import recfunctions as rfn
import numpy
from datetime import timedelta
import random
import time
from django.core.servers.basehttp import FileWrapper
from django.db import connection
from django.db.models import Q
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.contrib.auth.models import User
# from django.http import HttpResponse
from gardener.models import *
import experiments.models
from django.core.serializers.json import DjangoJSONEncoder
import commands
import sys
import re
from django.http import HttpResponse
from numpy import array, repeat, concatenate, ones, zeros, arange, reshape, put, add, dot, take, float32
from numpy.linalg import pinv
from scipy.signal.signaltools import lfilter
from django.shortcuts import render
import multiprocessing
from multiprocessing import Process, Manager, Pool
from rpy2 import robjects as ro
from rpy2.robjects.packages import importr
from django.contrib.auth.decorators import login_required
from django.conf import settings
from qc import my_QC
from cal_area import calcAreas
import pathway
import genome
import signif
from operator import attrgetter
import newfuncTest
# standarlib by Garfiled
import firmianaLib
from experiments.models import AuthChildUser
from experiments.models import AuthParentChildAssociation
from experiments.models import AuthChildUserAndSharedExp
from experiments.models import PublicExperiments
#from leafy.views import isChildAccount
tmpdir = pathway.tmpdir
#ms_dir = '/usr/local/firmiana/galaxy-dist/database/files/ms_peak/'
ms_dir = '/usr/local/firmiana/NFS_89/ms_peak/'
quant_dir = '/usr/local/firmiana/data/QuantTable/'
NEW = 'new'
RUNNING = 'running'
DONE = 'done'
ERROR = 'error'
''' When httpd restart, all running jobs are killed '''
for runningJob in XsearchTable.objects.filter(status=RUNNING):
runningJob.status = ERROR
runningJob.save()
def gardener_isValidatedChild(request):
'''
Response to request.
Validate whether the current user is a validated child account.
'''
userId = request.user.id
child = AuthChildUser.objects.all().filter(id=userId, child_is_active=True)
if child:
success = 1
prompt = "The current user is a child account"
else:
success = 0
prompt = "The current user is not a child account"
data = {"success": success, "prompt": prompt}
result = json.dumps(data, cls=DjangoJSONEncoder)
return HttpResponse(result)
def gardener_isValidatedParent(request):
'''
Response to request.
Validate whether the current user is a validated parent account.
'''
userId = request.user.id
parentFlag = gardener_isParent(userId)
if parentFlag:
success = 1
prompt = "The current user is a parent account"
else:
success = 0
prompt = "The current user is not a parent account"
data = {"success": success, "prompt": prompt}
result = json.dumps(data, cls=DjangoJSONEncoder)
return HttpResponse(result)
def gardener_isValidatedGuest(request):
'''
Response to request.
Validate whether the current user is a validated guest account.
'''
userId = request.user.id
guestFlag = gardener_isisGuest(userId)
if guestFlag:
success = 1
prompt = "The current user is a guest account"
else:
success = 0
prompt = "The current user is not a guest account"
data = {"success": success, "prompt": prompt}
result = json.dumps(data, cls=DjangoJSONEncoder)
return HttpResponse(result)
def gardener_isGuest(userId):
guest = User.objects.all().filter(id=userId)
if guest:
guest = guest[0]
if guest.username == "Guest":
return True
else:
return False
else:
return False
def gardener_isChild(userId):
'''
Validate whether the current user is a validated child account.
If the user is a child, the function returns True, otherwise, the function return False
'''
child = AuthParentChildAssociation.objects.all().filter(child_id=userId)
if child:
return True
else:
return False
def gardener_isParent(userId):
'''
Validate whether the current user is a validated parent account.
If the user is a parent, the function returns True, otherwise, the function return False
'''
childFlag = gardener_isChild(userId)
if not childFlag:
parent = User.objects.all().filter(id=userId)
if parent:
return True
else:
return False
else:
return False
def gardener_guestVisableExperiments():
guestVisableExps = PublicExperiments.objects.all()
if guestVisableExps:
experiment_list = Experiment.objects.all().filter(name=guestVisableExps[0].expName)
guestVisableExps_count = len(guestVisableExps)
for i in range(1,guestVisableExps_count):
tmpExpInstance = Experiment.objects.all().filter(name=guestVisableExps[i].expName)
experiment_list = experiment_list|tmpExpInstance
else:
experiment_list = Experiment.objects.all().filter(name="Exp000000")
return experiment_list
def gardener_childVisableExperiments(userId):
childSharedExps = AuthChildUserAndSharedExp.objects.all().filter(child_id=userId)
if childSharedExps:
childSharedExps = childSharedExps[0]
sharedExps = childSharedExps.sharedExp.split(",")
sharedExps.sort()
else:
sharedExps = []
if sharedExps:
sharedExps_count = len(sharedExps)
experiment_list = Experiment.objects.all().filter(name=sharedExps[0])
for i in range(1,sharedExps_count):
tmpExpInstance = Experiment.objects.all().filter(name=sharedExps[i])
experiment_list = experiment_list|tmpExpInstance
else:
experiment_list = Experiment.objects.all().filter(name="Exp000000")
return experiment_list
@login_required(login_url=settings.LOGIN_PAGE)
def showdatabase_data(request):
userId = request.user.id
if gardener_isChild(userId):
experiment_list = gardener_childVisableExperiments(userId)
elif gardener_isGuest(userId):
experiment_list = gardener_guestVisableExperiments()
else:
''' Simple Authority '''
lab = experiments.models.User_Laboratory.objects.filter(user=request.user)
lab = lab[0].lab.name if lab.count() else ''
if lab == 'Demo Lab':
experiment_list = Experiment.objects.filter(
is_public=1).filter(is_deleted=0)
elif request.user.is_superuser:
experiment_list = Experiment.objects.filter(is_deleted=0)
else:
experiment_list = Experiment.objects.filter(
lab=lab).filter(is_deleted=0)
Extra_Exp = Share_Exp.objects.filter(lab=lab)
for extra in Extra_Exp:
experiment_list = experiment_list | Experiment.objects.filter(
id=extra.exp.id)
public_exp = Experiment.objects.filter(is_public=1)
experiment_list = experiment_list | public_exp
'''
multi-sort is done below
'''
filters = []
if 'filter' in request.GET:
filters = json.loads(request.GET['filter'])
else:
filters = []
property = 'name'
direction = ''
if 'sort' in request.GET:
sort = json.loads(str(request.GET['sort'])[1:-1])
property = sort['property']
if sort['direction'] == 'DESC':
direction = '-'
else:
property = "name"
direction = '-'
start = int(request.GET['start'])
limit = int(request.GET['limit'])
end = start + limit
experiment_list = firmianaLib.result_filter(experiment_list, filters)
count = experiment_list.count()
if end > count or limit == -1:
end = count
if property !='name':
experiment_list = experiment_list.order_by(direction + property,'-name')[start:end]
else:
experiment_list = experiment_list.order_by(direction + property)[start:end]
expInfo_list = []
for experiment in experiment_list:
temp = {}
temp['id'] = experiment.id
temp['name'] = experiment.name
temp['type'] = experiment.type
temp['description'] = experiment.description
temp['species'] = experiment.species
temp['cell_type'] = experiment.cell_type
temp['tissue'] = experiment.tissue
temp['organ'] = experiment.organ
temp['fluid'] = experiment.fluid
temp['num_fraction'] = experiment.num_fraction
temp['num_repeat'] = experiment.num_repeat
temp['num_spectrum'] = experiment.num_spectrum
temp['num_peptide'] = experiment.num_peptide
temp['num_isoform'] = experiment.num_isoform
temp['num_gene'] = experiment.num_gene
temp['instrument'] = experiment.instrument
temp['protocol'] = experiment.protocol
temp['lab'] = experiment.lab
temp['operator'] = experiment.operator
temp['experiment_date'] = experiment.experiment_date
temp['index_date'] = experiment.index_date
temp['update_date'] = experiment.update_date
temp['stage'] = experiment.stage
temp['state'] = experiment.state
temp['bait'] = experiment.bait
try:
temp['ispec'] = experiments.models.Experiment.objects.get(
id=int(experiment.name.split('Exp')[1])).fm_no
except:
temp['ispec'] = ''
specific = ''
try:
for sample in experiments.models.Experiment.objects.get(id=int(experiment.name.split('Exp')[1])).samples.all():
if sample.source_tissue:
specific = specific + sample.source_tissue.specific_ID + ';'
if sample.source_cell:
specific = specific + sample.source_cell.specific_ID + ';'
if sample.source_fluid:
specific = specific + sample.source_fluid.specific_ID + ';'
except:
specific = ''
temp['specific'] = specific
expInfo_list.append(temp)
data = {"data": expInfo_list, "total": count}
result = json.dumps(data, cls=DjangoJSONEncoder)
return HttpResponse(result)
def showsearch_data(request):
sid = int(request.GET['id'])
Searchs = Search.objects.filter(exp_id=sid).filter(type='rep')
SearchList = []
for search in Searchs:
temp = {}
temp['repeat_id'] = search.repeat_id
temp['fraction_id'] = search.fraction_id
temp['num_fraction'] = Experiment.objects.get(id=search.exp_id).num_fraction
temp['search_id'] = search.id
temp['type'] = search.type
temp['name'] = search.name
temp['exp_id'] = search.exp_id
temp['rank'] = search.rank
temp['num_spectrum'] = search.num_spectrum
temp['num_peptide'] = search.num_peptide
temp['num_isoform'] = search.num_isoform
temp['num_gene'] = search.num_gene
temp['log'] = search.log
temp['create_time'] = search.create_time
temp['date'] = search.update_time
temp['user'] = search.user
temp['stage'] = search.stage
temp['rt_max'] = search.rt_max
temp['parameter'] = search.parameter
SearchList.append(temp)
data = {"data": SearchList, "total": len(SearchList)}
result = json.dumps(data, cls=DjangoJSONEncoder)
return HttpResponse(result)
def showjob(request):
''' Simple Authority '''
uname = str(request.user)
if request.user.is_superuser:
job_list = XsearchTable.objects.all()
else:
job_list = XsearchTable.objects.filter(user=uname)
'''
multi-sort is done below
'''
filters = []
if 'filter' in request.GET:
filters = json.loads(request.GET['filter'])
else:
filters = []
property = '?'
direction = ''
if 'sort' in request.GET:
sort = json.loads(str(request.GET['sort'])[1:-1])
property = sort['property']
if sort['direction'] == 'DESC':
direction = '-'
else:
property = "id"
direction = '-'
property = 'exp_num' if property == 'explist_length' else property
start = int(request.GET['start'])
limit = int(request.GET['limit'])
end = start + limit
job_list = firmianaLib.result_filter(job_list, filters)
count = job_list.count()
if end > count or limit == -1:
end = count
job_list = job_list.order_by(direction + property)[start:end]
jobs = []
for job in job_list:
temp = {}
temp['csv_name'] = job.id
temp['dmz'] = job.dmz
temp['drt'] = job.drt
temp['ionscore'] = job.ionscore
temp['searchs'] = job.searchs
temp['compare'] = job.compare
temp['qc'] = job.qc
temp['done'] = job.done
temp['ProGene'] = job.ProGene
temp['create_time'] = job.create_time
temp['update_time'] = job.update_time
temp['user'] = job.user
temp['status'] = job.status
temp['explist'] = job.exp_name
temp['exp_name'] = '*'.join([Experiment.objects.get(
id=exp_str.split('_')[1]).name for exp_str in job.exp_name.split(",")])
temp['explist_length'] = job.exp_num
temp['description'] = job.description
jobs.append(temp)
data = {"data": jobs, "total": count}
result = json.dumps(data, cls=DjangoJSONEncoder)
return HttpResponse(result)
def help(request):
return render_to_response('gardener/help.html')
@login_required(login_url=settings.LOGIN_PAGE)
def gardener(request):
if 'theme' in request.GET:
theme = request.GET['theme'] if request.GET['theme'] in [
'classic', 'access', 'gray', 'neptune'] else ''
else:
theme = ''
return render_to_response('gardener/gardener.html', {'theme': theme})
@login_required(login_url=settings.LOGIN_PAGE)
def showpeptide_data(request):
if 'sid' in request.GET:
sid = int(request.GET['sid'])
else:
sid = 0
try:
search_id = int(request.GET['search_id'])
except:
search_id = 0
try:
accession = str(request.GET['accession'])
except:
accession = 0
try:
exp_id = int(request.GET['exp_id'])
except:
exp_id = 0
try:
stype = str(request.GET['stype'])
except:
stype = ''
try:
rankid = int(request.GET['rankid'])
except:
rankid = 0
try:
symbol = str(request.GET['symbol'])
except:
symbol = 0
start = int(request.GET['start'])
limit = int(request.GET['limit'])
end = start + limit
'''
multi-sort is done below
'''
filters = []
try:
filters = json.loads(request.GET['filter'])
except:
filters = []
property = '?'
direction = ''
try:
sort = json.loads(str(request.GET['sort'])[1:-1])
property = sort['property']
if sort['direction'] == 'DESC':
direction = '-'
if property == 'exp_name':
property = 'search'
except:
property = "ion_score"
direction = '-'
if stype == 'protein':
tp = Search.objects.filter(id=search_id)[0].type
if tp == 'exp':
peptide_list = Exp_Peptide.objects.all()
elif tp == 'rep':
peptide_list = Repeat_Peptide.objects.all()
elif stype == 'exper' or stype == 'anywhere':
if sid!=6954:
peptide_list = Exp_Peptide.objects.all()
else:
peptide_list = Exp_Peptide_200.objects.all()
# peptide_list = Exp_Peptide.objects.all()
elif stype == 'search':
peptide_list = Repeat_Peptide.objects.all()
elif stype == 'gene':
tp = Search.objects.filter(id=search_id)[0].type
if tp == 'exp':
protein_list = Exp_Protein.objects.all()
peptide_list = Exp_Peptide.objects.all()
elif tp == 'rep':
protein_list = Repeat_Protein.objects.all()
peptide_list = Repeat_Peptide.objects.all()
if len(filters) != 0:
for filter in filters:
if filter['type'] == 'string':
if filter['field'] == 'exp_description':
peptide_list = peptide_list.filter(
search__exp__description__icontains=str(filter['value']))
else:
kwargs = {str(filter['field']) +
'__icontains': str(filter['value'])}
peptide_list = peptide_list.filter(**kwargs)
if filter['type'] == 'numeric':
if filter['comparison'] == 'lt' or filter['comparison'] == 'gt':
kwargs = {
str(filter['field']) + '__' + str(filter['comparison']): str(filter['value'])}
else:
kwargs = {str(filter['field']) +
'__exact': str(filter['value'])}
peptide_list = peptide_list.filter(**kwargs)
if filter['type'] == 'date':
ptime = str(filter['value']).split('/')
if filter['comparison'] == 'lt' or filter['comparison'] == 'gt':
today = str(datetime.datetime(
int(ptime[2]), int(ptime[0]), int(ptime[1])))
kwargs = {str(filter['field']) + '__' +
str(filter['comparison']): today}
peptide_list = peptide_list.filter(**kwargs)
else:
today = datetime.datetime(int(ptime[2]), int(
ptime[0]), int(ptime[1])) - timedelta(days=1)
tomorrow = today + timedelta(days=2)
kwargs = {str(filter['field']) + '__gt': str(today)}
protein_list = protein_list.filter(**kwargs)
kwargs = {str(filter['field']) + '__lt': str(tomorrow)}
peptide_list = peptide_list.filter(**kwargs)
if stype == 'protein':
peptide_list = peptide_list.filter(protein_group_accessions__contains=accession).filter(
search__id=search_id).exclude(type=-1)
# return HttpResponse(str(accession)+''+str(search_id))
elif stype == 'exper':
sid = Search.objects.filter(exp_id=sid).filter(type='exp')[0].id
peptide_list = peptide_list.filter(search__id=sid).order_by(
direction + property).exclude(type=-1)
elif stype == 'search':
peptide_list = peptide_list.filter(search__id=search_id).order_by(
direction + property).exclude(type=-1)
elif stype == 'gene':
protein_list = protein_list.filter(symbol=symbol).filter(
search__id=search_id).exclude(type=-1).values('accession')
acc_list = []
for tt in protein_list:
acc_list.append(str(tt['accession']))
temp_list = []
for acc in acc_list:
tt_list = peptide_list.filter(search__id=search_id).filter(
protein_group_accessions__contains=acc).order_by(direction + property).exclude(type=-1)
temp_list.extend(tt_list)
peptide_list = list(set(temp_list))
elif stype == 'anywhere':
peptide_list = peptide_list.filter(Q(sequence__icontains=symbol) | Q(
modification__icontains=symbol)).order_by(direction + property).exclude(type=-1)
# only_list = peptide_list.values('sequence', 'modification')
if stype != 'gene':
count = peptide_list.count()
else:
count = len(peptide_list)
# huge = peptide_list.aggregate(Max('area'))['area__max']
if end > count or limit == -1:
end = count
peptide_list = peptide_list[start:end]
# only_list = only_list[start:end]
peptides = []
for peptide in peptide_list:
temp = {}
temp['id'] = peptide.id
temp['ms2'] = peptide.ms2_id
temp['exp_description'] = peptide.search.exp.description
temp['search_id'] = peptide.search_id
temp['sequence'] = peptide.sequence
temp['type'] = peptide.type
temp['quality'] = peptide.quality
temp['num_psms'] = peptide.num_psms
temp['num_proteins'] = peptide.num_proteins
temp['num_protein_groups'] = peptide.num_protein_groups
temp['protein_group_accessions'] = peptide.protein_group_accessions
temp['modification'] = peptide.modification
temp['delta_cn'] = peptide.delta_cn
temp['area'] = peptide.area
temp['fot'] = peptide.fot
temp['q_value'] = peptide.q_value
temp['pep'] = peptide.pep
temp['ion_score'] = peptide.ion_score
temp['exp_value'] = peptide.exp_value
temp['charge'] = peptide.charge
temp['mh_da'] = peptide.mh_da
temp['delta_m_ppm'] = peptide.delta_m_ppm
temp['rt_min'] = round(float(peptide.rt_min), 2)
temp['num_missed_cleavages'] = peptide.num_missed_cleavages
if stype == 'anywhere':
temp['exp_name'] = peptide.search.exp.name
temp['fdr'] = peptide.fdr
temp['from_where'] = peptide.from_where
peptides.append(temp)
data = {"data": peptides, "total": count}
result = json.dumps(data, cls=DjangoJSONEncoder)
return HttpResponse(result)
@login_required(login_url=settings.LOGIN_PAGE)
def showgene_data(request):
sid = int(request.GET['sid']) if 'sid' in request.GET else 0
stype = str(request.GET['stype']) if 'stype' in request.GET else ''
symbol = str(request.GET['symbol']) if'symbol' in request.GET else ''
start = int(request.GET['start']) if 'start' in request.GET else 0
limit = int(request.GET['limit']) if 'limit' in request.GET else -1
end = start + limit
'''
multi-sort is done below
'''
filters = []
try:
filters = json.loads(request.GET['filter'])
except:
filters = []
property = '?'
direction = ''
try:
sort = json.loads(str(request.GET['sort'])[1:-1])
property = sort['property']
if property == 'exp_name':
property = 'search'
if sort['direction'] == 'DESC':
direction = '-'
except:
property = "area"
direction = '-'
if stype == 'exper' or stype == 'anywhere':
gene_list = Exp_Gene.objects.all()
if stype == 'search':
gene_list = Repeat_Gene.objects.all()
if len(filters) != 0:
for filter in filters:
if filter['field'] == 'user_specified':
anno_protein = user_defined.objects.filter(
user=request.user.id).filter(annotation__icontains=filter['value'])
if stype != 'anywhere':
if stype == 'exper':
species = Search.objects.get(id=Search.objects.filter(
exp_id=sid).filter(type='exp')[0].id).exp.species
else:
species = Search.objects.get(id=sid).exp.species
anno_protein = anno_protein.filter(species=species)
anno_proteins = anno_protein.values_list('symbol', flat=True)
gene_list = gene_list.filter(symbol__in=anno_proteins)
continue
if filter['type'] == 'list':
for anno in filter['value']:
kwargs = {str(filter['field']) + '__icontains': anno}
gene_list = gene_list.filter(**kwargs)
if filter['type'] == 'string':
if filter['field'] == 'exp_description':
gene_list = gene_list.filter(
search__exp__description__icontains=str(filter['value']))
else:
kwargs = {str(filter['field']) +
'__icontains': str(filter['value'])}
gene_list = gene_list.filter(**kwargs)
if filter['type'] == 'numeric':
if filter['comparison'] == 'lt' or filter['comparison'] == 'gt':
kwargs = {
str(filter['field']) + '__' + str(filter['comparison']): str(filter['value'])}
else:
kwargs = {str(filter['field']) +
'__exact': str(filter['value'])}
gene_list = gene_list.filter(**kwargs)
if filter['type'] == 'date':
ptime = str(filter['value']).split('/')
if filter['comparison'] == 'lt' or filter['comparison'] == 'gt':
today = str(datetime.datetime(
int(ptime[2]), int(ptime[0]), int(ptime[1])))
kwargs = {str(filter['field']) + '__' +
str(filter['comparison']): today}
gene_list = gene_list.filter(**kwargs)
else:
today = datetime.datetime(int(ptime[2]), int(
ptime[0]), int(ptime[1])) - timedelta(days=1)
tomorrow = today + timedelta(days=2)
kwargs = {str(filter['field']) + '__gt': str(today)}
gene_list = gene_list.filter(**kwargs)
kwargs = {str(filter['field']) + '__lt': str(tomorrow)}
gene_list = gene_list.filter(**kwargs)
if stype == 'exper':
gene_list = gene_list.filter(search__exp_id=sid).exclude(type=-1)
if stype == 'search':
gene_list = gene_list.filter(search__id=sid).exclude(type=-1)
if stype == 'anywhere':
if property != 'search':
gene_list = gene_list.filter(
symbol__icontains=symbol).exclude(type=-1)
else:
gene_list = gene_list.filter(
symbol__icontains=symbol).exclude(type=-1)
if property == 'search':
gene_list = gene_list.order_by(direction + 'search__exp__id')
elif property == 'user_specified': # some problems I don't know
for gen in range(len(gene_list)):
gene = gene_list[gen]
anno = user_defined.objects.filter(
user=request.user.id, species=gene.search.exp.species, symbol=gene.symbol)
gene_list[gen].user_specified = anno[0].annotation if anno else ""
sorted(gene_list, key=lambda x: x.user_specified)
else:
gene_list = gene_list.order_by(direction + property)
count = gene_list.count()
if end > count or limit == -1:
end = count
gene_list = gene_list[start:end]
genes = []
for gene in gene_list:
temp = {}
temp['id'] = gene.id
temp['exp_description'] = gene.search.exp.description
temp['search_id'] = gene.search_id
temp['symbol'] = gene.symbol
temp['gene_id'] = gene.gene_id
temp['protein_gi'] = gene.protein_gi
temp['num_proteins'] = gene.num_proteins
temp['num_identified_proteins'] = gene.num_identified_proteins
temp['num_uni_proteins'] = gene.num_uni_proteins
temp['num_peptides'] = gene.num_peptides
temp['num_uni_peptides'] = gene.num_uni_peptides
anno = user_defined.objects.filter(
user=request.user.id, species=gene.search.exp.species, symbol=gene.symbol)
temp['user_specified'] = anno[0].annotation if anno else ""
temp['area'] = gene.area
temp['fot'] = gene.fot
temp['ibaq'] = gene.ibaq
temp['fdr'] = gene.fdr
temp['description'] = gene.description
temp['annotation'] = gene.annotation
temp['modification'] = gene.modification
if stype == 'anywhere':
temp['exp_name'] = gene.search.exp.name
temp['fdr'] = gene.fdr
genes.append(temp)
data = {"data": genes, "total": count}
result = json.dumps(data, cls=DjangoJSONEncoder)
return HttpResponse(result)
def download_database(request):
'''
multi-sort is done below
'''
reload(sys)
sys.setdefaultencoding('utf-8')
filters = []
try:
filters = json.loads(request.GET['filter'])
except:
filters = []
'''
sort is done below
'''
property = '?'
direction = ''
try:
sort = json.loads(str(request.GET['sort'])[1:-1])
property = sort['property']
if sort['direction'] == 'DESC':
direction = '-'
except:
property = "id"
direction = ''
''' Simple Authority '''
lab = experiments.models.User_Laboratory.objects.filter(user=request.user)
lab = lab[0].lab if lab.count() else ''
if lab == 'Demo Lab':
experiment_list = Experiment.objects.all().filter(
is_public=1).filter(is_deleted=0)
elif request.user.is_superuser:
experiment_list = Experiment.objects.all().filter(is_deleted=0)
else:
experiment_list = Experiment.objects.all().filter(lab=lab).filter(is_deleted=0)
Extra_Exp = Share_Exp.objects.filter(lab=lab)
for extra in Extra_Exp:
experiment_list = experiment_list | Experiment.objects.filter(
id=extra.exp.id)
if len(filters) != 0:
for filter in filters:
if filter['type'] == 'string':
'''
need to be update:?a a? a
'''
kwargs = {str(filter['field']) +
'__icontains': str(filter['value'])}
experiment_list = experiment_list.filter(**kwargs)
if filter['type'] == 'numeric':
if filter['comparison'] == 'lt' or filter['comparison'] == 'gt':
kwargs = {
str(filter['field']) + '__' + str(filter['comparison']): str(filter['value'])}
else:
kwargs = {str(filter['field']) +
'__exact': str(filter['value'])}
experiment_list = experiment_list.filter(**kwargs)
count = experiment_list.count()
experiment_list = experiment_list.order_by(direction + property)
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="experiment.txt"'
writer = csv.writer(response, delimiter='\t')
writer.writerow(['', 'Name', 'Type', 'Description', 'Species', 'Cell Type', 'Tissue', 'Organ', 'Fraction Num', 'Repeat Num', 'Spectrum Num',
'Peptide Num', 'Isoform Num', 'Gene Num', 'Instrument', 'Protocol', 'Lab', 'Operator', 'Experiment Date', 'Index Date', 'Update Date', 'Stage'])
i = 1
for experiment in experiment_list:
temp = []
temp.append(str(i))
# temp.append(experiment.id)
temp.append(experiment.name)
temp.append(experiment.type)
temp.append(experiment.description)
temp.append(experiment.species)
temp.append(experiment.cell_type)
temp.append(experiment.tissue)
temp.append(experiment.organ)
temp.append(experiment.num_fraction)
temp.append(experiment.num_repeat)
temp.append(experiment.num_spectrum)
temp.append(experiment.num_peptide)
temp.append(experiment.num_isoform)
temp.append(experiment.num_gene)
temp.append(experiment.instrument)
temp.append(experiment.protocol)
temp.append(experiment.lab)
temp.append(experiment.operator)
temp.append(experiment.experiment_date)
temp.append(experiment.index_date)
temp.append(experiment.update_date)
temp.append(experiment.stage)
temp = [str(item) for item in temp]
writer.writerow(temp)
i += 1
return response
def download_protein(request):
'''
multi-sort is done below
'''
reload(sys)
sys.setdefaultencoding('utf-8')
try:
sid = int(request.GET['sid'])
except:
sid = 0
try:
stype = str(request.GET['stype'])
except:
stype = ''
filters = []
try:
filters = json.loads(request.GET['filter'])
except:
filters = []
try:
exp_name = str(request.GET['exp_name'])
except:
exp_name = ''
symbol = str(request.GET['symbol']) if 'symbol' in request.GET else ''
'''
sort is done below
'''
property = '?'
direction = ''
try:
sort = json.loads(str(request.GET['sort'])[1:-1])
property = sort['property']
if sort['direction'] == 'DESC':
direction = '-'
except:
property = "id"
direction = ''
if stype == 'exper':
if exp_name == '':
exp_name = Experiment.objects.get(id=sid).name
protein_list = Exp_Protein.objects.filter(
search__exp__id=sid).filter(search__type='exp').filter(type=1)
else:
#exp_name = Experiment.objects.get(id=sid).name
protein_list = Exp_Protein.objects.filter(search__exp__name=exp_name).filter(search__type='exp').filter(type=1)
if stype == 'search':
protein_list = [] # Repeat_Protein.objects.all().filter(search_id=sid)
if stype == 'anywhere' or stype == 'anno':
protein_list = Exp_Protein.objects.all()
if stype == 'anywhere':
exp_name = symbol
protein_list = protein_list.filter(Q(other_members__icontains=symbol) | Q(accession__icontains=symbol) | Q(
symbol__icontains=symbol) | Q(description__icontains=symbol)).order_by(direction + property).exclude(type=-1)
# protein_list = Protein.objects.all()
if len(filters) != 0:
for filter in filters:
if filter['type'] == 'list':
for anno in filter['value']:
kwargs = {str(filter['field']) + '__icontains': anno}
protein_list = protein_list.filter(**kwargs)
if filter['type'] == 'string':
kwargs = {str(filter['field']) +
'__icontains': str(filter['value'])}
protein_list = protein_list.filter(**kwargs)
if filter['type'] == 'numeric':
if filter['comparison'] == 'lt' or filter['comparison'] == 'gt':
kwargs = {
str(filter['field']) + '__' + str(filter['comparison']): str(filter['value'])}
else:
kwargs = {str(filter['field']) +
'__exact': str(filter['value'])}
protein_list = protein_list.filter(**kwargs)
count = protein_list.count()
protein_list = protein_list.order_by(direction + property)
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=' + \
exp_name + '_protein.txt'
writer = csv.writer(response, delimiter='\t')
title = ['Accession', 'Annotation', 'Modification', 'Same set', 'Symbol', 'Description', 'Score',
'Coverage', '# Proteins', '# Unqiue Peptides', '# Peptides',
'# PSMs', 'Area', 'FoT(1e-6)', 'iBAQ', 'Length', 'MW', 'calc. pI']
if stype == 'anywhere':
title = ['ExpName', 'Exp Description'] + title
writer.writerow(title)
i = 1
for protein in protein_list:
temp = []
# temp.append(str(i))
# temp.append(protein.id)
if stype == 'anywhere':
temp.append(protein.search.exp.name)
temp.append(protein.search.exp.description)
temp.append(protein.accession)
temp.append(protein.annotation)
temp.append(protein.modification)
temp.append(protein.other_members)
temp.append(protein.symbol)
temp.append(protein.description)
temp.append(protein.score)
temp.append(protein.coverage)
temp.append(protein.num_proteins)
temp.append(protein.num_uni_peptides)
temp.append(protein.num_peptides)
temp.append(protein.num_psms)
temp.append(protein.area)
temp.append(protein.fot)
temp.append(protein.ibaq)
temp.append(protein.length)
temp.append(protein.mw)
temp.append(protein.calc_pi)
temp = [str(item) for item in temp]
writer.writerow(temp)
i += 1
return response
def download_peptide(request):
reload(sys)
sys.setdefaultencoding('utf-8')
try:
sid = int(request.GET['sid'])
except:
sid = 0
try:
stype = str(request.GET['stype'])
except:
stype = ''
try:
exp_name = str(request.GET['exp_name'])
except:
exp_name = ''
filters = []
try:
filters = json.loads(request.GET['filter'])
except:
filters = []
'''
sort is done below
'''
property = '?'
direction = ''
try: