This repository has been archived by the owner on Jan 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
views.py
3171 lines (2790 loc) · 182 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
# -*- coding: utf-8 -*-
## import django
import statistics
import re, os, shutil
import datetime, time
from .fusioncharts.fusioncharts import FusionCharts
from django.shortcuts import get_object_or_404, render, redirect
from django.http import HttpResponse
from django.template import loader
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
#from django.contrib.auth.models import Group
from django_utils.models import Profile, Center
from django_utils.views import check_user_group
from .models import *
from iSkyLIMS_wetlab import wetlab_config
## import methods defined on utils.py
from .utils.sample_sheet_utils import *
from .utils.stats_calculation import *
from .utils.stats_graphics import *
from .utils.generic_functions import *
from .utils.library_kits import *
from .utils.fetching_information import *
from .utils.testing_wetlab_configuration import *
#from .utils.samplesheet_checks import *
#from .utils.parsing_run_info import get_machine_lanes
#from .utils.wetlab_misc_utilities import normalized_data
def index(request):
#
return render(request, 'iSkyLIMS_wetlab/index.html')
@login_required
def register_wetlab(request):
#
return render(request, 'iSkyLIMS_wetlab/index.html')
@login_required
def create_nextseq_run (request):
## Check user == WETLAB_MANAGER: if false, redirect to 'login' page
if request.user.is_authenticated:
if not is_wetlab_manager(request):
return render (
request,'iSkyLIMS_wetlab/error_page.html',
{'content':['You do not have enough privileges to see this page ',
'Contact with your administrator .']})
else:
#redirect to login webpage
return redirect ('/accounts/login')
## FIRST STEP in collecting data from the NextSeq run. Sample Sheet and experiment name are required
if request.method == 'POST' and (request.POST['action']=='uploadFile'):
get_user_names={}
projects=[]
#run_name=request.POST['runname']
myfile = request.FILES['myfile']
## CHECK if file contains the extension.
## Error page is showed if file does not contain any extension
split_filename=re.search('(.*)(\.\w+$)',myfile.name)
if None==split_filename:
return render (
request,'iSkyLIMS_wetlab/error_page.html',
{'content':['Uploaded file does not containt extension',
'Sample Sheet must have a csv extension', '', 'ADVICE:',
'Select the Sample file generated by Illumina Experient Manager (IEM)']})
ext_file=split_filename.group(2)
## CHECK if file contains the csv extension.
## Error page is shown if file does not contain the csv extension
if ext_file != '.csv':
return render (
request,'iSkyLIMS_wetlab/error_page.html',
{'content':['Sample Sheet must have a csv extension', '', 'ADVICE:',
'Select the Sample file generated by Illumina Experient Manager (IEM)']})
fs = FileSystemStorage()
timestr = time.strftime("%Y%m%d-%H%M%S")
## including the timestamp to the sample sheet file
# do not need to include the absolute path because django uses
# the MEDIA_ROOT variable defined on settings to upload the file
file_name=str(wetlab_config.RUN_SAMPLE_SHEET_DIRECTORY
+ split_filename.group(1) + timestr + ext_file)
filename = fs.save(file_name, myfile)
uploaded_file_url = fs.url(filename)
### add the document directory to read the csv file
stored_file = os.path.join(settings.MEDIA_ROOT, file_name)
## Fetch the experiment name and the library name from the sample sheet file
index_library_name = get_library_name(stored_file)
run_name = get_experiment_name(stored_file)
if run_name == '':
## define an temporary unique value for the run name
#until the real value is get from user FORM
run_name = timestr
## Check that runName is not already used in the database.
## Error page is showed if runName is already defined
if (RunProcess.objects.filter(runName = run_name)).exists():
if RunProcess.objects.filter(runName = run_name, state__runStateName__exact ='Pre-Recorded'):
## Delete the Sample Sheet file and the row in database
delete_run = RunProcess.objects.get(runName = run_name, state__runStateName__exact ='Pre-Recorded')
sample_sheet_file = delete_run.get_sample_file()
full_path_sample_sheet_file = os.path.join(settings.MEDIA_ROOT, sample_sheet_file)
os.remove(full_path_sample_sheet_file)
delete_run.delete()
else:
# delete sample sheet file
os.remove(stored_file)
return render (request,'iSkyLIMS_wetlab/error_page.html',
{'content':['Run Name is already used. ',
'Run Name must be unique in database.',' ',
'ADVICE:','Change the value in the Sample Sheet file ']})
## Fetch from the Sample Sheet file the projects included in
## the run and the user. Error page is showed if not project/description
## colunms are found
project_list=get_projects_in_run(stored_file)
if len (project_list) == 0 :
## delete sample sheet file
fs.delete(file_name)
return render (request,'iSkyLIMS_wetlab/error_page.html',
{'content':['Sample Sheet does not contain "Sample project" and/or "Description" fields',
'','ADVICE:','Check that csv file generated by Illumina Experient Manager (IEM) includes these columns']})
## Check if the projects are already defined on database.
## Error page is showed if projects are already defined on database
project_already_defined=[]
for key, val in project_list.items():
# check if project was already saved in database in Not Started State.
# if found delete the projects, because the previous attempt to complete the run was unsuccessful
if ( Projects.objects.filter(projectName__icontains = key).exists()):
if ( Projects.objects.filter(projectName__icontains = key, runprocess_id__state__runStateName = 'Pre-Recorded').exists()):
delete_project = Projects.objects.get(projectName__icontains = key , runprocess_id__state__runStateName = 'Pre-Recorded')
delete_project.delete()
else:
project_already_defined.append(key)
if (len(project_already_defined)>0):
if (len(project_already_defined)>1):
head_text='The following projects are already defined in database:'
else:
head_text='The following project is already defined in database:'
## convert the list into string to display the user names on error page
display_project= ' '.join(project_already_defined)
## delete sample sheet file before showing the error page
fs.delete(file_name)
return render (request,'iSkyLIMS_wetlab/error_page.html',
{'content':[ head_text,'', display_project,'',
'Project names must be unique','', 'ADVICE:',
'Edit the Sample Sheet file to correct this error']})
##Once the information looks good. it will be stores in runProcess and projects table
## store data in runProcess table, run is in pre-recorded state
center_requested_id = Profile.objects.get(profileUserID = request.user).profileCenter.id
center_requested_by = Center.objects.get(pk = center_requested_id)
run_proc_data = RunProcess(runName=run_name,sampleSheet= file_name,
state = RunStates.objects.get(runStateName__exact = 'Pre-Recorded'),
centerRequestedBy = center_requested_by)
run_proc_data.save()
experiment_name = '' if run_name == timestr else run_name
## create new project tables based on the project involved in the run and
## include the project information in projects variable to build the new FORM
run_info_values ={}
run_info_values['experiment_name'] = experiment_name
run_info_values['index_library_name'] = index_library_name
for key, val in project_list.items():
if User.objects.filter(username__exact = val).exists():
userid = User.objects.get(username__exact = val)
else:
userid = None
p_data = Projects(runprocess_id=RunProcess.objects.get(runName =run_name),
projectName=key, user_id=userid)
p_data.save()
projects.append([key, val])
run_info_values['projects_user'] = projects
run_info_values['runname']= run_name
## Get the list of the library kit used (libraryKit)
used_libraries = []
list_libraries = LibraryKit.objects.order_by().values_list('libraryName', flat=True)
run_info_values['used_libraryKit'] = list_libraries
user_names = []
all_users = User.objects.all()
for user in all_users :
user_names.append(user.username)
run_info_values['aval_users'] = user_names
## displays the list of projects and the user names found on Sample Sheet
return render(request, 'iSkyLIMS_wetlab/CreateNextSeqRun.html', {'get_user_names': run_info_values })
## SECOND STEP in collecting data from the NextSeq run. Confirmation /modification of data included in Sample Sheet
elif request.method=='POST' and (request.POST['action']=='displayResult'):
experiment_name = request.POST['experimentname']
run_index_library_name = request.POST['runindexlibraryname']
run_name= request.POST['runname']
projects=request.POST.getlist('project')
user_name=request.POST.getlist('username')
library_kit=request.POST.getlist('libraryKit')
project_index_kit=request.POST.getlist('projectindexlibraryname')
## get the sample sheet used in the run. return error if run already exists
if not RunProcess.objects.filter (runName__exact = run_name).exists():
return render (
request, 'iSkyLIMS_wetlab/error_page.html',
{'content':['You get this error page because you use the back Buttom'
' to return to previous page where asking for library kit name',
'To upload again the shample sheet, use the "Upload the Run" option from the top menu']})
run_p = RunProcess.objects.get(runName__exact = run_name)
s_file=run_p.get_sample_file()
## get the different type of library kit used in the run and
## convert the sample sheet into Base Space. Number of converted
## file will be the same as the number of different lybraries use in the run
library={}
bs_file={}
results=[]
in_file = os.path.join(settings.MEDIA_ROOT,s_file)
# Set unique Sample_ID in the sample sheet
index_file = os.path.join(settings.MEDIA_ROOT,'wetlab', 'index_file')
create_unique_sample_id_values (in_file, index_file)
# create the projects/users to update sample sheet
user_names_in_projects ={}
for p_index in range(len(projects)):
user_names_in_projects[projects[p_index]] = user_name[p_index]
set_user_names_in_sample_sheet (in_file, user_names_in_projects)
## build the project list for each project_library kit
for x in range(len(project_index_kit)):
if project_index_kit[x] in library :
library[project_index_kit[x]].append(projects[x])
else:
library[project_index_kit[x]]= [projects[x]]
## convert the sample sheet to base space format and have different files according the library kit
for key, value in library.items():
lib_kit_file =key.replace(' ', '_')
library_file = sample_sheet_map_basespace(in_file, key, lib_kit_file, value,'Plate96')
if library_file == 'ERROR':
# deleting the sample sheet file
os.remove(in_file)
# Deleting projects related to the shample sheet
for p in range(len( projects)):
my_project = projects [p]
delete_proj=Projects.objects.get(projectName = my_project)
delete_proj.delete()
# delete the run used when uploading the sample sheet
run_p.delete()
# show the error page
return render (
request,'iSkyLIMS_wetlab/error_page.html',
{'content':[ 'The information on the Library kit ', key,
' For the project ', value,
'Does not meet the requirements to perform the conversion to import to Base Space',
'ADVICE', 'Check the sample sheet that was uploaded ']})
else:
bs_file[key] = library_file
results.append([key, bs_file[key]])
## save the project information on database
for p in range(len( projects)):
my_project = projects [p]
my_name = user_name[p]
my_libkit = library_kit[p]
library_kit_id = LibraryKit.objects.get(libraryName__exact = library_kit[p])
update_info_proj=Projects.objects.get(projectName = my_project)
update_info_proj.libraryKit=project_index_kit[p]
update_info_proj.baseSpaceFile=bs_file[project_index_kit[p]]
update_info_proj.LibraryKit_id = library_kit_id
update_info_proj.user_id = User.objects.get(username__exact = user_name[p])
update_info_proj.save()
results.append(['runname', experiment_name])
## save the sample sheet file under tmp/recorded to be processed when run folder was created
subfolder_name=str(run_p.id)
temp_directory = os.path.join(settings.MEDIA_ROOT , wetlab_config.RUN_TEMP_DIRECTORY_RECORDED, subfolder_name)
os.mkdir(temp_directory)
# set group writing permission to the temporary directory
os.chmod(temp_directory, 0o774)
#os.mkdir(os.path.join(settings.MEDIA_ROOT, 'wetlab/tmp/recorded', subfolder_name ))
sample_sheet_copy= os.path.join(temp_directory, 'samplesheet.csv' )
shutil.copy(in_file,sample_sheet_copy)
# set the group write permission to the Sample Sheet File
os.chmod(sample_sheet_copy, 0o664)
# update the sample sheet with the experiment name
if run_name != experiment_name :
update_sample_sheet (in_file, experiment_name)
## update the Experiment name and the state of the run to 'Recorded'
run_p.runName = experiment_name
run_p.index_library = run_index_library_name
run_p.save()
run_p.set_run_state ('Recorded')
return render (request, 'iSkyLIMS_wetlab/CreateNextSeqRun.html', {'completed_form':results})
return render(request, 'iSkyLIMS_wetlab/CreateNextSeqRun.html')
@login_required
def add_library_kit (request):
'''
Description:
The function is called from web, having 2 main parts:
- User form with the information to add a new library
- Result information as response of user submit
Save a new library kit name in database if it is not already defined.
Input:
request # contains the request dictionary sent by django
Variables:
library_kit_information ={} # returned dictionary with the information
to include in the web page
library_kit_objects # contains the object list of the libraryKit model
library_kits = [] # It is a list containing the Library Kits names
new_library_kit_name # contain the new library name enter by user form
library # it is the new LibraryKit object
l_kit # is the iter variable for library_kit_objects
Return:
Return the different information depending on the execution:
-- Error page in case the library already exists.
-- library_kit_information with :
-- ['libraries']
---['new_library_kit'] in case a new library kit was added.
'''
libraries_information ={}
library_kit_information ={}
library_kits = []
library_kit_objects = LibraryKit.objects.all()
if len(library_kit_objects) >0 :
for l_kit in library_kit_objects :
library_kits.append(l_kit.libraryName)
if request.method == 'POST' and request.POST['action'] == 'addNewLibraryKit':
new_library_kit_name = request.POST['newLibraryKit']
## Check that library kit is not already defined in database
if LibraryKit.objects.filter(libraryName__icontains = new_library_kit_name).exists():
return render (request, 'iSkyLIMS_wetlab/error_page.html', {'content':['The Library Kit ', new_library_kit_name, 'is already defined on the system']})
library_kit_information['new_library_kit'] = new_library_kit_name
library_kits.append(new_library_kit_name)
#save the new library on database
library = LibraryKit(libraryName= new_library_kit_name)
library.save()
library_kit_information ['libraries'] = library_kits
return render(request,'iSkyLIMS_wetlab/AddLibraryKit.html',{'list_of_libraries': library_kit_information})
@login_required
def add_index_library (request):
#get the list of the already loaded index library to be displayed
'''
Description:
The function is called from web, having 2 main parts:
- User form with the information to add a new library
- Result information as response of user submit
Input:
request # contains the request dictionary sent by django
Variables:
index_libraries_information # returned dictionary with the information
to include in the web page
index_library_objects # contains the object list of the IndexLibraryKit model
index_library_names # It is a list containing the Index Library Kits names
index_to_store # contains the index (I7/I5) values that are stored in database
the same variable is used for the interaction for library_index
library # it is the new IndexLibraryKit object
library_settings # settings values returned by
l_kit # is the iteration variable for index_library_objects
lib_settings_to_store # is the new IndexLibraryKit object used to store
the information into database
index_library_file # contains the file provider by user in the form
fs_index_lib # file system index library object to store the input file
saved_file # contain the full path name, where the user file have been
stored in the server
Constants:
LIBRARY_KITS_DIRECTORY
LIBRARY_MAXIMUM_SIZE
MEDIA_ROOT
Functions:
in utils.library_kits :
-- check_index_library_file_format(saved_file) # for checking
the number of index in the input file
-- getting_index_library_name(saved_file) # gets the library name
-- get_library_settings(saved_file) # gets the settings values
from the input file
-- get_index_values(saved_file) # gets the index value
Return:
Return the different information depending on the execution:
-- Error page in case of:
-- Uploaded file is bigger than the LIBRARY_MAXIMUM_SIZE value
-- file uploaded does not have the right format
-- the library already exists.
-- library_kit_information with :
-- ['libraries']
---['new_library_kit'] in case a new library kit was added
'''
index_libraries_information ={}
index_library_names = []
index_library_objects = IndexLibraryKit.objects.all()
if len(index_library_objects) > 0 :
for l_index in index_library_objects :
index_library_names.append([l_index.id, l_index.indexLibraryName])
if request.method == 'POST' and request.POST['action'] == 'addNewIndexLibraryFile':
## fetch the file from user form and build the file name including
## the date and time on now to store in database
index_library_file = request.FILES['newIndexLibraryFile']
split_filename=re.search('(.*)(\.\w+$)',index_library_file.name)
f_name = split_filename[1]
f_extension = split_filename[2]
fs_index_lib = FileSystemStorage()
timestr = time.strftime("%Y%m%d-%H%M%S")
## do not need to include the absolute path because django use
## the MEDIA_ROOT variable defined on settings to upload the file
file_name=os.path.join(wetlab_config.LIBRARY_KITS_DIRECTORY , str(f_name + '_' +timestr + f_extension))
filename = fs_index_lib.save(file_name, index_library_file)
saved_file = os.path.join(settings.MEDIA_ROOT, file_name)
## check the file is not bigger that maximum allowed size file for index library
file_stat = os.stat(saved_file)
if file_stat.st_size > int(wetlab_config.LIBRARY_MAXIMUM_SIZE) :
# removing the uploaded file
os.remove(saved_file)
return render (request, 'iSkyLIMS_wetlab/error_page.html',
{'content':['The Index Library Kit file ', split_filename[0],
'exceed from the maximum allowed size']})
uploaded_file_url = fs_index_lib.url(filename)
## check if user file has the right format
if not check_index_library_file_format(saved_file):
## removing the uploaded file
os.remove(saved_file)
return render (request, 'iSkyLIMS_wetlab/error_page.html',
{'content':['The Index Library Kit file', split_filename[0],
'does not have the right format']})
## get the libary name to check if it is already defined
library_name = getting_index_library_name(saved_file)
if library_name == '' :
# removing the uploaded file
os.remove(saved_file)
return render (request, 'iSkyLIMS_wetlab/error_page.html',
{'content':['The Index Library Kit file', split_filename[0],
'does not contain the library name']})
# check if library name is already defined on database
if IndexLibraryKit.objects.filter (indexLibraryName__exact = library_name).exists():
# removing the uploaded file
os.remove(saved_file)
return render (request, 'iSkyLIMS_wetlab/error_page.html',
{'content':['The Library Kit Name ', library_name,
'is already defined on iSkyLIMS']})
# Get the library settings included in the file
library_settings = get_library_settings(saved_file)
# saving library settings into database
if len(library_settings['adapters']) == 1:
adapter_2 = ''
else :
adapter_2 = library_settings['adapters'][1]
lib_settings_to_store = IndexLibraryKit(indexLibraryName = library_settings['name'],
version = library_settings ['version'],
plateExtension = library_settings['plate_extension'] ,
adapter1 = library_settings['adapters'][0],
adapter2 = adapter_2, indexLibraryFile = file_name)
lib_settings_to_store.save()
## get the index name and index bases for the library
library_index = get_index_values(saved_file)
# saving index values into database
for index_7 in library_index['I7'] :
index_name, index_base = index_7
index_to_store = IndexLibraryValues(indexLibraryKit_id = lib_settings_to_store,
indexNumber = 'I7', indexName = index_name,
indexBase = index_base)
index_to_store.save()
for index_5 in library_index['I5'] :
index_name, index_base = index_5
index_to_store = IndexLibraryValues(indexLibraryKit_id = lib_settings_to_store,
indexNumber = 'I5', indexName = index_name,
indexBase = index_base)
index_to_store.save()
index_libraries_information['new_index_library'] = library_settings['name']
index_libraries_information ['index_libraries'] = index_library_names
return render (request, 'iSkyLIMS_wetlab/AddIndexLibrary.html',{'index_library_info': index_libraries_information })
else:
index_libraries_information ['index_libraries'] = index_library_names
return render (request, 'iSkyLIMS_wetlab/AddIndexLibrary.html',{'list_of_index_libraries': index_libraries_information })
@login_required
def search_run (request):
'''
Description:
The function is called from web, having 2 main parts:
- User form with the information to search runs
- Result information can be :
- list of the matched runs
- run information in case that only 1 match is found
Input:
request # contains the request dictionary sent by django
Imports:
Machines and Platform are imported from iSkyLIMS_drylab.models
for filtering runs based on the platform
Functions:
get_information_run() # Collects information about one run
Variables:
User inputs from search options
run_name # string characters to find in the run name
platform_name # platform name filter
run_state # state of the run
start_date # filter of starting date of the runs
end_date # filter for the end of the runs
available_platforms # contains the list of platform defined in
# iSkyLIMS.models.Platform
machine_list # list of machines to filter on the matches runs
platforms # contain the object from iSkyLIMS.models.Platform
platform_name # has the platform get from user form
runs_found # runProcess object that contains the result query
# it is updated with the user form conditions
r_data_display # contains the information to display about the run
run_list # contains the run list that mathches te user conditions
Return:
Return the different information depending on the execution:
-- Error page in case no run is founded on the matching conditions.
-- SearchRun.html is returned with one of the following information :
-- r_data_display # in case that only one run is matched
---run_list # in case several run matches the user conditions.
'''
# check user privileges
if request.user.is_authenticated:
try:
groups = Group.objects.get(name=wetlab_config.WETLAB_MANAGER)
if groups not in request.user.groups.all():
allowed_all_runs = False
#return render (request,'iSkyLIMS_wetlab/error_page.html', {'content':['You do have the enough privileges to see this page ','Contact with your administrator .']})
else:
allowed_all_runs = True
except:
return render (request,'iSkyLIMS_wetlab/error_page.html', {'content':['You do have the enough privileges to see this page ','Contact with your administrator .']})
else:
#redirect to login webpage
return redirect ('/accounts/login')
#############################################################
## Search for runs that fullfil the input values
#############################################################
if request.method == 'POST' and (request.POST['action'] == 'runsearch'):
run_name = request.POST['runname']
start_date = request.POST['startdate']
end_date = request.POST['enddate']
run_state = request.POST['runstate']
platform_name = request.POST['platform']
# check that some values are in the request if not return the form
if run_name == '' and start_date == '' and end_date == '' and run_state == '' and platform_name == '' :
return render(request, 'iSkyLIMS_wetlab/SearchRun.html')
### check the right format of start and end date
if start_date != '':
try:
datetime.datetime.strptime(start_date, '%Y-%m-%d')
except:
return render (request,'iSkyLIMS_wetlab/error_page.html',
{'content':['The format for the "Start Date Search" Field is incorrect ',
'ADVICE:', 'Use the format (DD-MM-YYYY)']})
if end_date != '':
try:
datetime.datetime.strptime(end_date, '%Y-%m-%d')
except:
return render (request,'iSkyLIMS_wetlab/error_page.html',
{'content':['The format for the "End Date Search" Field is incorrect ',
'ADVICE:', 'Use the format (DD-MM-YYYY)']})
### Get all the available runs to start the filtering
if allowed_all_runs :
runs_found=RunProcess.objects.all().order_by('runName')
else:
user_projects = Projects.objects.filter(user_id__exact = request.user.id)
run_list =[]
for user_project in user_projects :
run_list.append(user_project.runprocess_id.id)
if RunProcess.objects.filter(pk__in = run_list).exists():
runs_found = RunProcess.objects.filter(pk__in = run_list)
else:
return render (request,'iSkyLIMS_wetlab/error_page.html',
{'content':['There are not run where ',
request.user.username , 'was involved' ]})
### Get runs when run name is not empty
if run_name !='':
if (RunProcess.objects.filter(runName__exact =run_name).exists()):
run_name_found=RunProcess.objects.filter(runName__exact =run_name)
if (len(run_name_found)>1):
return render (request,'iSkyLIMS_wetlab/error_page.html', {'content':['Too many matches found when searching for the run name ', run_name ,
'ADVICE:', 'Select additional filter to find the run that you are looking for']})
r_data_display= get_information_run(run_name_found[0])
return render(request, 'iSkyLIMS_wetlab/SearchRun.html', {'display_one_run': r_data_display })
if (runs_found.filter(runName__icontains =run_name).exists()):
runs_found=runs_found.filter(runName__icontains =run_name).order_by('runName')
else:
return render (request,'iSkyLIMS_wetlab/error_page.html',
{'content':['No matches have been found for the run name ',
run_name ]})
if platform_name != '' :
from iSkyLIMS_drylab.models import Machines, Platform
if Machines.objects.filter(platformID__exact = Platform.objects.get(platformName__exact = platform_name)).exists() :
machine_list = Machines.objects.filter(platformID__exact = Platform.objects.get(platformName__exact = platform_name))
if runs_found.filter(sequencerModel__in = machine_list).exists() :
runs_found = runs_found.filter(sequencerModel__in = machine_list)
else:
return render (request,'iSkyLIMS_wetlab/error_page.html',
{'content':['No matches have been found for the platform ',
platform_name ]})
else:
return render (request,'iSkyLIMS_wetlab/error_page.html',
{'content':['No matches have been found for the platform ', platform_name ]})
### Check if state is not empty
if run_state != '':
s_state = RunStates.objects.get(runStateName__exact = run_state)
if runs_found.filter(state__runStateName__exact = s_state).exists():
runs_found = runs_found.filter(state__runStateName__exact = s_state).order_by('runName')
else :
return render (request,'iSkyLIMS_wetlab/error_page.html', {'content':['No matches have been found for the run name ', run_name ,
'and the state', run_state ]})
### Check if start_date is not empty
if start_date !='' and end_date != '':
if runs_found.filter(run_date__range=(start_date, end_date)).exists():
runs_found = runs_found.filter(run_date__range=(start_date, end_date))
else:
return render (request,'iSkyLIMS_wetlab/error_page.html', {'content':['There are no runs containing ', run_name,
' created between ', start_date, 'and the ', end_date]})
if start_date !='' and end_date == '':
if runs_found.filter(run_date__gte = start_date).exists():
runs_found = runs_found.filter(run_date__gte = start_date)
else:
return render (request,'iSkyLIMS_wetlab/error_page.html', {'content':['There are no Runs containing ', run_name,
' starting from', start_date]})
if start_date =='' and end_date != '':
if runs_found.filter(run_date__lte = end_date).exists():
runs_found = runs_found.filter(run_date__lte = end_date)
else:
return render (request,'iSkyLIMS_wetlab/error_page.html', {'content':['There are no Runs containing ', run_name,
' finish before ', end_date]})
#If only 1 run mathes the user conditions, then get the project information
if (len(runs_found)== 1) :
r_data_display= get_information_run(runs_found[0])
#r_data_display= get_information_run(runs_found[0],runs_found[0].id)
return render(request, 'iSkyLIMS_wetlab/SearchRun.html', {'display_one_run': r_data_display })
else:
## collect the list of run that matches the run date
run_list=[]
for i in range(len(runs_found)):
run_list.append([runs_found[i],runs_found[i].id])
return render(request, 'iSkyLIMS_wetlab/SearchRun.html', {'display_run_list': run_list })
else:
available_platforms = []
available_machines = []
from iSkyLIMS_drylab.models import Platform, Machines
available_states = []
run_states = RunStates.objects.all()
for state in run_states :
available_states.append(state.runStateName)
platforms = Platform.objects.all()
for platform in platforms :
available_platforms.append(platform.get_platform_name())
machines = Machines.objects.all()
for machine in machines :
available_machines.append(machine.get_machine_name())
return render(request, 'iSkyLIMS_wetlab/SearchRun.html', {'platforms': available_platforms,'machines':available_machines,'run_states':available_states})
@login_required
def search_project (request):
'''
Description:
The function is called from web, having 2 main parts:
- User form with the information to search projects
- Result information can be :
- list of the matched projects
- project information in case that only 1 match is found
Input:
request # contains the request dictionary sent by django
Imports:
Machines and Platform are imported from iSkyLIMS_drylab.models
for filtering runs based on the platform
Variables:
User inputs from search options
project_name # string characters to find in the project name
platform_name # platform name filter
start_date # filter of starting date of the project
end_date # filter for the end of the project
available_platforms # contains the list of platform defined in
# iSkyLIMS.models.Platform
machine_list # list of machines to filter on the matches runs
platforms # contain the object from iSkyLIMS.models.Platform
platform_name # has the platform get from user form
project_found # Projects object that contains the result query
# it is updated with the user form conditions
r_data_display # contains the information to display about the project
run_list # contains the project list that mathches te user conditions
run_process_ids # contains the runs ids which have the platflorm
value enter by user
Return:
Return the different information depending on the execution:
-- Error page in case no run is founded on the matching conditions.
-- SearchRun.html is returned with one of the following information :
-- r_data_display # in case that only one run is matched
---run_list # in case several run matches the user conditions.
'''
if request.method=='POST' and (request.POST['action']=='searchproject'):
project_name=request.POST['projectname']
start_date=request.POST['startdate']
end_date=request.POST['enddate']
user_name = request.POST['username']
platform_name = request.POST['platform']
run_state = request.POST['runstate']
run_process_ids = []
# check that some values are in the request if not return the form
if project_name == '' and start_date == '' and end_date == '' and user_name =='' and platform_name == '':
available_platforms = get_available_platform()
available_states = get_available_run_state()
return render(request, 'iSkyLIMS_wetlab/SearchProject.html', {'platforms': available_platforms,'run_states':available_states})
if user_name !='' and len(user_name) <5 :
return render (request,'iSkyLIMS_wetlab/error_page.html',
{'content':['The user name must contains at least 5 caracters ',
'ADVICE:', 'write the full user name to get a better match']})
### check the right format of start and end date
if start_date != '':
try:
datetime.datetime.strptime(start_date, '%Y-%m-%d')
except:
return render (request,'iSkyLIMS_wetlab/error_page.html',
{'content':['The format for the "Start Date Search" Field is incorrect ',
'ADVICE:', 'Use the format (DD-MM-YYYY)']})
if end_date != '':
try:
datetime.datetime.strptime(end_date, '%Y-%m-%d')
except:
return render (request,'iSkyLIMS_wetlab/error_page.html',
{'content':['The format for the "End Date Search" Field is incorrect ',
'ADVICE:', 'Use the format (DD-MM-YYYY)']})
### Get projects when project name is not empty
if project_name != '' :
if Projects.objects.filter(projectName__exact = project_name).exists():
project_id = Projects.objects.get (projectName__exact = project_name).id
project_found_id = Projects.objects.get(pk=project_id)
p_data_display = get_information_project(project_found_id, request)
return render(request, 'iSkyLIMS_wetlab/SearchProject.html',
{'display_one_project': p_data_display })
if Projects.objects.filter (projectName__contains = project_name).exists():
projects_found = Projects.objects.filter (projectName__contains = project_name)
else:
return render (request,'iSkyLIMS_wetlab/error_page.html',
{'content':['No Project found with the string , ', project_name ]})
### if there is no project name, then get all which will be filtered by other conditions set by user
#
if project_name == '':
projects_found = Projects.objects.all()
if platform_name != '':
from iSkyLIMS_drylab.models import Machines, Platform
if Machines.objects.filter(platformID__platformName__exact = platform_name).exists() :
machine_list = Machines.objects.filter(platformID__platformName__exact = platform_name)
if RunProcess.objects.filter(sequencerModel__in = machine_list).exists() :
runs_found = RunProcess.objects.filter(sequencerModel__in = machine_list)
for run in runs_found :
run_process_ids.append(run.id)
if projects_found.filter(runprocess_id__in = run_process_ids).exists():
projects_found = projects_found.filter(runprocess_id__in = run_process_ids)
else:
return render (request,'iSkyLIMS_wetlab/error_page.html',
{'content':['No matches have been found for the platform ',
platform_name ]})
else:
return render (request,'iSkyLIMS_wetlab/error_page.html',
{'content':['No matches have been found for the platform ',
platform_name ]})
else:
return render (request,'iSkyLIMS_wetlab/error_page.html',
{'content':['No matches have been found for the platform ', platform_name ]})
# check if user name is not empty
if user_name != '':
if User.objects.filter(username__icontains = user_name).exists():
r_name_id = User.objects.get(username__icontains = user_name).id
if projects_found.filter(user_id__exact =r_name_id).exists():
projects_found = projects_found.filter(user_id__exact =r_name_id)
else:
return render (request,'iSkyLIMS_wetlab/error_page.html', {'content':['The Project found does not belong to the user, ', user_name ]})
else:
return render (request,'iSkyLIMS_wetlab/error_page.html', {'content':['The Project found does not belong to the user, ', user_name ]})
if (run_state !='' ):
if projects_found.filter(runprocess_id__state__runStateName__exact = run_state):
projects_found = projects_found.filter(runprocess_id__state__runStateName__exact = run_state)
else :
return render (request,'iSkyLIMS_wetlab/error_page.html', {'content':['There ane not Projects containing ', project_name,
'in state', project_state ]})
if start_date !='' and end_date != '':
if projects_found.filter(project_run_date__range=(start_date, end_date)).exists():
projects_found = projects_found.filter(project_run_date__range=(start_date, end_date))
else:
return render (request,'iSkyLIMS_wetlab/error_page.html', {'content':['There are no Projects containing ', project_name,
' created between ', start_date, 'and the ', end_date]})
if start_date !='' and end_date == '':
if projects_found.filter(project_run_date__gte = start_date).exists():
projects_found = projects_found.filter(project_run_date__gte = start_date)
#
else:
return render (request,'iSkyLIMS_wetlab/error_page.html', {'content':['There are no Projects containing ', project_name,
' starting from', start_date]})
if start_date =='' and end_date != '':
if projects_found.filter(project_run_date__lte = end_date).exists():
projects_found = projects_found.filter(project_run_date__lte = end_date)
else:
return render (request,'iSkyLIMS_wetlab/error_page.html', {'content':['There are no Projects containing ', project_name,
' finish before ', end_date]})
#If only 1 project mathes the user conditions, then get the project information
if len (projects_found) == 1:
project_id = projects_found[0].id
project_found_id = Projects.objects.get(pk=project_id)
p_data_display = get_information_project(project_found_id, request)
return render(request, 'iSkyLIMS_wetlab/SearchProject.html', {'display_one_project': p_data_display })
else :
# Display a list with all projects that matches the conditions
project_list_dict = {}
project_list = []
for project in projects_found :
p_name = project.get_project_name()
p_name_id = project.id
project_list.append([p_name, p_name_id])
project_list_dict ['projects'] = project_list
return render(request, 'iSkyLIMS_wetlab/SearchProject.html', {'display_project_list': project_list_dict })
else:
available_platforms = get_available_platform()
available_states = get_available_run_state()
return render(request, 'iSkyLIMS_wetlab/SearchProject.html', {'platforms': available_platforms,'run_states':available_states})
@login_required
def search_sample (request):
'''
Description:
The function is called from web, having 2 main parts:
- User form with the information to search samples
- Result information can be :
- list of the matched samples
- sample information in case that only 1 match is found
Input:
request # contains the request dictionary sent by django
Variables:
User inputs from search options
sample_name # string characters to find in the project name
start_date # filter of starting date of the project
end_date # filter for the end of the project
user_name # name of user owner of the sample
sample_found # Sample object that contains the result query
# it is updated with the user form conditions
project_id_list # contains the a list of projects objects
owner of the enter used name for filtering
the previous matched samples
sample_data_information # Contains all the sample information
to be displayed on the web page
sample_list # contains the sample list that mathches
the user conditions
Return:
Return the different information depending on the execution:
-- Error page in case no sample is founded on the matching conditions.
-- SearchSample.html is returned with one of the following information :
-- sample_data_information # in case that only one run is matched
---sample_list # in case several run matches the user conditions.
'''
if request.method=='POST' and (request.POST['action']=='searchsample'):
sample_name=request.POST['samplename']
start_date=request.POST['startdate']
end_date=request.POST['enddate']
user_name = request.POST['username']
# check that some values are in the request if not return the form
if user_name == '' and start_date == '' and end_date == '' and sample_name =='':
return render(request, 'iSkyLIMS_wetlab/SearchNextSample.html')
if user_name !='' and len(user_name) <5 :
return render (request,'iSkyLIMS_wetlab/error_page.html',
{'content':['The user name must contains at least 5 caracters ',
'ADVICE:', 'write the full user name to get a better match']})
### check the right format of start and end date
if start_date != '':
try:
datetime.datetime.strptime(start_date, '%Y-%m-%d')
except:
return render (request,'iSkyLIMS_wetlab/error_page.html',
{'content':['The format for the "Start Date Search" Field is incorrect ',
'ADVICE:', 'Use the format (DD-MM-YYYY)']})
if end_date != '':
try:
datetime.datetime.strptime(end_date, '%Y-%m-%d')
except:
return render (request,'iSkyLIMS_wetlab/error_page.html',
{'content':['The format for the "End Date Search" Field is incorrect ',
'ADVICE:', 'Use the format (DD-MM-YYYY)']})
### Get projects when sample name is not empty
if sample_name != '' :
if SamplesInProject.objects.filter(sampleName__exact = sample_name).exists():
sample_found = SamplesInProject.objects.filter(sampleName__exact = sample_name)
if len(sample_found) == 1:
# get information from the sample found
########################################
sample_data_information = get_info_sample (sample_found[0])
return render(request, 'iSkyLIMS_wetlab/SearchSample.html',{'display_one_sample': sample_data_information })
elif SamplesInProject.objects.filter(sampleName__contains = sample_name).exists():
sample_found = SamplesInProject.objects.filter(sampleName__contains = sample_name)
#
else:
return render (request,'iSkyLIMS_wetlab/error_page.html',
{'content':['No sample found with the string , ', sample_name ]})
### if there is no project name, then get all which will be filtered by other conditions set by user
#
else :
sample_found = SamplesInProject.objects.all()
# Check the start and end date
if start_date !='' and end_date != '':
if sample_found.filter(generated_at__range=(start_date, end_date)).exists():
sample_found = sample_found.filter(generated_at__range=(start_date, end_date))
else:
return render (request,'iSkyLIMS_wetlab/error_page.html',
{'content':['There are no Projects containing ', sample_name,
' created between ', start_date, 'and the ', end_date]})
if start_date !='' and end_date == '':
if sample_found.filter(generated_at__gte = start_date).exists():
sample_found = sample_found.filter(generated_at__gte = start_date)
else:
return render (request,'iSkyLIMS_wetlab/error_page.html',
{'content':['There are no Projects containing ', sample_name,
' starting from', start_date]})
if start_date =='' and end_date != '':
if sample_found.filter(generated_at__lte = end_date).exists():
sample_found = sample_found.filter(generated_at__lte = end_date)
else:
return render (request,'iSkyLIMS_wetlab/error_page.html',
{'content':['There are no Projects containing ', sample_name,
' finish before ', end_date]})
# check if user name is not empty
if user_name != '':
#
if User.objects.filter(username__contains = user_name).exists():
users = User.objects.filter (username__contains = user_name)
if len(users) == 1:
user_id= users[0].id