-
Notifications
You must be signed in to change notification settings - Fork 8
/
phasdetect.py
1349 lines (1097 loc) · 51.2 KB
/
phasdetect.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
#!/usr/local/bin/python3
## phasdetect : identifies phased siRNA clusters
## Updated : version-v1.07 24/04/17
## author : [email protected]
## Copyright (c): 2016, by University of Delaware
## Contributor : Atul Kakrana
## Affilation : Meyers Lab (Donald Danforth Plant Science Center, St. Louis, MO)
## License copy: Included and found at https://opensource.org/licenses/Artistic-2.0
#### FUNCTIONS ###########################################
import os,sys,subprocess,multiprocessing,time,getpass,shutil,hashlib,datetime,collections,re,argparse
from importlib.machinery import SourceFileLoader
from multiprocessing import Process, Queue, Pool
from subprocess import check_output
import os.path
from os.path import expanduser
# from dedup import dedup_main,dedup_process,dedup_fastatolist,deduplicate,dedup_writer
#### USER SETTINGS ########################################
### Settings file
setFile = "phasis.set"
memFile = "phasis.mem"
res_folder = "phased_%s" % (datetime.datetime.now().strftime("%m_%d_%H_%M"))
home = expanduser("~")
phaster_path = "%s/.phasis" % (home)
## Degradome - Optional ####################################
deg = 'N' ## Use Degradome validation, IF yes enter PARE db in line below
PARE = 'GuturGu' ## If deg = 'Y' then File for degradome analysis
## ADVANCED SETTINGS #######################################
cores = 0 ## 0: Most cores considered as processor pool | 1-INTEGER: Cores to be considered for pool
# nthread = 3 ## Threads perprocess
# server = "tarkan.ddpsc.org" ## Server to use to fetch library information and smallRNA libraries
# perl = "/usr/local/bin/perl_5.18" ## Josh updated the perl on Tarkan and its not ready yet for PHAS script FORK is missing and somemore modules -Check with Pingchuan help
perl = "perl"
Local = 3 ## [0]: Files in directory [2]: Get the libs from $ALLDATA with raw reads
## [3] Get library from srna db with reads filtered on number of hits
noiseLimit = 2
hitsLimit = 10
#############################################################
#############################################################
parser = argparse.ArgumentParser()
parser.add_argument('--lowmem', action='store_true', default=True, help=
'Flag to reduce memory usage for large genomes. Using this flag'\
'will increase the runtime for phaser')
args = parser.parse_args()
def checkUser():
'''
Checks if user is authorized to use script
'''
print ("\n#### Checking user ###########################")
auser = getpass.getuser()
print("Hello '%s' - Please report issues at: https://github.com/atulkakrana/PHASIS/issues" % (auser))
# if auser in allowedUser:
# print("Hello '%s' - Issues need to be reproted: https://github.com/atulkakrana/phasTER/issues \n" % (auser))
# else:
# print("YOU ARE NOT AUTHORIZED TO USE DEVELOPMENTAL VERSION OF 'PHASER'")
# print("Contact 'Atul Kakrana' at [email protected] for permission\n")
# sys.exit()
return None
def checkHost(allowedHost):
'''
Checks if Phster is allowed at this server
'''
print ("#### Pre-run checks ###########################")
f = subprocess.Popen("hostname", stdout=subprocess.PIPE,shell= True)
output,err = f.communicate()
#print (output.decode("ascii"))
host = output.decode("ascii")
print ('--Current host:',host.strip('\n'))
## DO not turn OFF this 'for' loop as that given an error while matching current host with allowedHost - Reason Unknown
# print ('Allowed Hosts:')
# for host in allowedHost:
# print (host)
print("--Allowed hosts: %s" % (','.join(x for x in allowedHost)))
if str(host.strip('\n')) in allowedHost:
print("--PHASIS is supported on this server - good to go!!!\n")
pass
else:
print("--PHASIS is not tested on this server")
print("--Run your analysis at any of these servers:%s" % (','.join(x for x in allowedHost)))
print("--Script will exit now\n")
sys.exit()
return None
def checkDependency():
'''Checks for required components on user system'''
print("\n#### Fn: checkLibs ###########################")
goSignal = True ### Signal to process is set to true
### Check PYTHON version
pythonver = sys.version_info[0]
if int(pythonver) >= 3:
print("--Python v3.0 or higher : found")
pass
else:
print("--Python v3.0 or higher : missing")
goSignal = False
# print("See README for how to INSTALL")
### Check PERL version
# perlver = os.system("perl -e 'print $];' &> /dev/null")
aninfo = check_output(["perl", "-v"]).decode("utf-8")
aninfo2 = aninfo.split('\n')[1].split('(')[1].split(')')[0].rsplit('.',1)[0]
perlver = aninfo2[1:] ## Remove 'v' before version
if float(perlver) >= 5.014:
print("--Perl v5.14 or higher : found")
pass
else:
print("--Perl v5.14 or higher : missing")
goSignal = False
# print("See README for how to INSTALL")
### Check BOWTIE
isbowtie = shutil.which("bowtie")
if isbowtie:
print("--Bowtie (v1) : found")
pass
else:
print("--Bowtie (v1) : missing")
goSignal = False
# print("See README for how to INSTALL")
### Check Perl dependecies
retcode = os.system("perl -MScalar::Util -e1 &> /dev/null")
if retcode == 0:
print("--Scalar::Util (perl) : found")
pass
else:
print("--Scalar::Util (perl) : missing")
goSignal = False
# print("See README for how to INSTALL")
### Check Perl dependecies
retcode = os.system("perl -MData::Dumper -e1 &> /dev/null")
if retcode == 0:
print("--Data::Dumper (perl) : found")
pass
else:
print("--Data::Dumper (perl) : missing")
goSignal = False
# print("See README for how to INSTALL")
### Check Perl dependecies
retcode = os.system("perl -MParallel::ForkManager -e1 &> /dev/null")
if retcode == 0:
print("--Parallel::ForkManager (perl) : found")
pass
else:
print("--Parallel::ForkManager (perl) : missing")
goSignal = False
# print("See README for how to INSTALL")
### Check Perl dependecies
retcode = os.system("perl -MGetopt::Long -e1 &> /dev/null")
if retcode == 0:
print("--Getopt::Long (perl) : found")
pass
else:
print("--Getopt::Long (perl) : missing")
goSignal = False
# print("See README for how to INSTALL")
if goSignal == False:
print("\n** Please install the missing libraries before running the analyses")
# print("See README for how to install these")
print("** revFerno has unmet dependendies and will exit for now\n")
sys.exit()
return None
def readSet(setFile):
'''
Read and parse external settings file
'''
if os.path.isfile(setFile):
pass
else:
print("---Settings file 'phasis.set' not found in current directory")
print("---Please copy it to same directory as script and rerun")
sys.exit()
print("\n#### Fn: Settings Reader #####################")
fh_in = open(setFile, 'r')
setFile = fh_in.readlines()
fh_in.close()
for line in setFile:
if line: ## Not empty
if line.startswith('@'):
line = line.strip("\n")
# print(line)
akey,aval = line.split('=')
param = akey.strip()
value = aval.strip()
# print(param,value)
### Extract values #########
if param.strip() == '@runType':
global runType
runType = str(value.strip())
if (runType != "G") and (runType != "T") and (runType != "S"):
print("Please input correct setting for '@runType' parameter in 'phasis.set' file")
print("Script will exit for now\n")
sys.exit()
else:
print('User Input runType :',runType)
elif param.strip() == '@reference':
global reference
reference = str(value.strip())
print('User Input reference location :',reference)
elif param.strip() == '@index':
global index
index = str(value.strip())
if index:
print('User Input index location :',index)
else:
print('User Input index location : None')
elif param.strip() == '@userLibs':
global libs
# libs = list(map(str,value.strip().split(',')))
libs = [str(x) for x in value.strip().split(',') if x.strip() != '' ] ## This is my dope...
print('User Input Libs :',",".join(libs))
elif param.strip() == '@libFormat':
global libFormat
libFormat = str(value.strip())
if (libFormat != "T") and (libFormat != "F"):
print("Please input correct setting for '@libFormat' parameter in 'phasis.set' file")
print("Script will exit for now\n")
sys.exit()
else:
print('user library format :',libFormat)
elif param.strip() == '@phase':
global phase
phase = int(value.strip())
print('User Input for phase length :',phase)
elif param.strip() == '@path_prepro_git':
global phaster_path
phaster_path = str(value.strip()).rstrip("/")+"/phaster"
# phaster_path = str(value.strip()).rstrip("/")+"/core"
print('User Input for phaster path :',phaster_path)
elif param.strip() == '@minDepth':
global minDepth
minDepth = int(value.strip())
if not minDepth:
minDepth = 3
print('User Input for min. sRNA depth :',minDepth)
elif param.strip() == '@clustBuffer':
global clustBuffer
clustBuffer = int(value.strip())
if not clustBuffer:
clustBuffer = 250
print('User Input distance b/w clusters :',clustBuffer)
# elif param.strip() == '@mismat':
# global mismat
# mismat = int(value.strip())
# if not mismat:
# mismat = 0
# print('User Input for max mismatches :',mismat)
else:
#print("Missed line:",line)
pass
# sys.exit()
return libs
def PHASBatch(con,libs,runType,index,deg):
'''
## Deprecated
'''
#os.mkdir('./%s' % (lib))
#output_path = './%s' % (lib)
for lib in libs:
print (lib)
cur = con.cursor()
cur.execute('SELECT processed_path FROM master.library_info where lib_id = %s' % (lib))
path = cur.fetchall()
#print(path[0][0])
pro_file = path[0][0].replace('$ALLDATA', '/alldata')###Processed sRNA file
out_file = '%s.txt' % (lib)
rl = str(phase)
nproc2 = str(nproc)
sRNAratio = str(75)
print (pro_file)
if runType == 'G': ### Uses Whole genome as input
if deg == 'Y':
retcode = subprocess.call([perl, "/data2/homes/kakrana/svn/users/kakrana/phasiRNA_prediction_pipeline.ver.genome.pl", "-i", pro_file, "-q", PARE, "-f", "-t", sRNAratio, "-d", index, "-px", out_file, "-rl", rl, "-cpu", nproc2])
else:
retcode = subprocess.call([perl, "/data2/homes/kakrana/svn/users/kakrana/phasiRNA_prediction_pipeline.ver.genome.pl", "-i", pro_file,"-f", "-t", sRNAratio, "-d", index, "-px", out_file, "-rl", rl, "-cpu", nproc2])
else: ### Uses FASTA file of genes as input
#pipe =subprocess.Popen(["perl5.18", "-v"])
if deg == 'Y':
retcode = subprocess.call([perl, "/data2/homes/kakrana/svn/users/kakrana/phasiRNA_prediction_pipeline.ver.MUL.pl", "-i", pro_file, "-q", PARE, "-f", "-t", sRNAratio, "-d", index, "-px", out_file, "-rl", rl, "-cpu", nproc2])
else:
retcode = subprocess.call([perl, "/data2/homes/kakrana/svn/users/kakrana/phasiRNA_prediction_pipeline.ver.MUL.pl", "-i", pro_file, "-f", "-t", sRNAratio, "-d", index, "-px", out_file, "-rl", rl, "-cpu", nproc2])
if retcode == 0:
pass
else:
print("Problem with Phasing script - Return code not 0")
sys.exit()
return lib
def TagAbundanceFile(con,db,libs):
'''
### sRNA Libraries are fetched from server
'''
for alib in libs:##For all the libraries
## Check if file already exsits in directory - This saves a lot of time downloading the same file
filePath = '%s.fas' % (alib)
if os.path.isfile(filePath) == False:
print ('\nPreparing sRNA reads file for library: %s' % (alib[0]))
#print (lib[0])
#print ('Caching tag and count information from server for PARE alib %s' % (alib[0]) )
cur = con.cursor()
cur.execute("SELECT tag,norm from %s.run_master where lib_id = %s AND (hits between 0 and 20)" % (db,alib[0]))
lib_info = cur.fetchall()
#print('These are the tags:',lib_info[:10])
fh_out = open('%s.fas' % (alib), 'w')##Naming file with lib_ids name
print ('Library cached, writing abundance file')
tag_num = 1
for ent in lib_info:## All the PARE tags in a library
#print (ent)
fh_out.write('%s\t%s\n' % (ent[0],ent[1]))
tag_num += 1
fh_out.close()
else:
print('tag abundance file exists for library: %s' % (alib))
pass
def PHASBatch2(aninput):
'''
Phasing anlysis - New
'''
print ("\n#### Fn: phaser #############################")
# print("\naninput\n",aninput)
lib,runType,index,deg,nthread,noiseLimit,hitsLimit,clustBuffer = aninput
### Sanity check #####################
if not os.path.isfile(lib):
print("** %s - sRNA library file not found" % (lib))
print("** Please check the library- Is it in specified directory? Did you input wrong name?")
print("** Script will exit for now\n")
sys.exit()
else:
print("sRNA library located - Running phasing analysis")
pass
#####################################
pro_file = lib ### sRNA input file
out_file = './%s/%s.txt' % (res_folder,lib.rpartition(".")[0]) ## Output file suffix
rl = str(phase)
# nproc2 = str(nproc)
nthread = str(nthread)
sRNAratio = str(75)
noiseLimit = str(minDepth-1)
# mismat = str(mismat)
clustBuffer = str(clustBuffer)
print(pro_file)
if runType == 'G':### Uses Whole genome as input
full_path = "%s/phasclust.genome.v2.pl" % (phaster_path)
# print(full_path)
if deg == 'Y':
retcode = subprocess.call([perl, "%s/phasclust.genome.v2.pl" % (phaster_path), "-i", pro_file, "-q", PARE, "-f", "-t", sRNAratio, "-d", index, "-px", out_file, "-rl", rl, "-cpu", nthread])
else:
if libFormat == "T":
aformat = "t"
retcode = subprocess.call([perl, "%s/phasclust.genome.v2.pl" % (phaster_path), "-i", pro_file,"-f", aformat, "-t", sRNAratio,"-n", noiseLimit, "-g", clustBuffer, "-d", index, "-px", out_file, "-rl", rl, "-cpu", nthread])
elif libFormat == "F":
aformat = "f"
retcode = subprocess.call([perl, "%s/phasclust.genome.v2.pl" % (phaster_path), "-i", pro_file,"-f", aformat, "-t", sRNAratio,"-n", noiseLimit, "-g", clustBuffer, "-d", index, "-px", out_file, "-rl", rl, "-cpu", nthread])
else:
print("** Invalid '@libFormat' parameter value")
print("** Please check the '@libFormat' parameter value in setting file")
print("** F for FASTA format | T for tag-count format are the only acceptable values")
print("** Script will exit now")
sys.exit()
else: ### Uses FASTA file of genes as input
full_path = "%s/phasclust.MUL.v2.pl" % (phaster_path)
# print(full_path)
if deg == 'Y':
retcode = subprocess.call([perl, "%s/phasclust.MUL.v2.pl" % (phaster_path), "-i", pro_file, "-q", PARE, "-f", "-t", sRNAratio, "-d", index, "-px", out_file, "-rl", rl, "-cpu", nthread])
else:
if libFormat == "T":
aformat = "t"
retcode = subprocess.call([perl, "%s/phasclust.MUL.v2.pl" % (phaster_path), "-i", pro_file, "-f", aformat, "-t", sRNAratio,"-n", noiseLimit, "-g", clustBuffer, "-d", index, "-px", out_file, "-rl", rl, "-cpu", nthread])
elif libFormat == "F":
aformat = "f"
retcode = subprocess.call([perl, "%s/phasclust.MUL.v2.pl" % (phaster_path), "-i", pro_file,"-f", aformat, "-t", sRNAratio,"-n", noiseLimit, "-g", clustBuffer, "-d", index, "-px", out_file, "-rl", rl, "-cpu", nthread])
else:
print("** Invalid '@libFormat' parameter value")
print("** Please check the '@libFormat' parameter value in setting file")
print("** F for FASTA format | T for tag-count format are the only acceptable values")
print("** Script will exit now")
sys.exit()
if retcode == 0:
pass
else:
print("** Problem with Phasing script - Return code not 0")
sys.exit()
return None
def PP(module,alist):
'''
paralleizes process with no results catching
'''
start = time.time()
npool = Pool(int(nproc))
npool.map(module, alist)
def PPResults(module,alist):
'''
Parallelizes and stores result
'''
####
npool = Pool(int(nproc))
res = npool.map_async(module, alist)
results = (res.get())
npool.close()
return results
def PPBalance(module,alist):
'''
Balance process according to core pool
'''
#print('***********Parallel instance of %s is being executed*********' % (module))
start = time.time()
##PP is being used for Bowtie mappings - This will avoid overflooding of processes to server
nprocPP = round((nproc/int(nthread)))
if nprocPP < 1:
nprocPP = 1 ## 1 here so as to avoid 0 processor being allocated in serial mode
else:
pass
print("nprocPP : %s" % (nprocPP))
npool = Pool(int(nprocPP))
npool.map(module, alist)
def optimize(nproc):
'''
dirty optimization of threads per library
'''
nlibs = len(libs)
ninstances = int(nproc/nlibs) ### Number of parallel instances to use
# print("Libs:%s | nproc:%s | ninstance:%s" % (nlibs,nproc,ninstances))
if ninstances > 3:
nthread = ninstances
else:
nthread = 3
print("\n#### %s computing core(s) reserved for analysis ##########" % (str(nproc)))
print("#### %s computing core(s) assigned to one lib ############\n" % (str(nthread)))
# time.sleep(1)
return nthread
def inputList(libs,runType,index,deg,nthread,noiseLimit,hitsLimit,clustBuffer):
'''generate raw inputs for parallel processing'''
rawInputs = [] ## An empty list to store inputs for PP
for alib in libs:
rawInputs.append((alib,runType,index,deg,nthread,noiseLimit,hitsLimit,clustBuffer))
# print("These are rawInputs:",rawInputs)
return rawInputs
def indexBuilder(reference):
'''
Generic index building module
'''
print ("\n#### Fn: indexBuilder #######################")
### Sanity check #####################
if not os.path.isfile(reference):
print("'%s' reference file not found" % (reference))
print("Please check the genomeFile - Is it in specified directory? Did you input wrong name?")
print("Script will exit for now\n")
sys.exit()
else:
print("Reference file located - Preparing to create index")
pass
#####################################
### Clean reference ################
fastaclean,fastasumm = FASTAClean(reference,0)
### Prepare Index ##################
print ("**Deleting old index 'folder' !!!!!!!!!!!**")
shutil.rmtree('./index', ignore_errors=True)
os.mkdir('./index')
genoIndex = '%s/index/%s' % (os.getcwd(),fastaclean.rpartition('/')[-1].rpartition('.')[0]) ## Can be merged with genoIndex from earlier part if we use bowtie2 earlier
# genoIndex = './index/%s' % (fastaclean.rpartition('/')[-1].rpartition('.')[0]) ## Alternative approach -Can be merged with genoIndex from earlier part if we use bowtie2 earlier
print('Creating index of cDNA/genomic sequences:%s**\n' % (genoIndex))
adcv = "256"
divn = "6"
### Run based on input about the memory
if args.lowmem:
retcode = subprocess.call(["bowtie-build","-f", fastaclean, genoIndex])
else:
retcode = subprocess.call(["bowtie-build","-f", "--noauto", "--dcv", adcv,"--bmaxdivn", divn, fastaclean, genoIndex])
if retcode == 0:## The bowtie mapping exit with status 0, all is well
# print("Reference index prepared sucessfully")
pass
else:
print("There is some problem preparing index of reference '%s'" % (reference))
print("Is 'Bowtie' installed? And added to environment variable?")
print("Script will exit now")
sys.exit()
##########################################
## Test for index files #################
# Close this code if not testing
# fh_in1 = open("./index/Triticum_aestivum.TGACv1.dna.toplevel.clean.1.ebwtl",'w')
# fh_in1.write("Atul is a developer for PHASIS")
# fh_in1.close()
##########################################
### Make a memory file ###################
fh_out = open(memFile,'w')
# print("Generating MD5 hash for reference")
refHash = (hashlib.md5(open('%s' % (reference),'rb').read()).hexdigest()) ### reference hash used instead of cleaned FASTA because while comparing only the user input reference is available
print("Generating MD5 hash for Bowtie index")
if os.path.isfile("%s.1.ebwtl" % (genoIndex)):
indexHash = (hashlib.md5(open('%s.1.ebwtl' % (genoIndex),'rb').read()).hexdigest())
elif os.path.isfile("%s.1.ebwt" % (genoIndex)):
indexHash = (hashlib.md5(open('%s.1.ebwt' % (genoIndex),'rb').read()).hexdigest())
else:
print("File extension for index couldn't be determined properly")
print("It could be an issue from Bowtie")
print("This needs to be reported to 'PHASIS' developer - Script will exit")
sys.exit()
print("\n@genomehash:%s | @indexhash:%s" % (refHash, indexHash) )
fh_out.write("@timestamp:%s\n" % (datetime.datetime.now().strftime("%m_%d_%H_%M")))
fh_out.write("@genomehash:%s\n" % (refHash))
fh_out.write("@index:%s\n" % (genoIndex))
fh_out.write("@indexhash:%s\n" % (indexHash))
print("Index prepared:%s\n" % (genoIndex))
# sys.exit()
return genoIndex
def indexBuilder2(reference,fastaclean):
'''
Prepared to work with parallelized version of FASTA cleaner - Not implemented yet - because parallel FASTA
cleaner is slow on bigger genomes - need trouble shooting
'''
print ("\n#### Fn: indexBuilder #######################")
### Prepare Index ##################
print ("**Deleting old index 'folder' !!!!!!!!!!!**")
shutil.rmtree('./index', ignore_errors=True)
os.mkdir('./index')
genoIndex = '%s/index/%s' % (os.getcwd(),fastaclean.rpartition('/')[-1].rpartition('.')[0]) ## Can be merged with genoIndex from earlier part if we use bowtie2 earlier
# genoIndex = './index/%s' % (fastaclean.rpartition('/')[-1].rpartition('.')[0]) ## Alternative approach -Can be merged with genoIndex from earlier part if we use bowtie2 earlier
print('Creating index of cDNA/genomic sequences:%s**\n' % (genoIndex))
adcv = "256"
divn = "6"
### Run based on input about the memory
if args.lowmem:
retcode = subprocess.call(["bowtie-build","-f", fastaclean, genoIndex])
else:
retcode = subprocess.call(["bowtie-build","-f", "--noauto", "--dcv", adcv,"--bmaxdivn", divn, fastaclean, genoIndex])
if retcode == 0:## The bowtie mapping exit with status 0, all is well
# print("Reference index prepared sucessfully")
pass
else:
print("There is some problem preparing index of reference '%s'" % (reference))
print("Is 'Bowtie' installed? And added to environment variable?")
print("Script will exit now")
sys.exit()
##########################################
### Test for index files #################
# ## Close this code if not testing
# fh_in1 = open("./index/Triticum_aestivum.TGACv1.dna.toplevel.clean.1.ebwtl",'w')
# fh_in1.write("Atul is a developer for PHASIS")
# fh_in1.close()
##########################################
### Make a memory file ###################
fh_out = open(memFile,'w')
print("Generating MD5 hash for reference")
refHash = (hashlib.md5(open('%s' % (reference),'rb').read()).hexdigest()) ### reference hash used instead of cleaned FASTA because while comparing only the user input reference is available
print("Generating MD5 hash for Bowtie index")
if os.path.isfile("%s.1.ebwtl" % (genoIndex)):
indexHash = (hashlib.md5(open('%s.1.ebwtl' % (genoIndex),'rb').read()).hexdigest())
elif os.path.isfile("%s.1.ebwt" % (genoIndex)):
indexHash = (hashlib.md5(open('%s.1.ebwt' % (genoIndex),'rb').read()).hexdigest())
else:
print("File extension for index couldn't be determined properly")
print("It could be an issue from Bowtie")
print("This needs to be reported to 'PHASIS' developer - Script will exit")
sys.exit()
print("\n@genomehash:%s | @indexhash:%s" % (refHash, indexHash) )
fh_out.write("@timestamp:%s\n" % (datetime.datetime.now().strftime("%m_%d_%H_%M")))
fh_out.write("@genomehash:%s\n" % (refHash))
fh_out.write("@index:%s\n" % (genoIndex))
fh_out.write("@indexhash:%s\n" % (indexHash))
print("Index prepared:%s\n" % (genoIndex))
# sys.exit()
return genoIndex
def indexIntegrityCheck(index):
'''
Checks the integrity of index and the extension
'''
indexFolder = index.rpartition("/")[0]
# print("This is the folder from earlier run:%s" % (indexFolder))
if os.path.isfile("%s.1.ebwtl" % (index)): ## Check if this extension exists in folder
indexExt = "ebwtl"
indexFiles = [i for i in os.listdir('%s' % (indexFolder)) if i.endswith('.ebwtl')]
if len(indexFiles) >= 6:
# print("Index has all six parts")
indexIntegrity = True
elif os.path.isfile("%s.1.ebwt" % (index)):
indexExt = "ebwt"
indexFiles = [i for i in os.listdir('%s' % (indexFolder)) if i.endswith('.ebwt')]
if len(indexFiles) >= 6:
# print("Index has all six parts")
indexIntegrity = True
else:
print("Existing index extension couldn't be determined")
print("Genome index will be remade")
indexExt = False
indexIntegrity = False
print("Ancillary data integrity :",indexIntegrity)
# print("Number of files:%s" % (len(indexFiles)))
return indexIntegrity,indexExt
def FASTAClean(filename,mode):
'''Cleans FASTA file - multi-line fasta to single line, header clean, empty lines removal'''
## Read seqeunce file
fh_in = open(filename, 'r')
print ("phasdetect uses FASTA header as key for identifying the phased loci")
print ("Caching '%s' reference FASTA file" % (filename))
## Write file
if mode == 0:
fastaclean = ('%s/%s.clean.fa' % (os.getcwd(),filename.rpartition('/')[-1].rpartition('.')[0])) ## os.getcwd(),fastaclean.rpartition('/')[-1].rpartition('.')[0]
else:
print("Input correct mode- 0: Normal | 1: Seqeunces reversed | 2: Seqeunces reverse complemented | 3: Seqeunces complemented only")
print("USAGE: cleanFasta.v.x.x.py FASTAFILE MODE")
sys.exit()
### Outfiles
fh_out1 = open(fastaclean, 'w')
fastasumm = ('%s/%s.summ.txt' % (os.getcwd(),filename.rpartition('/')[-1].rpartition('.')[0]))
fh_out2 = open(fastasumm, 'w')
fh_out2.write("Name\tLen\n")
### Read files
fasta = fh_in.read()
fasta_splt = fasta.split('>')
fastaD = {} ## Store FASTA as dict
acount = 0 ## count the number of entries
empty_count = 0
for i in fasta_splt[1:]:
ent = i.split('\n')
aname = ent[0].split()[0].strip()
if runType == 'G':
## To match with phasing-core script for genome version which removed non-numeric and preceding 0s
name = re.sub("[^0-9]", "", aname).lstrip('0')
else:
name = aname
seq = ''.join(x.strip() for x in ent[1:]) ## Sequence in multiple lines
alen = len(seq)
if alen > 200:
fh_out1.write('>%s\n%s\n' % (name,seq))
fh_out2.write('%s\t%s\n' % (name,alen))
acount+=1
else:
empty_count+=1
pass
#### Prepare a dictionary - Not Tested
# for line in fh_in:
# if line.startswith('>'):
# name = line[1:].rstrip('\n').split()[0]
# fastaD[name] = ''
# else:
# fastaD[name] += line.rstrip('\n').rstrip('*')
#### Write results - Not tested
# for name,seq in fastaD.items():
# alen = len(seq)
# if alen > 200:
# fh_out1.write('>%s\n%s\n' % (name,seq))
# fh_out2.write('%s\t%s\n' % (name,alen))
# acount+=1
# else:
# empty_count+=1
# pass
fh_in.close()
fh_out1.close()
fh_out2.close()
print("Fasta file with reduced header: '%s' with total entries %s is prepared" % (fastaclean, acount))
print("There were %s entries found with empty sequences and were removed\n" % (empty_count))
return fastaclean,fastasumm
def readMem(memFile):
'''
Reads memory file and gives global variables
'''
print ("#### Fn: memReader ############################")
fh_in = open(memFile,'r')
memRead = fh_in.readlines()
fh_in.close()
memflag = True
varcount = 0
for line in memRead:
if line: ## Not empty
if line.startswith('@'):
line = line.strip("\n")
# print(line)
akey,aval = line.split(':')
param = akey.strip()
value = aval.strip()
# print(param,value)
if param == '@genomehash':
global existRefHash
varcount+=1
existRefHash = str(value)
print('Existing reference hash :',existRefHash)
elif param == '@indexhash':
global existIndexHash
varcount+=1
existIndexHash = str(value)
print('Existing index hash :',existIndexHash)
elif param == '@index':
global index
varcount+=1
index = str(value)
print('Existing index location :',index)
else:
pass
## Sanity Check - Memory file is not empty, from a crash
# if existRefHash.strip() == '':
# memflag = False
# elif existIndexHash.strip() == '':
# memflag = False
# elif index.strip() == '':
# memflag = False
if varcount == 3:
memflag = True
else:
memflag = False
return memflag
def coreReserve(cores):
'''
Decides the core pool for machine - written to make PHASIS comaptible with machines that
have less than 10 cores - Will be improved in future
'''
if cores == 0:
## Automatic assignment of cores selected
totalcores = int(multiprocessing.cpu_count())
if totalcores == 4: ## For quad core system
nproc = 3
elif totalcores == 6: ## For hexa core system
nproc = 5
elif totalcores > 6 and totalcores <= 10: ## For octa core system and those with less than 10 cores
nproc = 7
else:
nproc = int(totalcores*0.9)
else:
## Reserve user specifed cores
nproc = int(cores)
return nproc
#### FASTA CLEAN P - IN DEV
def FASTAread(filename):
'''
Reads FASTA file to alist
'''
### Sanity check #####################
if not os.path.isfile(reference):
print("'%s' reference file not found" % (reference))
print("Please check the genomeFile - Is it in specified directory? Did you input wrong name?")
print("Script will exit for now\n")
sys.exit()
else:
print("Reference file located - Preparing to create index")
pass
#####################################
### Read seqeunce file ##############
fh_in = open(filename, 'r')
print ("phasdetect uses FASTA header as key for identifying the phased loci")
print ("Caching reference '%s' FASTA file" % (filename))
fasta = fh_in.read()
fasta_splt = fasta.split('>')
print("Cached FASTA file with %s entries" % (len(fasta_splt[1:])))
fh_in.close()
return fasta_splt[1:]
def FASTAclean(ent):
'''
Cleans one entry of FASTA file - multi-line fasta to single line, header clean, empty lines removal
'''
ent_splt = ent.split('\n')
aname = ent_splt[0].split()[0].strip()
# print("Cleaning - %s" % (aname))
if runType == 'G':
## To match with phasing-core script for genome version which removed non-numeric and preceding 0s
bname = re.sub("[^0-9]", "", aname).lstrip('0')
else:
bname = aname
bseq = ''.join(x.strip() for x in ent[1:]) ## Sequence in multiple lines
return bname,bseq
def FASTAwrite(filename,alist,mode):
'''
Writes list of processed/cleaned FASTA
'''
## Write file
if mode == 0:
fastaclean = ('%s/%s.clean.fa' % (os.getcwd(),filename.rpartition('/')[-1].rpartition('.')[0])) ## os.getcwd(),fastaclean.rpartition('/')[-1].rpartition('.')[0]
else:
print("Input correct mode- 0: Normal | 1: Seqeunces reversed | 2: Seqeunces reverse complemented | 3: Seqeunces complemented only")
print("USAGE: cleanFasta.v.x.x.py FASTAFILE MODE")
sys.exit()
### Outfiles
fh_out1 = open(fastaclean, 'w')
fastasumm = ('%s/%s.summ.txt' % (os.getcwd(),filename.rpartition('/')[-1].rpartition('.')[0]))
fh_out2 = open(fastasumm, 'w')
fh_out2.write("Name\tLen\n")
acount = 0 ## count the number of entries
empty_count = 0 ## count empty entries
for ent in alist:
aname,aseq = ent
alen = len(aseq)
if alen > 200:
fh_out1.write('>%s\n%s\n' % (aname,aseq))
fh_out2.write('%s\t%s\n' % (aname,alen))
acount+=1
else:
empty_count+=1
pass
fh_out1.close()
fh_out2.close()
print("Fasta file with reduced header: '%s' with total entries %s is prepared" % (fastaclean, acount))
print("There were %s entries with empty/short sequences,these were removed\n" % (empty_count))
return fastaclean,fastasumm
#### DE-DUPLICATOR MODULES ####
def dedup_process(alib):
'''
To parallelize the process
'''
print("\n#### Fn: De-duplicater #######################")
afastaL = dedup_fastatolist(alib) ## Read
acounter = deduplicate(afastaL ) ## De-duplicate
countFile = dedup_writer(acounter,alib) ## Write
return countFile
def dedup_fastatolist(alib):
'''
New FASTA reader
'''
### Sanity check
try:
f = open(alib,'r')
except IOError:
print ("The file, %s, does not exist" % (alib))
return None
## Output
fastaL = [] ## List that holds FASTA tags
print("Reading FASTA file:%s" % (alib))
read_start = time.time()
acount = 0
empty_count = 0
for line in f:
if line.startswith('>'):
seq = ''
pass
else:
seq = line.rstrip('\n')
fastaL.append(seq)
acount += 1