-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun.py
1640 lines (1511 loc) · 59.1 KB
/
run.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 xml.dom.minidom
import socket
import subprocess
import os
import re
import sys
import pipelineparams as params
import gnomex
from states import States
from emailer import Emailer
from simultaneousjobrunner import SimultaneousJobRunner
connection = gnomex.GNomExConnection().GnConnect(params.db_user,params.db_password)
def EraseCommas(s):
"""Removes all commas in string s."""
if s:
return ''.join(s.split(','))
else:
return s
class Run(Emailer,SimultaneousJobRunner):
"""Information about one sequencing run including its current
state in the pipeline."""
def __init__( self, id, full_path_of_run_dir, state=None ):
self.id = id
self.dirname = full_path_of_run_dir
if state is None:
self.state = States.new
else:
self.state = state
self.runtype = None
self.sample_sheet = None
self.IsPaired = None
# List of full pathnames of all data files produced by this run, following rename.
self.datafiles=[]
self.output_dirs=[]
# List of Lane objects.
self.lanes = []
SimultaneousJobRunner.__init__( self, verbose=True )
self.InitializeCoreFacility()
def __cmp__( self, other ):
"""Sort runs by decreasing state, increasing run start date."""
if self.state > other.state:
return -1
elif self.state < other.state:
return 1
elif self.id < other.id:
return -1
else:
return 1
def Query( self, query ):
"""
Runs a SQL query against GNomEx, and retuns a cursor from
which the results can be retrieved.
"""
global connection
c = connection.cursor()
c.execute(query)
return c
def InitializeCoreFacility( self ):
"""
InitializeCoreFacility identifies which core facility
started this run.
"""
self.corefacilityname = None
query="""select distinct facilityname
from corefacility
join flowcell on flowcell.idcorefacility = corefacility.idcorefacility
join flowcellchannel on flowcellchannel.idflowcell = flowcell.idflowcell
and flowcellchannel.filename = '%s';""" % self.id
recs=self.Query(query).fetchall()
try:
self.corefacilityname = recs[0][0]
except:
self.corefacilityname = 'Unknown'
#self.Log("Run %s came from core facility '%s'." % (self.id,self.corefacilityname))
def FromAddr( self ):
"""
Returns from address for emailing purposes.
"""
# Unix account under which PipelineMgr.py runs.
username = os.environ['LOGNAME']
return username + "@" + socket.getfqdn()
def Notify( self, subject, message ):
to_addr = params.notify_addresses
self.send_msg( self.FromAddr(), to_addr, subject, message, attachments=[] )
def NotifyError( self ):
"""Notify someone that this run has entered the error state."""
to_addr = params.notify_addresses
subject = "HiSeq Pipeline Notification"
message = "Run %s (%s) just entered error state." % (self.id,self.dirname)
self.Log(["Notifying",to_addr,":",message])
try:
self.send_msg( self.FromAddr(), to_addr, subject, message, attachments=[] )
return True
except:
self.Log(["PROBLEM! Can't notify",to_addr,"that",message])
return False
def CheckRegisteredSilent( self ):
"""Boolean function to test if run folder actually registered in GNomEx."""
g = gnomex.GNomExConnection()
connection = g.GnConnect(params.db_user,params.db_password)
c = connection.cursor()
c.execute("select count(*) from flowcellchannel where filename = %s", self.id)
results = c.fetchall()
numlanes = results[0][0]
# 2013/07/15: Flow cells can now either have 8 lanes (HiSeq2000)
# or 1 lane (HiSeq2500). Permit either of these styles of
# flow cell here. Brett Milash.
if numlanes == 8 or numlanes == 1:
return True
else:
# 2013/10/02 - If run is complete and flow cell still
# not registered, send an urgent email.
if self.CheckTransferComplete(notify=False):
subject = "HiSeq Pipeline Problem! (%s)" % self.id
message = "The sequencing run %s is done, but the run folder has not been entered in GNomEx.\n" % self.id
message += "The pipeline can not start until the flow cell has been entered into GNomEx.\n"
self.NotifyLabStaff( subject, message )
return False
def NotifyLabStaff( self, subject, message ):
# Notify the lab folks to correct the problem.
to_addr = params.lab_staff_addresses[self.corefacilityname]
self.send_msg( self.FromAddr(), to_addr, subject, message )
def CheckRegisteredVerbose( self ):
if self.CheckRegisteredSilent():
return True
else:
# Complain to lab staff, and log it.
self.Log(["PROBLEM! Run directory",self.id,"not registered correctly in GNomEx."])
# Notify the lab folks to correct the problem.
subject = "HiSeq Pipeline Problem! (%s)" % self.id
message = "The HiSeq run folder %s has not been entered in GNomEx.\n" % self.id
message += "Please check GNomEx to make sure the run folder was entered correctly.\n"
message += "Thanks, and have a nice day!\n"
self.NotifyLabStaff( subject, message )
return False
def CheckTransferComplete(self,notify=True):
"""Checks if data transfer from sequencer is done. Illumina
RTA 1.12 creates a data transfer complete file for each read
in the run. This function checks if the last file for the
run is present."""
configfile = os.path.join(self.dirname, "RunInfo.xml")
doc = xml.dom.minidom.parse(configfile)
numreads=len(doc.getElementsByTagName("Read"))
done_file=os.path.join(self.dirname,"Basecalling_Netcopy_complete_Read%d.txt"%numreads)
print(done_file)
if os.path.exists(done_file):
self.Log(["Run", self.id, "complete-file",done_file,"exists."])
if notify:
self.NotifyStarting()
return True
else:
self.Log(["Run", self.id, "complete-file",done_file,"doesn't exist."])
return False
def CheckSingleIndexLength( self ):
if self.sample_sheet is None:
# Try to find the sample sheet. It should exist.
self.sample_sheet = self.SampleSheetName()
# Open, read, and parse the sample sheet. The Index column lists the bar codes. Determine if they are all
# the same length or not. If they are, return True, else False.
ifs = open(self.sample_sheet)
lines = ifs.readlines()
ifs.close()
lengths=set()
for line in lines[1:]:
f = line.split(',')
barcode = f[4]
lengths.add(len(barcode))
# Count the number of elements in set lengths.
numlengths=0
while lengths:
lengths.pop()
numlengths+=1
if numlengths == 1:
return True
return False
def MakeSampleSheet( self ):
self.sample_sheet = self.CreateSampleSheet()
if self.sample_sheet is None:
self.Log(["PROBLEM! Can't locate or create sample sheet .csv file in", self.dirname, "for barcoded run", self.id] )
return False
return True
def ReadLengths( self ):
"""
Returns a tuple with the lengths of each read in the run
read from the RunInfo.xml file.
"""
lengths=[]
doc = xml.dom.minidom.parse(os.path.join(self.dirname,"RunInfo.xml"))
reads=doc.getElementsByTagName("Read")
for read in reads:
lengths.append(int(read.getAttribute("NumCycles")))
return tuple(lengths)
def FlowCellVersion( self ):
"""Returns run's flow cell version from the
runParameters.xml file."""
# Look in the runParameters.xml document for the Flowcell element to determine flow cell type.
doc = xml.dom.minidom.parse(os.path.join(self.dirname,"runParameters.xml"))
e=doc.getElementsByTagName("Flowcell")[0]
flowcell=e.firstChild.nodeValue
return flowcell
def BclConvert( self, sample_sheet=None, output_dir=None, use_bases_mask=None, compress_bcls=True, mismatches=1 ):
"""Converts the bcl files into compressed Fastq."""
# Generate a sample sheet if it is not already present.
if sample_sheet:
self.sample_sheet = sample_sheet
elif not self.sample_sheet:
self.sample_sheet = self.SampleSheetName()
if self.sample_sheet is None:
self.Log(["PROBLEM! Can't locate or create sample sheet .csv file in", self.dirname, "for barcoded run", self.id] )
return False
flowcell = self.FlowCellVersion()
print(self.FlowCellVersion())
if flowcell == "HiSeq Flow Cell v3":
# V3 flowcell processing.
# Run the configureBclToFastq.pl scripts.
self.Log(["Running configureBclToFastq on run", self.id])
child_dir=self.dirname
if not output_dir:
output_dir = os.path.join( self.dirname, "Unaligned" )
child_stdout=open(os.path.join(child_dir,"bcltofastq.out"),'w')
child_stderr=open(os.path.join(child_dir,"bcltofastq.err"),'w')
child_args=[os.path.join(params.casava_dir,"configureBclToFastq.pl"),
"--input-dir",os.path.join(self.dirname,"Data","Intensities","BaseCalls"),
"--positions-format",".clocs",
"--sample-sheet",self.sample_sheet,
"--output-dir",output_dir,
"--mismatches",`mismatches`,
]
if use_bases_mask:
child_args.append( "--use-bases-mask" )
child_args.append( use_bases_mask )
p = subprocess.Popen(args=child_args,cwd=child_dir,stdout=child_stdout,stderr=child_stderr)
retval = p.wait()
child_stdout.close()
child_stderr.close()
else:
# V4 and other types of flowcell processing.
# Run the configureBclToFastq.pl scripts.
self.Log(["Running configureBclToFastq on run", self.id])
#basecallsdir=$rundir/Data/Intensities/BaseCalls
#configureBclToFastq.pl --input-dir=$basecallsdir \
# --output-dir=$rundir/Unaligned \
# --sample-sheet=$basecallsdir/created_samplesheet.csv \
# --positions-format=.clocs \
# --mismatches 1 \
# --no-eamss
child_dir=self.dirname
if not output_dir:
output_dir = os.path.join( self.dirname, "Unaligned" )
child_stdout=open(os.path.join(child_dir,"bcltofastq.out"),'w')
child_stderr=open(os.path.join(child_dir,"bcltofastq.err"),'w')
child_args=[os.path.join(params.bcl2fastq_dir,"configureBclToFastq.pl"),
"--input-dir",os.path.join(self.dirname,"Data","Intensities","BaseCalls"),
"--positions-format",".clocs",
"--sample-sheet",self.sample_sheet,
"--output-dir",output_dir,
"--mismatches",`mismatches`,
"--ignore-missing-bcl",
"--ignore-missing-stats",
"--no-eamss",
]
# Determine the use_bases_mask. Even during a simple
# BCL conversion, if the bar code read length is longer
# than required, then Illumina's method for guessing the
# mask will fail. Brett Milash, 8/24/2016.
if not use_bases_mask:
barcode_len,is_dual_index=self.DetermineBarcodeLength()
use_bases_mask = self.UseBasesMask(barcode_len,is_dual_index)
self.Log(["Using use_bases_mask:",use_bases_mask])
if use_bases_mask:
child_args.append( "--use-bases-mask" )
child_args.append( use_bases_mask )
print(" ".join(child_args))
p = subprocess.Popen(args=child_args,cwd=child_dir,stdout=child_stdout,stderr=child_stderr)
retval = p.wait()
child_stdout.close()
child_stderr.close()
# If configure successful...
if retval == 0:
# Run make in the Unaligned directory.
self.Log(["Running make (to convert bcl files) on run",self.id])
child_dir = output_dir
child_stdout=open(os.path.join(child_dir,"make.out"),'w')
child_stderr=open(os.path.join(child_dir,"make.err"),'w')
child_args=["/usr/bin/make","-j","8"]
p = subprocess.Popen(args=child_args,cwd=child_dir,stdout=child_stdout,stderr=child_stderr)
retval = p.wait()
child_stdout.close()
child_stderr.close()
if retval == 0 and compress_bcls == True:
# Compress .bcl files.
self.CompressFiles("*.bcl")
return retval == 0
def CheckMultiplex( self ):
"""Checks if a run contains any barcoded samples or not. Counts
the number of samples for each lane on the flow cell, and returns
true if any lane has more than one sample."""
g = gnomex.GNomExConnection()
connection = g.GnConnect(params.db_user,params.db_password,asdict=True)
c = connection.cursor()
try:
query="""select count(*) n
from flowcellchannel
join sequencelane on sequencelane.idflowcellchannel = flowcellchannel.idflowcellchannel
join sample on sample.idsample = sequencelane.idsample
where flowcellchannel.filename = '%s'
group by flowcellchannel.filename, flowcellchannel.number""" % self.id
c.execute(query)
except pymssql.OperationError:
print query
raise
results = c.fetchall()
connection.close()
for rec in results:
if rec['n'] > 1:
self.Log("Run %s is barcoded."%self.id)
return True
self.Log("Run %s is not barcoded."%self.id)
return False
def FindBarcodedLanes( self ):
"""Determines which lanes on the flow cell contain barcoded samples. Returns a string
with the lane numbers, for example "12348"."""
g = gnomex.GNomExConnection()
connection = g.GnConnect(params.db_user,params.db_password)
c = connection.cursor()
try:
query="""select flowcellchannel.number, count(*) n
from flowcellchannel
join sequencelane on sequencelane.idflowcellchannel = flowcellchannel.idflowcellchannel
join sample on sample.idsample = sequencelane.idsample
where flowcellchannel.filename = '%s'
group by flowcellchannel.filename, flowcellchannel.number
order by flowcellchannel.filename, flowcellchannel.number"""%self.id
c.execute(query)
except pymssql.OperationError:
print query
raise
results = c.fetchall()
connection.close()
barcoded_lanes = ''
for rec in results:
lane = rec[0]
numsamples=rec[1]
if numsamples > 1:
barcoded_lanes += str(lane)
return barcoded_lanes
def LocateSampleSheet( self ):
"""Finds sample sheet file, a comma-delimited file (.csv) in the run directory. Returns
None if not found."""
fnames = os.listdir(self.dirname)
for file in os.listdir(self.dirname):
if file[-4:] == ".csv":
return os.path.join(self.dirname,file)
return None
def WriteSampleSheetRow( self, flowcell_barcode, lane, sampleid, genome, sample_barcode, fname, lname, rnum, ofs ):
# Regular row. Write it to the file.
row = [ flowcell_barcode,`lane`,sampleid,EraseCommas(genome) or 'None',sample_barcode or '',EraseCommas(fname+' '+lname),'N','RI','Sandy',rnum ]
ofs.write(','.join(row)+'\n')
def CreateSampleSheet(self):
"""Creates sample sheet for multiplexed flow cell, and writes
it to the BaseCalls directory within the run directory.
Returns full path of sample sheet file name.
Changes for version 1.8 of CASAVA:
Added SampleProject column
altered other column names
write file to BaseCalls directory
4/3/2012: now permitting samples without barcodes. These samples will
have an Null values for the sample.barcode field, and no barcode
processing will happen for that lane.
5/16/2012: if only single sample is in a lane, the barcode for
that sample will be ignored, and it will be treated as if a single
non-barcoded sample is there. Doing this because sequence quality
for single barcodes is poor, and many clients just want all the
reads anyway.
11/28/2012: External customer Amplicon Express is submitting libraries
with 8-base custom barcodes. They submit libraries with any number of
samples ready for sequencing, but don't want to divulge which samples
are present. If registered user for Amplicon gets a lane, then the master
barcode sheet for Amplicon will be subsituted for that lane, so their
master spreadsheet will get used for every library they submit.
11/12/2013: Updated to handle paired bar codes.
03/06/2014: Updated to handle rapid runs. These runs are
registered in GnomEx as a single lane, but actually have 2
lanes of data (numbered 1 and 2). GNomEx does not support
this, so the pipeline is going to fake it by detecting these
flow cells, and adding a second lane (identical to the first)
in the sample sheet.
"""
# Generate sample sheet name. If it already exists just
# return its name. Doing this to make it easier to override
# the automatic sample sheet creation. Brett Milash, 10/11/2013.
samplesheet_fname = self.SampleSheetName()
if os.path.exists(samplesheet_fname):
return samplesheet_fname
# Select lanes from flow cell that are bar coded.
g = gnomex.GNomExConnection()
connection = g.GnConnect(params.db_user,params.db_password,asdict=False)
c = connection.cursor()
try:
query = """select flowcell.barcode,
flowcellchannel.number,
sample.number,
genomebuild.genomebuildname,
sample.barcodesequence,
appuser.firstname,
appuser.lastname,
request.number,
sample.barcodesequenceb
from flowcell
join flowcellchannel on flowcellchannel.idflowcell=flowcell.idflowcell
join sequencelane on sequencelane.idflowcellchannel =
flowcellchannel.idflowcellchannel
join sample on sequencelane.idsample = sample.idsample
left outer join genomebuild on sequencelane.idgenomebuildalignto =
genomebuild.idgenomebuild
join request on sequencelane.idrequest = request.idrequest
join appuser on request.idappuser = appuser.idappuser
where flowcellchannel.filename = '%s'
order by flowcellchannel.number, sample.number;""" % self.id
c.execute(query)
except pymssql.OperationError:
print query
raise
results = c.fetchall()
# Open file
ofs = open(samplesheet_fname,'w')
# Write header.
header = ['FCID','Lane','SampleID','SampleRef','Index','Description','Control','Recipe','Operator','SampleProject']
ofs.write(','.join(header)+'\n')
# Count how many samples are in each lane.
sample_count = {}
for rec in results:
lane = rec[1]
try:
sample_count[lane]+=1
except KeyError:
sample_count[lane] = 1
# Write the results.
for rec in results:
# Write row.
flowcell_barcode = rec[0]
lane = rec[1]
sampleid=rec[2]
genome=rec[3]
sample_barcode=rec[4]
sample_barcode_b=rec[8]
if sample_barcode_b is not None:
sample_barcode = sample_barcode.strip()+'-'+sample_barcode_b.strip()
elif type(sample_barcode) == type(''):
sample_barcode = sample_barcode.strip()
fname=rec[5]
lname=rec[6]
rnum=rec[7]
# If lane has a single sample, don't write its
# barcode.
if sample_count[lane] == 1:
sample_barcode = ''
self.WriteSampleSheetRow( flowcell_barcode, lane, sampleid, genome, sample_barcode, fname, lname, rnum, ofs )
# Check if this is a rapid run. This will be the case
# if the flow cell is registered as a single lane, but there
# will be two lanes of data for it.
if len(sample_count.keys())==1 and \
int(sample_count.keys()[0]) == 1 and \
os.path.exists(os.path.join(self.dirname,'Data','Intensities','L002')):
# Its a rapid run.
self.Log(["Run", self.id, "is a rapid run. Duplicating rows for lane 2 in sample sheet",samplesheet_fname,"."])
for rec in results:
# Write row.
flowcell_barcode = rec[0]
lane = rec[1]
sampleid=rec[2]
genome=rec[3]
sample_barcode=rec[4]
sample_barcode_b=rec[8]
if sample_barcode_b is not None:
sample_barcode = sample_barcode.strip()+'-'+sample_barcode_b.strip()
elif type(sample_barcode) == type(''):
sample_barcode = sample_barcode.strip()
fname=rec[5]
lname=rec[6]
rnum=rec[7]
# If lane has a single sample, don't write its
# barcode.
if sample_count[lane] == 1:
sample_barcode = ''
self.WriteSampleSheetRow( flowcell_barcode, 2, sampleid, genome, sample_barcode, fname, lname, rnum, ofs )
# Close file.
ofs.close()
# Close database.
connection.close()
# Return file name.
return samplesheet_fname
def DeMultiplex( self ):
"""Performs barcode processing."""
# Locate sample sheet file, a comma-delimited file (.csv) in the run directory.
sample_sheet = self.LocateSampleSheet()
if sample_sheet is None:
sample_sheet = self.CreateSampleSheet()
if sample_sheet is None:
self.Log(["PROBLEM! Can't locate or create sample sheet .csv file in", self.dirname, "for barcoded run", self.id] )
return False
# Identify which lanes contain barcoded samples.
barcoded_lanes = self.FindBarcodedLanes()
# Create config template file.
config_template = os.path.join(self.dirname,"config.Template.txt")
if not os.path.exists( config_template ):
if not self.CreateGeraldConfig(config_template):
return False
# Run demultiplex.pl script.
self.Log(["Running demultiplex.pl on run", self.id])
basecall_dir=os.path.join(self.dirname,"Data","Intensities","BaseCalls")
demultiplexed_dir=os.path.join(basecall_dir,"Demultiplexed")
child_dir=os.path.join(self.dirname,"Data")
child_stdout=open(os.path.join(child_dir,"demultiplex.out"),'w')
child_stderr=open(os.path.join(child_dir,"demultiplex.err"),'w')
child_args=[ os.path.join(params.casava_dir,"demultiplex.pl"),
"--input-dir",basecall_dir,
"--sample-sheet",sample_sheet,
"--alignment-config",config_template,
"--output-dir",demultiplexed_dir,
"--mismatches", "1",
]
p = subprocess.Popen(args=child_args,cwd=child_dir,stdout=child_stdout,stderr=child_stderr)
retval = p.wait()
child_stdout.close()
child_stderr.close()
if retval == 0:
# Run make in the Demultiplexed directory.
self.Log(["Running make (to demultiplex qseq files) on run",self.id])
child_dir = demultiplexed_dir
child_stdout=open(os.path.join(child_dir,"make.out"),'w')
child_stderr=open(os.path.join(child_dir,"make.err"),'w')
child_args=["/usr/bin/make","-j","8","ALIGN=yes"]
p = subprocess.Popen(args=child_args,cwd=child_dir,stdout=child_stdout,stderr=child_stderr)
retval = p.wait()
child_stdout.close()
child_stderr.close()
return retval == 0
def FindGeraldDirectory(self,parent_dir=None):
"""Returns name of GERALD directory for run, or None if
no directory exists."""
if parent_dir is None:
parent_dir = os.path.join(self.dirname,"Data","Intensities","BaseCalls")
subdirs = os.listdir(parent_dir)
subdirs.sort()
subdirs.reverse()
pattern = re.compile("GERALD_[0-9]*-[0-9]*-[0-9]*_"+params.username)
for subdir in subdirs:
if pattern.match(subdir):
return os.path.join(parent_dir,subdir)
return None
def DetermineRunType(self):
"""
DetermineRunType determines the run type of the run by looking
at the RunInfo.xml file in the run directory. This mechanism
should be more reliable than checking in GNomEx, since the
GNomEx database run type names change from time to time.
Looking at the RunInfo.xml file, this function counts the
number of reads >= 25 bases in length. If the number of reads
>= 25 bp is 2, the run is paired, otherwise single-end.
Brett Milash, 10/09/2013.
Updated 03/17/2014: Also determines how many index reads
are present, and stores the number of data reads and
index reads in member variables num_data_reads and
num_index_reads. Brett Milash.
"""
# Parse the RunInfo.xml file.
configfile = os.path.join(self.dirname, "RunInfo.xml")
doc = xml.dom.minidom.parse(configfile)
# Get the Read elements from the document.
reads=doc.getElementsByTagName("Read")
# Count the reads that are at least 25 bp long.
self.num_data_reads = 0
self.num_index_reads = 0
for read in reads:
if int(read.getAttribute('NumCycles')) >= 25:
self.num_data_reads += 1
else:
self.num_index_reads += 1
if self.num_data_reads == 1:
self.IsPaired = False
elif self.num_data_reads == 2:
self.IsPaired = True
else:
raise Exception("Expected 1 or 2 data reads in RunInfo.xml. Found %d data reads." % self.num_data_reads )
def CreateGeraldConfig(self,gerald_config_file,lanes="12345678"):
"""Creates GERALD configuration file."""
self.DetermineRunType()
# Determine if single-end or paired-end sequencing.
if self.runtype == 'Paired-end reads':
analysis = 'sequence_pair'
elif self.runtype == 'Single-end reads':
analysis = 'sequence'
else:
# Unknown type of sequencing.
self.Log(["PROBLEM! Run ",self.id,"has unknown type of sequencing,",self.runtype,", unable to create GERALD configuration file."])
return False
ofs = open(gerald_config_file,'w')
ofs.write("""# %s
# Created by %s.
%s:ANALYSIS %s
""" % ( gerald_config_file, sys.argv[0], lanes, analysis ) )
# This section not necessary. Can just use a generic
# gerald config file to process all lanes, barcoded or not.
## Write additional lines if there are any non-barcoded lanes.
#if len(lanes) != 8:
# # Identify non-barcoded lanes.
# non_barcoded_lanes = ''
# for lane in [ '1','2','3','4','5','6','7','8',]:
# if lanes.find(lane) == -1:
# non_barcoded_lanes += lane
# ofs.write("SAMPLE unknown %s:ANALYSIS %s\n" % ( non_barcoded_lanes, analysis ))
ofs.write("""USE_BASES all
EMAIL_LIST [email protected]
EMAIL_DOMAIN hci.utah.edu
EMAIL_SERVER hci-mail.hci.utah.edu:25
WITH_SEQUENCE true
""")
ofs.close()
return True
def FindUnbarcodedLanes( self, sample_sheet_file ):
"""Reads sample sheet file to identify lanes that do NOT include
barcoded samples. Return these lanes as a list of integers."""
barcoded_lanes = []
ifs = open(sample_sheet_file)
for rec in ifs:
try:
lane = int(rec.strip().split(',')[1])
barcoded_lanes.append( lane )
except ValueError:
pass
ifs.close()
# barcoded_lanes is list of lanes with barcoded samples.
s1 = set(range(1,9))
b = set(barcoded_lanes)
non_barcoded_set = s1 - b
return list(non_barcoded_set)
def FindSampleSheetFile( self ):
for filename in os.listdir(self.dirname):
if filename[-4:] == ".csv":
return os.path.join(self.dirname,filename)
raise IOError, "Sample sheet not found in " + self.dirname
def MakeBinList( self ):
"""Finds list of subdirectories named 001, 002, ...."""
binlist = []
for entry in os.listdir("."):
if os.path.isdir(entry) and entry[0] == "0":
binlist.append(entry)
binlist.sort()
return binlist
def ProcessSample(self,lane,sampleid,gerald_dir,demultiplexed_dir):
"""Handles renaming a single samples sequence file or
files (if paired end) within a single bin."""
# Identify the files to be processed.
#pattern = "s_%d_([12]_)*sequence.txt" % lane
#for entry in os.listdir(gerald_dir):
# if re.match(pattern,entry) is not None:
# filelist.append(entry)
#filelist.sort()
run=self.id
# Generate list of files to be processed.
if self.IsPaired:
# Paired-end run
filelist = [ "s_%d_1_sequence.txt" % lane, "s_%d_2_sequence.txt" % lane ]
else:
# Single-end run
filelist = [ "s_%d_sequence.txt" % lane ]
# Alter the sample id from nnnnLn to nnnnXn. Doing this so the file name
# contains the same "X" notation of the samples in GNomEx.
sampleid=re.sub("L","X",sampleid)
retval = True
for file in filelist:
if self.IsPaired:
end=file.split("_")[2]
else:
end=""
orig_name=os.path.join(gerald_dir,file)
if end:
# paired-end
new_name=os.path.join(demultiplexed_dir,"%s_%s_%s_%s.txt" % ( sampleid, run, lane, end ) )
else:
# Single end.
new_name=os.path.join(demultiplexed_dir,"%s_%s_%s.txt" % ( sampleid, run, lane ) )
self.datafiles.append(new_name)
# Check if file already renamed and compressed.
if os.path.exists(new_name+".gz"):
self.Log(["File",orig_name,"already renamed and compressed."])
continue
if os.path.exists(orig_name):
if os.path.exists(new_name):
# Problem! Both the original or new file exist.
self.Log(["PROBLEM! Found both",orig_name,"and",new_name])
retval = False
else:
# Good! Rename the original file.
self.Log(["Renaming",orig_name,"to",new_name])
os.rename(orig_name,new_name)
else:
if os.path.exists(new_name):
# OK - file has already been renamed.
self.Log(["File",orig_name,"already renamed to",new_name])
else:
# Problem! File not found by either name.
self.Log(["PROBLEM! Neither",orig_name,"nor",new_name,"found."])
retval = False
return retval
def ProcessBin( self, bin, demultiplexed_dir ):
"""Renames data files in a single bin subdirectory following demultiplexing.
Data files will end up in demultiplexed_dir.
"""
os.chdir(bin)
# Identify the GERALD directory.
gerald_dir = None
for entry in os.listdir("."):
if os.path.isdir(entry) and entry[0:6] == 'GERALD':
gerald_dir = entry
break
if gerald_dir is None:
self.Log("PROBLEM! No GERALD directory in bin %s.\n" % bin )
os.chdir('..')
return False
# Locate the SampleSheet.csv file.
try:
ifs = open("SampleSheet.csv")
# Feedback.
self.Log( "Processing SampleSheet.csv in %s, Gerald directory %s." % (bin, gerald_dir))
# Read and discard header.
rec = ifs.readline()
# For each line...
for rec in ifs:
f = rec.strip().split(",")
flowcell_barcode=f[0]
lane=int(f[1])
sampleid=f[2].upper()
self.ProcessSample(lane,sampleid,gerald_dir,demultiplexed_dir)
ifs.close()
except IOError:
# No sample sheet!
self.Log("PROBLEM! No SampleSheet.csv file in bin %s.\n" % bin )
os.chdir('..')
return False
os.chdir('..')
return True
def DemultiplexRenameDataFiles_18(self):
"""Combines small gzipped fastq files produced by CASAVA 1.8
into a single gzipped fastq file per sample / end. File names
will be added to self.datafiles, for copying to repository.
If sample belongs to Amplicon Express, however, the files are
left as-is, and the entire directory of files is copied into
the GNomEx repository.
10/11/2013 - commenting out the Amplicon Express-specific
code, because they are running some conventional samples
at HCI. Brett Milash.
05/10/2017 - added code to handle case with missing samples.
If a sample produces 0 reads the directory for the sample isn't
created, and that results in an invalid .txt.gz file for the
sample. This messes up downstream processes where we gunzip
the file. This code now creates a legit empty .txt.gz file.
"""
# Read and parse the sample sheet. This gives lane, sample,
# and request information.
sample_info = []
ifs = open(self.SampleSheetName())
for rec in ifs:
f = rec.strip().split(',')
if f[0] == 'FCID':
# Skip the header.
continue
lane = int(f[1])
sample=f[2]
request = f[9]
requester = f[5]
sample_info.append( (lane,sample,request, requester) )
ifs.close()
# Construct cat statements to build the result files.
self.DetermineRunType()
for ( lane, sample, request, requester ) in sample_info:
basename=os.path.join(self.dirname,"Unaligned")
dirname=os.path.join(basename,'Project_'+request,'Sample_'+sample)
if self.IsPaired:
# Paired-end sequencing
for end in [ 1, 2 ]:
newname = "%s/%s_%s_%d_%d.txt.gz" % ( basename, sample, self.id, lane, end )
if os.path.exists(dirname):
command = "cat %s/%s_*_L00%d_R%d_*.fastq.gz > %s" % ( dirname, sample, lane, end, newname )
else:
command = "cat < /dev/null | gzip > %s" % newname
self.AddJob( command )
self.datafiles.append(newname)
self.Log(command)
else:
# Single-end sequencing.
end = 1
newname = "%s/%s_%s_%d.txt.gz" % ( basename, sample, self.id, lane )
if os.path.exists(dirname):
command = "cat %s/Project_%s/Sample_%s/%s_*_L00%d_R%d_*.fastq.gz > %s" % ( basename, request, sample, sample, lane, end, newname )
else:
command = "cat < /dev/null | gzip > %s" % newname
self.AddJob( command )
self.datafiles.append(newname)
self.Log(command)
retval = self.RunJobs(4,verbose=True)
return retval
def GenerateChecksums( self ):
"""
Creates a .md5 checksum file for each gzipped fastq file.
"""
md5files = []
# Generate MD5 checksum files for each data file.
self.Log(["Generating MD5 checksum files for run",self.id])
for filename in self.datafiles:
# Some of the file names may be directories. Copy
# them using cp -r. This is the case for requests
# from Amplicon Express.
if os.path.isdir(filename):
pass
else:
# Generate command.
directory=os.path.dirname(filename)
fastq_file=os.path.basename(filename)
md5file = fastq_file + ".md5"
cmd="(cd %s; /usr/bin/md5sum %s > %s)" % ( directory, fastq_file, md5file )
self.AddJob( cmd )
md5files.append(os.path.join( directory, md5file) )
cleared = False
while not cleared:
try:
(pid,jobexitstatus) = os.waitpid(-1,os.P_WAIT)
except:
cleared = True
self.RunJobs(5,verbose=True)
# Add the md5 checksum files to the list of data files
# to be distributed.
self.datafiles += md5files
return True
def DistributeDemultiplexed_18( self ):
# CASAVA 1.8 creates many gzipped fastq files per sample.
# Cat these files together into single file per sample/end.
if self.DemultiplexRenameDataFiles_18():
# Generate the MD5 checksums.
if self.GenerateChecksums():
# Copy data files.
if self.CopyDataFiles():
# Notify that run is complete.
self.NotifyComplete('')
return True
return False
def DistributeDemultiplexed( self ):
"""Compress data files from multiplexed samples and copy to server for distribution.
This requires a connection to GNomEx for sample information."""
self.Log(["Distributing data files from run",self.id])
report = ''
if self.DemultiplexRenameDataFiles():
if self.CompressDataFiles():
if self.CopyDataFiles():
# Notify that the run is complete and data available.
self.NotifyComplete(report)
return True
return False
def Gerald( self ):
"""Runs the GERALD scripts to produce sequence files.
If geraldConfig.txt not found, create it.
If GERALD directory not found or geraldConfig.txt is newer,
run GERALD.pl.
Run make in Gerald directory.
"""
# Create gerald config file.
gerald_config_file = os.path.join(self.dirname,"geraldConfig.txt")
if not os.path.exists( gerald_config_file ):
if not self.CreateGeraldConfig(gerald_config_file):
return False
# If GERALD directory does not already exist or is older
# than config file, run GERALD.pl to create it.
gerald_dir = self.FindGeraldDirectory()
retval = 0
if gerald_dir is None or os.path.getctime(gerald_dir) < os.path.getctime(gerald_config_file):
self.Log("Running GERALD.pl on run %s." % self.id)
child_dir = os.path.join(self.dirname,"Data","Intensities","BaseCalls")
child_stdout=open(os.path.join(child_dir,"gerald.out"),'w')
child_stderr=open(os.path.join(child_dir,"gerald.err"),'w')
child_args=[os.path.join(params.casava_dir,"GERALD.pl"),os.path.join(self.dirname,"geraldConfig.txt"),"--EXPT_DIR=.","-make"]
p = subprocess.Popen(args=child_args,cwd=child_dir,stdout=child_stdout,stderr=child_stderr)
retval = p.wait()
child_stdout.close()
child_stderr.close()
# If Gerald ran successfully, get the gerald directory name.
if retval == 0:
gerald_dir = self.FindGeraldDirectory()
else:
self.Log("GERALD.pl already run in %s." % self.id)
# If GERALD run successful, or had been run before...
if retval == 0:
# Run make in the GERALD... directory.
self.Log(["Running make (to create sequence files) on run",self.id])
child_dir = gerald_dir
child_stdout=open(os.path.join(child_dir,"make.out"),'w')
child_stderr=open(os.path.join(child_dir,"make.err"),'w')
child_args=["/usr/bin/make","-j","8"]
p = subprocess.Popen(args=child_args,cwd=child_dir,stdout=child_stdout,stderr=child_stderr)
retval = p.wait()
child_stdout.close()
child_stderr.close()
return retval == 0
def RenameDataFiles( self, lanes=[1,2,3,4,5,6,7,8],dest_dir=None,gerald_parent_dir=None ):
"""Renames the sequence data files produced by a non-barcoded run. Returns True if successful."""
self.Log(["Renaming data files for run",self.id])
self.DetermineRunType()
# Get list of sample names and their lanes.
query = """select sample.number samplenum, flowcellchannel.number lanenum
from flowcellchannel
join sequencelane on sequencelane.idflowcellchannel = flowcellchannel.idflowcellchannel
join sample on sample.idsample = sequencelane.idsample
where flowcellchannel.filename = '%s'""" % self.id
g = gnomex.GNomExConnection()
connection = g.GnConnect(params.db_user,params.db_password)
c = connection.cursor()
c.execute(query)
results = c.fetchall()
# Build mapping from s_<lane>_[<end>_]sequence.txt files to <sample>_<run>_<lane>.txt files.
gerald_dir = self.FindGeraldDirectory(gerald_parent_dir)
self.Log(["RenameDataFiles: gerald_parent_dir = %s, gerald_dir = %s." % ( gerald_parent_dir, gerald_dir )])
if dest_dir is None:
dest_dir=gerald_dir
filenames = []
# List of full pathnames of all data files produced by this run.
for rec in results:
sample = rec[0]
lane = rec[1]
# Skip lane if it is not in one of the lanes to be processed. By default all lanes
# are processed - only exception is for non-barcoded lanes on a flow cell with
# some barcoded samples.
if lane not in lanes:
continue
if self.IsPaired: