├── Sort.sh ├── check_rpack.r ├── check_pypack.py ├── test.opt.tbl ├── heliano_bcheck.R ├── Flanking_seq.R ├── configure.sh ├── SplitJoint.R ├── tclcv.txt ├── heliano_cons.py ├── heliano_fisher.R ├── readme.md ├── LICENSE.txt └── heliano.py /Sort.sh: -------------------------------------------------------------------------------- 1 | inputfile=${1} 2 | CPU_num=${2} 3 | 4 | sort -k1,1 -k2,2n --parallel=${CPU_num} ${inputfile} > ${inputfile}.tmp 5 | 6 | mv ${inputfile}.tmp ${inputfile} 7 | -------------------------------------------------------------------------------- /check_rpack.r: -------------------------------------------------------------------------------- 1 | 2 | tryCatch({library('seqinr')}, error=function(e){print("R package seqinr not installed!")}) 3 | tryCatch({library('bedtoolsr')}, error=function(e){print("R package bedtoolsr not installed!")}) 4 | -------------------------------------------------------------------------------- /check_pypack.py: -------------------------------------------------------------------------------- 1 | 2 | try: 3 | from Bio import SeqIO 4 | except: 5 | print("python package biopython was not installed!\n") 6 | try: 7 | import pybedtools as BT 8 | except: 9 | print("python package pybedtools was not installed!") 10 | 11 | -------------------------------------------------------------------------------- /test.opt.tbl: -------------------------------------------------------------------------------- 1 | CP128282.1 53617 59046 HLE2_left_18-HLE2_right_18 7 - 6.3390e-07 60 HLE2 auto insertion_HLE2_auto_1 2 | CP128282.1 83425 88824 HLE2_left_18-HLE2_right_18 7 - 6.3390e-07 60 HLE2 auto insertion_HLE2_auto_2 3 | CP128282.1 94525 99924 HLE2_left_18-HLE2_right_18 7 + 6.3390e-07 60 HLE2 auto insertion_HLE2_auto_3 4 | CP128282.1 306838 312276 HLE2_left_18-HLE2_right_18 7 + 6.3390e-07 60 HLE2 auto insertion_HLE2_auto_4 5 | CP128282.1 665681 668554 HLE2_left_33-HLE2_right_32 3 - 1.3547e-05 60 HLE2 nonauto insertion_HLE2_nonauto_1 6 | CP128282.1 668719 671599 HLE2_left_33-HLE2_right_32 3 + 1.3547e-05 60 HLE2 nonauto insertion_HLE2_nonauto_2 7 | CP128282.1 855863 858738 HLE2_left_33-HLE2_right_32 3 + 1.3547e-05 60 HLE2 nonauto insertion_HLE2_nonauto_3 8 | CP128282.1 855863 880806 HLE2_left_33-HLE2_right_32 3 + 1.3547e-05 60 HLE2 auto insertion_HLE2_auto_5 9 | CP128282.1 926221 928267 CP128282.1-926221-928267 1 - 1 0 HLE2 orfonly insertion_HLE2_orfonly_1 10 | CP128282.1 963556 968985 HLE2_left_18-HLE2_right_18 7 + 6.3390e-07 60 HLE2 auto insertion_HLE2_auto_6 11 | CP128282.1 1107206 1112635 HLE2_left_18-HLE2_right_18 7 + 6.3390e-07 60 HLE2 auto insertion_HLE2_auto_7 12 | CP128282.1 1259412 1264991 HLE2_left_18-HLE2_right_18 7 - 6.3390e-07 60 HLE2 auto insertion_HLE2_auto_8 13 | -------------------------------------------------------------------------------- /heliano_bcheck.R: -------------------------------------------------------------------------------- 1 | library(seqinr) 2 | 3 | args=commandArgs(T) 4 | 5 | wkdir = args[1] 6 | OPTFILE = args[2] 7 | 8 | setwd(wkdir) 9 | 10 | file_list = list.files('./') 11 | 12 | aln_list = file_list[sapply(file_list, function(x){endsWith(x, '.fa.aln')})] 13 | 14 | calculate_distance = function(x){ 15 | aln = read.alignment(x, format = 'fasta') 16 | distance = as.vector(dist.alignment(aln)) 17 | ## means only one sequence 18 | if(length(distance)==0){ 19 | distance = 1 20 | } 21 | ## na means the two sequences have very low identity. 22 | distance[is.na(distance)] = 1 23 | identity =1 - distance**2 24 | string_vector = strsplit(x, split = '\\.')[[1]] 25 | name = string_vector[1] 26 | direction = string_vector[2] 27 | return(c(name, direction, mean(identity))) 28 | } 29 | 30 | 31 | if(length(aln_list)>=2){ 32 | identity_df = as.data.frame(do.call('rbind', lapply(aln_list, function(x){calculate_distance(x)})), stringsAsFactors = F) 33 | colnames(identity_df)=c('pairname', 'direction', 'identity') 34 | # identity_df = tidyr::spread(identity_df, key = direction, value = identity) 35 | # identity_df[which(is.na(identity_df$left)), 'left'] = 0 36 | # identity_df[which(is.na(identity_df$right)), 'right'] = 0 37 | 38 | write.table(identity_df, file = OPTFILE, sep = '\t', quote = F, col.names = T, row.names = F) 39 | } 40 | 41 | -------------------------------------------------------------------------------- /Flanking_seq.R: -------------------------------------------------------------------------------- 1 | library(bedtoolsr) 2 | library(parallel) 3 | 4 | ###set argument##### 5 | args=commandArgs(T) 6 | bedtools_path = args[1] 7 | bed_fisher_dir=args[2] 8 | boundary_dir = args[3] 9 | Genome_path=args[4] 10 | Genome_size = args[5] 11 | MAX_CPU_num = detectCores() -1 12 | CPU_num=as.numeric(args[6]) 13 | CPU_num = ifelse(CPU_num < MAX_CPU_num, CPU_num, MAX_CPU_num) 14 | CPU_num = ifelse(CPU_num<1, 1, CPU_num) 15 | options(bedtools.path = bedtools_path) 16 | 17 | ##################### To output sequences #################### 18 | Genome_size_df=read.csv2(Genome_size, stringsAsFactors = F, header = F, sep = '\t') 19 | colnames(Genome_size_df)=c('chr', 'length') 20 | fisher_file_list = list.files(bed_fisher_dir, full.names = T, pattern = '.bed') 21 | 22 | cl = makeCluster(CPU_num) 23 | clusterExport(cl, c('bedtools_path', 'Genome_path', 'Genome_size_df'), envir = .GlobalEnv) 24 | clusterEvalQ(cl, list(library(bedtoolsr), options(bedtools.path = bedtools_path))) 25 | 26 | parSapply(cl, fisher_file_list, function(x){ 27 | pairname=gsub('\\.bed', '', basename(x)) 28 | candidate_bed=bt.sort(x) 29 | merged_candidate = bt.merge(d=100, c = '4,5,6', o='first,mean,first') 30 | merged_candidate = merged_candidate[order(merged_candidate$V5, decreacing=T), ] 31 | row_count = nrow(merged_candidate) 32 | if(row_count>=2){ 33 | row_count = ifelse(row_count>20, 20, row_count) 34 | merged_candidate = merged_candidate[1:row_count, c(1:6)] 35 | colnames(merged_candidate)=c('chr', 'start', 'stop', 'family', 'copy', 'strand') 36 | ### To output 100 bp terminal flanking 37 | terminal_flank = merged_candidate 38 | terminal_flank$start=terminal_flank$start-101 39 | terminal_flank$stop=terminal_flank$stop+99 40 | terminal_flank = merge(terminal_flank, Genome_size_df) 41 | terminal_flank$start = ifelse(terminal_flank$start<0, 0, terminal_flank$start) 42 | terminal_flank$stop = ifelse(terminal_flank$stop>terminal_flank$length, terminal_flank$length, terminal_flank$stop) 43 | terminal_flank = terminal_flank[which(terminal_flank$stop - terminal_flank$start >200), ] 44 | } 45 | 46 | }) 47 | 48 | stopCluster (cl) -------------------------------------------------------------------------------- /configure.sh: -------------------------------------------------------------------------------- 1 | ## check dependencies 2 | 3 | dependency_stat=1 4 | 5 | gt=`which gt` 6 | if [[ ${gt} == '' ]];then echo "Dependency genometools was not installed!";dependency_stat=0;fi 7 | 8 | hmmsearch=`which hmmsearch` 9 | if [[ ${hmmsearch} == '' ]];then echo "Dependency hmmsearch was not installed!";dependency_stat=0;fi 10 | 11 | cdhit=`which cd-hit-est` 12 | if [[ ${cdhit} == '' ]];then echo "Dependency cd-hit-est was not installed!";dependency_stat=0;fi 13 | 14 | mafft=`which mafft` 15 | if [[ ${mafft} == '' ]];then echo "Dependency mafft was not installed!";dependency_stat=0;fi 16 | 17 | blast=`which blastn` 18 | if [[ ${blast} == '' ]];then echo "Dependency blastn was not installed!";dependency_stat=0;fi 19 | 20 | bedtools=`which bedtools` 21 | if [[ ${bedtools} == '' ]];then echo "Dependency bedtools was not installed!";dependency_stat=0;fi 22 | 23 | dialign2=`which dialign2-2` 24 | if [[ ${dialign2} == '' ]];then echo "Dependency dialign2 was not installed!";dependency_stat=0;fi 25 | 26 | rnabob=`which rnabob` 27 | if [[ ${rnabob} == '' ]];then echo "Dependency rnabob was not installed!";dependency_stat=0;fi 28 | 29 | getorf=`which getorf` 30 | if [[ ${getorf} == '' ]];then echo "Dependency getorf was not installed!";dependency_stat=0;fi 31 | 32 | ## check R packages 33 | R_path=`which R` 34 | if [[ ${R_path} == '' ]]; 35 | then 36 | echo "R was not installed!" 37 | dependency_stat=0 38 | else 39 | rpack_stat=`Rscript check_rpack.r|grep "installed"` 40 | echo -e ${rpack_stat} 41 | if [[ ${rpack_stat} != '' ]];then dependency_stat=0;fi 42 | fi 43 | 44 | ## check python packages 45 | myPYTHON_PATH=`which python3` 46 | if [[ ${myPYTHON_PATH} == '' ]]; 47 | then 48 | echo "python3 was not installed!" 49 | dependency_stat=0 50 | else 51 | pypack_stat=`python3 check_pypack.py|grep "installed"` 52 | echo -e ${pypack_stat} 53 | if [[ ${pypack_stat} != '' ]];then dependency_stat=0;fi 54 | fi 55 | 56 | ## To summary dependecny status 57 | if [[ ${dependency_stat} == 0 ]]; 58 | then 59 | echo "Please make sure that these dependencies installed!" 60 | exit 0 61 | fi 62 | 63 | ## set pathes for heliano 64 | SCRIT_DIR_PATH=`pwd` 65 | 66 | BCHECK=${SCRIT_DIR_PATH}/heliano_bcheck.R 67 | FISHER=${SCRIT_DIR_PATH}/heliano_fisher.R 68 | HMMmodel=${SCRIT_DIR_PATH}/RepHel.hmm 69 | Headermodel=${SCRIT_DIR_PATH}/tclcv.txt 70 | SPLIT=${SCRIT_DIR_PATH}/SplitJoint.R 71 | SORT=${SCRIT_DIR_PATH}/Sort.sh 72 | 73 | cp heliano.py heliano 74 | 75 | sed -i "s|_INTERPRETERPYTHON_PATH_|${myPYTHON_PATH}|" heliano 76 | 77 | sed -i "s|_HMM_|${HMMmodel}|" heliano 78 | 79 | sed -i "s|_HEADER_|${Headermodel}|" heliano 80 | 81 | sed -i "s|_FISHER_|${FISHER}|" heliano 82 | 83 | sed -i "s|_BOUNDARY_|${BCHECK}|" heliano 84 | 85 | sed -i "s|_SPLIT_JOINT_|${SPLIT}|" heliano 86 | 87 | sed -i "s|_SORTPRO_|${SORT}|" heliano 88 | 89 | chmod 755 heliano 90 | 91 | ## set pathes for heliano_cons 92 | 93 | cp heliano_cons.py heliano_cons 94 | sed -i "s|_INTERPRETERPYTHON_PATH_|${myPYTHON_PATH}|" heliano_cons 95 | chmod 755 heliano_cons 96 | 97 | if [ ! -d "bin" ];then mkdir bin;fi 98 | mv heliano heliano_cons bin/ 99 | 100 | echo "Succeed! Please find programs in bin/ directory." 101 | 102 | 103 | 104 | -------------------------------------------------------------------------------- /SplitJoint.R: -------------------------------------------------------------------------------- 1 | ## This script was used to split big bed file into small bed files. 2 | library(bedtoolsr) 3 | library(parallel) 4 | 5 | ###set argument 6 | options(scipen = 200) 7 | 8 | args=commandArgs(T) 9 | left_beddir=args[1] 10 | right_beddir=args[2] 11 | combinid_file=args[3] 12 | subed_dir=args[4] 13 | Genome_size_file = args[5] 14 | HALF_DIST = as.numeric(args[6]) 15 | bedtools_path = args[7] 16 | # Set bedtools option 17 | options(bedtools.path = bedtools_path) 18 | 19 | ## multiple processing 20 | MAX_CPU_num = detectCores() -1 21 | CPU_num=as.numeric(args[8]) 22 | CPU_num = ifelse(CPU_num < MAX_CPU_num, CPU_num, MAX_CPU_num) 23 | CPU_num = ifelse(CPU_num<1, 1, CPU_num) 24 | 25 | 26 | if(F){ 27 | setwd('~/remote2/Helitron/Supplementary_material/TEverify/XL_is1020_sim90_s30_dn6k_heliano16_up0620/HLE1/') 28 | left_beddir='SubBlastnBed/HLE1_left/' 29 | right_beddir='SubBlastnBed/HLE1_right/' 30 | combinid_file='HLE1.combinid.txt' 31 | subed_dir='HLE1_Windowing' 32 | Genome_size_file = '../../Genome.size' 33 | HALF_DIST = 15000 34 | bedtools_path = '/home/zhenli/bioinfo/bedtools2/bin/' 35 | options(bedtools.path = bedtools_path) 36 | 37 | CPU_num=10 38 | } 39 | 40 | ## To make directory 41 | if(dir.exists(subed_dir)){ 42 | unlink(subed_dir,recursive = TRUE) 43 | } 44 | 45 | left_flank_dir=paste(subed_dir, 'leftflank', sep = '/') 46 | dir.create(left_flank_dir, recursive = TRUE) 47 | right_flank_dir=paste(subed_dir, 'rightflank', sep = '/') 48 | dir.create(right_flank_dir, recursive = TRUE) 49 | 50 | ## read genome size 51 | genome_size_df = read.csv2(Genome_size_file, sep = '\t', header = F, stringsAsFactors = F) 52 | colnames(genome_size_df)=c('chrmid', 'length') 53 | 54 | #### Output left bed file #### 55 | left_bedfile_list = list.files(left_beddir, full.names = T) 56 | 57 | cl = makeCluster(CPU_num) 58 | clusterExport(cl, c('left_flank_dir', 'genome_size_df', 'bedtools_path', 'HALF_DIST'), envir = .GlobalEnv) 59 | clusterEvalQ(cl, list(library(bedtoolsr), options(bedtools.path = bedtools_path, scipen = 200))) 60 | 61 | parSapply(cl, left_bedfile_list, function(x){ 62 | sub_leftbed = bt.sort(x) 63 | sub_leftbed = bt.merge(sub_leftbed, s=TRUE, d = 100, c="4,5,6", o="first,max,first") 64 | 65 | # To backup the real start point 66 | sub_leftbed$bk=ifelse(sub_leftbed$V6=='+', sub_leftbed$V2, sub_leftbed$V3) 67 | 68 | ## To extend bed files, but remove the terminal region. 69 | sub_leftbed$stop=ifelse(sub_leftbed$V6=='+', sub_leftbed$V3+HALF_DIST, sub_leftbed$V2) 70 | sub_leftbed$start=ifelse(sub_leftbed$V6=='+', sub_leftbed$V3, sub_leftbed$V2-HALF_DIST) 71 | sub_leftbed$start=ifelse(sub_leftbed$start<=0, 1, sub_leftbed$start) 72 | sub_leftbed=sub_leftbed[, c('V1', 'start', 'stop', 'V4', 'V5', 'V6', 'bk')] 73 | 74 | colnames(sub_leftbed)=c('chrmid', 'start', 'stop', 'name', 'score', 'strand', 'bk') 75 | sub_leftbed = merge(sub_leftbed, genome_size_df) 76 | sub_leftbed$stop = ifelse(sub_leftbed$stop <= sub_leftbed$length, sub_leftbed$stop, sub_leftbed$length) 77 | sub_leftbed = sub_leftbed[, c('chrmid', 'start', 'stop', 'name', 'score', 'strand', 'bk')] 78 | ## To output 79 | bnm=basename(x) 80 | sub_leftfile = paste(left_flank_dir, '/', bnm, sep = '') 81 | bt.sort(sub_leftbed, output = sub_leftfile) 82 | }) 83 | stopCluster (cl) 84 | 85 | #### Output right bed file#### 86 | right_bedfile_list = list.files(right_beddir, full.names = T) 87 | ## multiple processing 88 | cl = makeCluster(CPU_num) 89 | clusterExport(cl, c('right_flank_dir', 'genome_size_df', 'bedtools_path', 'HALF_DIST'), envir = .GlobalEnv) 90 | clusterEvalQ(cl, list(library(bedtoolsr), options(bedtools.path = bedtools_path, scipen = 200))) 91 | 92 | parSapply(cl, right_bedfile_list, function(x){ 93 | sub_rightbed = bt.sort(x) 94 | sub_rightbed = bt.merge(sub_rightbed, s=TRUE, d = 100, c="4,5,6", o="first,max,first") 95 | 96 | # To backup the real start point 97 | sub_rightbed$bk=ifelse(sub_rightbed$V6=='+', sub_rightbed$V3, sub_rightbed$V2) 98 | 99 | ## To extend bed files, but remove the original terminal regions 100 | sub_rightbed$stop=ifelse(sub_rightbed$V6=='+', sub_rightbed$V2, sub_rightbed$V3+HALF_DIST) 101 | sub_rightbed$start=ifelse(sub_rightbed$V6=='+', sub_rightbed$V2-HALF_DIST, sub_rightbed$V3) 102 | sub_rightbed$start=ifelse(sub_rightbed$start<=0, 1, sub_rightbed$start) 103 | sub_rightbed=sub_rightbed[, c('V1', 'start', 'stop', 'V4', 'V5', 'V6', 'bk')] 104 | 105 | colnames(sub_rightbed)=c('chrmid', 'start', 'stop', 'name', 'score', 'strand', 'bk') 106 | sub_rightbed = merge(sub_rightbed, genome_size_df, by='chrmid') 107 | sub_rightbed$stop = ifelse(sub_rightbed$stop <= sub_rightbed$length, sub_rightbed$stop, sub_rightbed$length) 108 | 109 | ## To output 110 | sub_rightbed = sub_rightbed[, c('chrmid', 'start', 'stop', 'name', 'score', 'strand', 'bk')] 111 | bnm=basename(x) 112 | sub_rightfile = paste(right_flank_dir, '/', bnm, sep = '') 113 | bt.sort(sub_rightbed, output = sub_rightfile) 114 | }) 115 | 116 | stopCluster (cl) 117 | ### To create file path file #### 118 | 119 | ## read combined id file 120 | leftname_list = sapply(left_bedfile_list, function(x){strsplit(basename(x), split = '\\.')[[1]][1]}) 121 | rightname_list = sapply(right_bedfile_list, function(x){strsplit(basename(x), split = '\\.')[[1]][1]}) 122 | combine_id=read.csv2(combinid_file, stringsAsFactors = F, header = F, sep = '\t') 123 | colnames(combine_id)=c('leftname', 'rightname') 124 | combine_id=combine_id[which(combine_id$leftname %in% leftname_list & combine_id$rightname %in% rightname_list), ] 125 | 126 | combine_id$leftname=paste(subed_dir, '/leftflank/', combine_id$leftname, '.bed',sep = '') 127 | combine_id$rightname=paste(subed_dir, '/rightflank/', combine_id$rightname, '.bed', sep = '') 128 | head(combine_id) 129 | write.table(combine_id, file = paste(subed_dir, '/', 'left_right.path.join', sep = ''), 130 | quote = F, sep="\t", col.names = F, row.names = F) -------------------------------------------------------------------------------- /tclcv.txt: -------------------------------------------------------------------------------- 1 | TCTCTACTA 2 | TCT.TACTA.T 3 | TCT.TACTAC 4 | TC.{2}TACTACT 5 | TCT.TAC.ACT 6 | TCT.TA.TACT 7 | TCT.TACT.CT 8 | TCT.T.CTACT 9 | TC.{1}CTACTA.T 10 | TC.{9}TATTAAG 11 | TC.{1}CTACTAC 12 | TCTCTA.TA.T 13 | TCTCTAC.AC 14 | TCTC.ACTA.T 15 | TCTCTA.TAC 16 | TCTC.AC.ACT 17 | TCT.TA.TATA 18 | TC.{5}TA.CTAT.A 19 | TC.{5}TA.C.ATTA 20 | TC.{8}CTAT.AAG 21 | TCT.TACTAA 22 | TC.{5}TATA.T.AA 23 | TCTCTA.TAA 24 | TCT.TA.TA.CT 25 | TC.{2}TA.TA.C.AT 26 | TC.{0,4}TA.TATAT 27 | TC.{6}TAT.TAT.A 28 | TC.{0,4}TATTAT.T 29 | TC.{0,4}TATTATA 30 | TC.{0,5}TATA.TAA 31 | TC.{0,3}TAT.TA.TA 32 | TCTAT.ATAT 33 | TC.{0,1}T.TTATAT 34 | TC.{5,8}T.TA.TAA.A 35 | TC.{0,5}TATA.TA.A 36 | TC.{0,2}T.TATTAT 37 | TC.{4,5}TA.T.TAT.A 38 | TCTAT.T.TA.A 39 | TC.{6}TAT.TATA 40 | TC.{3,5}CTAT.TAT 41 | TC.{0,2}T.TATCT.T 42 | TC.{2,7}TA.TAAAA 43 | TCTA.AT.TA.A 44 | TC.{5,9}TA.TAT.AA 45 | TC.{4,7}AT.TA.TAA 46 | TCTATATAT 47 | TCTATCTAT 48 | TCT.TATA.A.A 49 | TC.{7,8}ACTAAAA 50 | TC.{0,2}T.T.TCTAT 51 | TC.{2,3}TATATAC 52 | TC.{0,5}TATAC.AA 53 | TC.{1,6}ATA.TAAA 54 | TC.{3,5}TAC.A.T.AA 55 | TC.{3,4}A.AA.TAA.A 56 | TC.{4,9}AC.A.T.AAA 57 | TC.{5}C.A.T.AAAA 58 | TC.{0,3}TA.A.CTAA 59 | TC.{2,3}TA.A.CTA.A 60 | TC.{3,5}TA.AA.T.AA 61 | TC.{5,6}TA.TATA.A 62 | TC.{4,9}TATA.A.TT 63 | TC.{5}C.A.TAA.AA 64 | TC.{5,6}AA.TAAAA 65 | TC.{3,4}A.AA.TA.AA 66 | TC.{4,7}AC.A.TAAA 67 | TC.{6}T.TTATA.A 68 | TC.{12,17}AAA.A.TAA 69 | TC.{12,17}A.A.A.TAAA 70 | TC.{2,6}TA.TA.TA.A 71 | TC.{6}AT.AAA.TT 72 | TC.{2,7}CTA.AA.T.A 73 | TC.{1,5}TA.A.AT.AA 74 | TC.{1,5}T.T.TATA.A 75 | TCTCTAT.T.T 76 | TC.{7,9}TAT.TAT.A 77 | TC.{15,18}TATT.TA.A 78 | TC.{9,12}TATA.A.A.A 79 | TC.{22,26}AA.A.ATAA 80 | TC.{12,13}A.T.AAAA.A 81 | TC.{2,4}TA.TATTA 82 | TC.{7,12}T.T.TAT.AA 83 | TC.{9,11}TAT.T.AAA 84 | TC.{2,5}TA.T.AAA.A 85 | TC.{4,6}TA.ATT.TT 86 | TC.{5}TA.A.TT.AA 87 | TC.{2}TA.TA.TT.A 88 | TC.{36}TAATTTT 89 | TC.{10}AAA.C.CA.T 90 | TC.{8,13}T.TTATTA 91 | TC.{4,9}TT.T.CCTA 92 | TC.{24,28}ATTTTAA 93 | TC.{35}AT.TAT.T.T 94 | TC.{10,12}TTATA.TT 95 | TC.{21}ATTTTT.T 96 | TC.{19}AC.A.A.GAA 97 | TC.{35,37}TC.TT.GG.C 98 | TC.{1}CTAC.ACT 99 | TCTCTAC.A.T 100 | TC.{1}CTACT.CT 101 | TCTCT.CTA.T 102 | TC.{1}CTA.TACT 103 | TCTCT.C.ACT 104 | TCTCTACTA 105 | TC.{9}TATTAAG 106 | TCT.TACTAT 107 | TCT.TACTA.A 108 | TC.{5}TA.C.A.TAA 109 | TC.{8}CTATTAA 110 | TC.{2}TA.TATA.T 111 | TCT.TACTA.C 112 | TC.{3}A.TA.C.ATT 113 | TCTCTA.TAT 114 | TCTA.TATA.A 115 | TC.{0,2}TA.TAT.TA 116 | TCT.TTATA.A 117 | TC.{0,4}TATT.TAT 118 | TC.{1,4}AT.TA.TA.A 119 | TCTAT.ATA.A 120 | TC.{6}T.T.TATA.A 121 | TC.{0,4}TATTA.AT 122 | TC.{1,5}ATTATAT 123 | TCTATA.TA.T 124 | TC.{6}TAT.TA.A.A 125 | TC.{0,2}T.TA.TAT.T 126 | TC.{8}TCTATTA 127 | TC.{2,3}TTATATA 128 | TC.{8,10}TATTAA.A 129 | TC.{0,5}T.TA.TAAA 130 | TC.{5,6}T.T.TAT.AA 131 | TC.{2,5}T.AT.TA.TA 132 | TCTAT.AT.TA 133 | TCTAT.T.T.TA 134 | TC.{1}AT.TATTA 135 | TCTA.A.ATA.A 136 | TCTAT.TAT.T 137 | TC.{5}C.ACT.A.AA 138 | TC.{4}A.A.CTAAA 139 | TC.{3,4}A.AA.T.AAA 140 | TC.{7}A.T.AAAA.A 141 | TC.{2,3}TA.A.CT.AA 142 | TC.{8}CTA.AAAG 143 | TC.{7}A.TA.AAA.A 144 | TC.{3,5}TAC.A.TA.A 145 | TC.{3,5}TAC.A.TAA 146 | TC.{6}T.CTATA.A 147 | TC.{6,7}ACTA.AAA 148 | TC.{5}C.A.TA.AAA 149 | TC.{5,6}TA.TAT.AA 150 | TC.{8}CT.AAAA.A 151 | TC.{0,3}TAC.ACTA 152 | TC.{4,9}AC.A.TA.AA 153 | TC.{9}TATAAAG 154 | TC.{5,6}AA.TAAA.A 155 | TC.{12}AAAA.TAA 156 | TC.{2,5}CTAC.A.TA 157 | TC.{7,11}A.TAAA.A.A 158 | TC.{5}TT.CTA.A.A 159 | TCT.TATCT.T 160 | TC.{0,1}TCT.TCT.T 161 | TC.{2,6}TA.TA.AAA 162 | TC.{6}TA.T.TAAA 163 | TC.{3,6}TA.TA.T.AA 164 | TC.{5}T.T.AAA.TT 165 | TC.{1}TAT.TAT.A 166 | TC.{4,5}C.ACTA.AA 167 | TC.{2,5}CTA.TA.T.A 168 | TC.{1,5}T.T.TAT.AA 169 | TC.{11,15}A.AA.A.TAA 170 | TC.{2,3}TAC.AC.A.A 171 | TC.{5}TT.CTATA 172 | TC.{5}TT.CT.TA.A 173 | TC.{9,11}AAAAA.TA 174 | TC.{6}T.TTAT.AA 175 | TC.{1}AT.A.AAAA 176 | TC.{1,6}TA.TATAT 177 | TC.{8,9}TATATA.T 178 | TC.{9}TATA.AG.T 179 | TC.{5,9}TA.TATA.A 180 | TCTATA.TA.A 181 | TCTA.AT.TA.A 182 | TC.{1,4}ATA.TA.AA 183 | TC.{4,8}TATA.A.TT 184 | TC.{23}AAA.ATAA 185 | TC.{0,4}T.T.TACTA 186 | TC.{9}TATAT.AA 187 | TC.{2,4}TA.TA.TA.A 188 | TC.{2,4}TA.TAT.A.A 189 | TCTATA.TAA 190 | TC.{5}CT.TTATA 191 | TC.{4}TATA.AT.T 192 | TC.{1}CTAT.T.TA 193 | TC.{2}T.T.TCTA.T 194 | TC.{13}T.TATTAT 195 | TC.{1}ATA.TAA.A 196 | TC.{0,1}T.T.TATA.A 197 | TCTCTATCT 198 | TC.{6}TATTAT.T 199 | TC.{1}ATA.TAAA 200 | TC.{9,14}TATA.AAA 201 | TC.{0,3}TAT.TAT.T 202 | TC.{0,3}TAT.ATA.A 203 | TC.{7}CTTA.AAA 204 | TC.{2,6}CTAT.TAT 205 | TC.{5,9}TATTATA 206 | TC.{2,5}TA.TAT.AA 207 | TC.{6,8}TA.TA.T.AA 208 | TCT.TA.CTCT 209 | TC.{11}T.TCTA.TA 210 | TC.{6}TA.ATTTT 211 | TC.{1}CTATCT.T 212 | TC.{10,14}T.AAAAAA 213 | TC.{9,12}TAT.TA.A.A 214 | TC.{18,23}AAAA.TAA 215 | TC.{1}T.TATA.A.A 216 | TC.{2,4}TAT.ATTA 217 | TC.{1,5}ATA.TATT 218 | TC.{9,11}TAT.TA.TA 219 | TC.{9,10}AC.A.T.AAA 220 | TC.{0,4}T.T.TATCT 221 | TC.{10,15}TAAAAAA 222 | TC.{2,4}TATTAT.A 223 | TC.{10,14}T.T.AAA.TT 224 | TC.{2}TA.TA.TTA 225 | TC.{10,12}ATAT.AAA 226 | TC.{5,8}TATA.T.AA 227 | TC.{3,5}A.TA.T.AAA 228 | TC.{9,10}A.TA.TTA.A 229 | TC.{11,13}T.TATTA.A 230 | TC.{0,2}TA.TA.T.TA 231 | TC.{39}T.AAAAA.T 232 | TC.{2,5}T.A.AAAAT 233 | TC.{25}T.TAAA.A.A 234 | TC.{7,12}T.TAT.T.AA 235 | TC.{6,10}TATAAA.A 236 | TC.{0,1}TATATAC 237 | TCT.TA.CT.TA 238 | TC.{18,23}A.AA.TAA.A 239 | TC.{7,8}ATAT.A.A.A 240 | TC.{22,26}AA.AA.TAA 241 | TC.{9,12}ATAAA.A.A 242 | TC.{5}TATA.TT.A 243 | TC.{0,4}CTA.AA.T.A 244 | TC.{0,5}TA.AA.T.AA 245 | TC.{4}CTA.A.TT.A 246 | TC.{0,5}TA.C.TATA 247 | TC.{14}A.AAT.TCA 248 | TC.{9}TT.TT.CTA 249 | TC.{14,19}A.A.CTAAA 250 | TC.{4}CT.TA.TT.A 251 | TC.{1,2}AC.A.T.AAA 252 | TCT.TATT.AT 253 | TC.{7}AT.TTA.A.T 254 | TC.{23,24}CTAATT.T 255 | TC.{1}CTAAT.TT 256 | TC.{16}TA.AA.TAA 257 | TC.{10,12}AT.TT.TTA 258 | TC.{31}CC.TA.T.TT 259 | TC.{25}A.TA.C.ATT 260 | TC.{5,8}TA.AATT.A 261 | TC.{12,14}AAAG.TAA 262 | TC.{0,5}T.TT.TAAA 263 | TC.{8}T.TAT.T.TC 264 | TC.{2}CA.C.AAA.A 265 | TC.{38}T.T.TCT.TC 266 | TCC.TAAT.T.A 267 | TC.{0,5}TA.ATTT.T 268 | TC.{0,3}A.TA.TTA.A 269 | TC.{5,8}T.TT.TTAT 270 | TCC.TA.TAA.T 271 | TC.{5,10}AT.TT.TT.T 272 | TC.{28,31}CCC.ACTA 273 | TC.{10,11}A.T.TTAT.A 274 | TC.{6,10}TAT.TAT.T 275 | TC.{4,9}TT.TTCCT 276 | TC.{7,10}T.AT.C.CCA 277 | TC.{20}ACA.CTAA 278 | TC.{32}TACTA.AA 279 | TC.{28}CTAC.A.AT 280 | TC.{5,7}T.ATT.AAA 281 | TC.{1,5}A.TAAAAA 282 | TC.{10}TAAA.A.A.C 283 | TC.{22,25}T.ATT.TAA 284 | TC.{0,5}TAATTA.A 285 | TC.{5}TAT.A.A.AA 286 | TC.{28}AC.TAAA.C 287 | TC.{10,15}TAT.T.T.TA 288 | TC.{16}AATT.T.TA 289 | TC.{1,5}ACTA.AA.G 290 | TC.{0,1}TCTT.T.T.C 291 | TC.{24}T.T.TATT.A 292 | TC.{29}TT.TTATA 293 | TC.{6,10}ATAAT.CA 294 | TC.{34}CTAT.TAT 295 | TCCATAATA 296 | TC.{8,10}AC.CTT.TA 297 | TC.{37}AG.G.G.CCA 298 | TC.{21}ATTTTT.T 299 | TC.{35,37}TC.TT.G.CC 300 | TC.{34,37}A.CG.GGC.A 301 | TC.{33,36}ATTT.T.TA 302 | TC.{3,4}AA.A.CGA.T 303 | TC.{32}C.A.TA.CGA 304 | TC.{25}TAAA.A.AA 305 | -------------------------------------------------------------------------------- /heliano_cons.py: -------------------------------------------------------------------------------- 1 | #!_INTERPRETERPYTHON_PATH_ 2 | 3 | import os, re, subprocess, sys, argparse, shutil, random 4 | from Bio import SeqIO 5 | from multiprocessing.pool import ThreadPool 6 | from collections import defaultdict 7 | import pybedtools as BT 8 | 9 | class Consensus_making: 10 | def __init__(self, genome, wkdir, represent_bed, process_num): 11 | self.genome = genome 12 | self.genome_dict = SeqIO.parse(genome, 'fasta') 13 | self.genome_dict = {k.id: k.seq.upper() for k in self.genome_dict} 14 | self.process_num=int(process_num) 15 | self.wkdir = wkdir 16 | self.repsenbed = represent_bed 17 | if not os.path.exists(self.wkdir): 18 | os.mkdir(self.wkdir) 19 | os.chdir(self.wkdir) 20 | else: 21 | os.chdir(self.wkdir) 22 | 23 | self.genome_size = 'Genome.size' 24 | genome_size = [[i, len(self.genome_dict[i])] for i in self.genome_dict] 25 | genome_size = sorted(genome_size, key=lambda x: x[0]) 26 | with open(self.genome_size, 'w') as F: 27 | F.writelines([''.join([i[0], '\t', str(i[1]), '\n']) for i in genome_size]) 28 | 29 | def cdhitest_clust(self, input_fa): 30 | cons_name = '.'.join([input_fa, 'reduce.temp']) 31 | cluster_file = '.'.join([cons_name, 'clstr']) 32 | run_cluster = subprocess.Popen( 33 | ['cd-hit-est', '-i', input_fa, '-o', cons_name, '-d', '0', '-aS', '0.8', '-aL', '0.8', '-c', '0.8', '-G', '1', '-g', 34 | '1', '-b', '500', '-T', str(self.process_num), '-M', '0'], stdout=subprocess.DEVNULL) 35 | run_cluster.wait() 36 | 37 | cluster_dict = {} 38 | with open(cluster_file, 'r') as F: 39 | for line in F: 40 | if line.startswith('>'): 41 | cluster_name = line.strip('>\n').replace(' ', '_') 42 | else: 43 | insertion_name = line.split('...')[0].split(', >')[1] 44 | cluster_dict[insertion_name] = cluster_name 45 | 46 | if os.path.exists(cons_name): 47 | os.remove(cons_name) 48 | os.remove(cluster_file) 49 | reversed_cluster_dict = defaultdict(list) 50 | [reversed_cluster_dict[cluster_dict[key]].append(key) for key in cluster_dict] 51 | return reversed_cluster_dict 52 | 53 | def consencus(self, mfa): 54 | basename = os.path.basename(mfa).split('.')[0] 55 | ## need to cluster before making consensus 56 | cluster_dict = self.cdhitest_clust(mfa) #{pairname:[insertion1, insertion2, ...]} 57 | mfa_dict = SeqIO.parse(mfa, 'fasta') 58 | mfa_dict = {k.id: k.seq.upper() for k in mfa_dict} 59 | 60 | for pairname in cluster_dict: 61 | insertion_name_list = cluster_dict[pairname] 62 | if len(insertion_name_list) < 2: 63 | conseq = str(mfa_dict[insertion_name_list[0]]) 64 | self.consensus_dict[basename].append(conseq) 65 | continue 66 | 67 | submfa = ''.join(['Consensus/', basename, '.mfa']) 68 | subaln = ''.join([submfa, '.fa']) 69 | with open(submfa, 'w') as F: 70 | ## only first five insertions used for consensus making 71 | for insertion in insertion_name_list[:5]: 72 | F.write(''.join(['>', insertion, '\n', str(mfa_dict[insertion]), '\n'])) 73 | 74 | mul_aln_run = subprocess.Popen(['dialign2-2', '-n', '-fa', '-mask', submfa], 75 | stdout=subprocess.DEVNULL) 76 | mul_aln_run.wait() 77 | 78 | ## To remove non utf-8 codes 79 | with open(subaln, 'rb') as F: 80 | text = F.read().decode('utf-8', 'ignore') 81 | with open(subaln, 'w') as F: 82 | F.write(text) 83 | 84 | consensus_file = ''.join([submfa, '.con.fa']) 85 | consencus_task = subprocess.Popen(["cons", "-sequence", subaln, '-outseq', consensus_file], 86 | stdout = subprocess.DEVNULL) 87 | consencus_task.wait() 88 | 89 | consencus_seq = {} 90 | with open(consensus_file, 'r') as F: 91 | for line in F: 92 | if line.startswith('>'): 93 | key = line.strip('>\n') 94 | consencus_seq[key] = '' 95 | else: 96 | consencus_seq[key] += line.rstrip() 97 | #os.remove(consensus_file) 98 | #os.remove(subaln) 99 | conseq = list(consencus_seq.values())[0] 100 | conseq = re.findall('[ATCG]{5,}.*[ATCG]{5,}', conseq)[0].replace('n', '').replace('N', '').replace('*', '').replace('x', '') ## delete gap region 101 | self.consensus_dict[basename].append(conseq) 102 | 103 | def extract_seq(self, pairlist): 104 | subwkdir = 'Consensus' 105 | pairname = pairlist[0][3] 106 | pairfa = ''.join([subwkdir, '/', pairname, '.fa']) 107 | ## To extend both ends for 50 bp. 108 | distance = 50 109 | with open(pairfa, 'w') as PF: 110 | for line in pairlist: 111 | chrmid, start, stop, name, score, strand = line[:6] 112 | seq_start = int(start) - distance if int(start) - distance > 0 else 0 113 | seq_stop = int(stop) + distance 114 | seq = self.genome_dict[chrmid][seq_start-1:seq_stop] 115 | if strand == '+': 116 | PF.write(''.join(['>', chrmid, '-', str(seq_start), '-', str(seq_stop), '\n'])) 117 | PF.write(str(seq)) 118 | PF.write('\n') 119 | else: 120 | PF.write(''.join(['>', chrmid, '-', str(seq_start), '-', str(seq_stop), '\n'])) 121 | PF.write(str(seq.reverse_complement())) 122 | PF.write('\n') 123 | self.mfalist.append(pairfa) 124 | 125 | def main(self): 126 | sys.stdout.write('Begin to make consensus sequences.\n') 127 | subwkdir = 'Consensus/' 128 | if not os.path.exists(subwkdir): 129 | os.mkdir(subwkdir) 130 | else: 131 | shutil.rmtree(subwkdir) 132 | os.mkdir(subwkdir) 133 | representative_dict = defaultdict(list) 134 | with open(self.repsenbed, 'r') as F: 135 | for line in F: 136 | splitlines = line.rstrip().split('\t') 137 | representative_dict[splitlines[3]].append(splitlines) 138 | representative_list = [representative_dict[pairname] for pairname in representative_dict] 139 | 140 | ## To output the multiple sequences 141 | self.mfalist = [] 142 | planpool = ThreadPool(int(self.process_num)) 143 | for pairlist in representative_list: 144 | planpool.apply_async(self.extract_seq, args=(pairlist, )) 145 | planpool.close() 146 | planpool.join() 147 | 148 | self.consensus_dict = defaultdict(list) 149 | ## To make consensus sequences for each subfamily. 150 | planpool = ThreadPool(int(self.process_num)) 151 | for mfa in self.mfalist: 152 | opfile='' 153 | planpool.apply_async(self.consencus, args=(mfa, )) 154 | planpool.close() 155 | planpool.join() 156 | 157 | with open('RC.representative.cons.fa', 'w') as F: 158 | for name in self.consensus_dict: 159 | init = 1 160 | for seq in self.consensus_dict[name]: 161 | seqname = ''.join(['>', name, '.', str(init)]) 162 | F.write(''.join([seqname, '\n', seq, '\n'])) 163 | init += 1 164 | sys.stdout.write('Consensus sequences got constructed!.\n') 165 | 166 | 167 | if __name__ == "__main__": 168 | parser = argparse.ArgumentParser(description="Making consensus for Helitron-like sequences. Please visit https://github.com/Zhenlisme/heliano/ for more information. Email us: zhen.li3@universite-paris-saclay.fr") 169 | parser.add_argument("-g", "--genome", type=str, required=True, help="The genome file in fasta format.") 170 | parser.add_argument("-r", "--repsenbed", type=str, required=True, help="The representative bed file.") 171 | parser.add_argument("-o", "--opdir", type=str, required=True, help="The output directory.") 172 | parser.add_argument("-n", "--process", type=int, default=2, required=False, help="Maximum of threads to be used.") 173 | parser.add_argument("-v", "--version", action='version', version='%(prog)s 1.0.2') 174 | Args = parser.parse_args() 175 | makeconsenus = Consensus_making(os.path.abspath(Args.genome), os.path.abspath(Args.opdir), os.path.abspath(Args.repsenbed), Args.process) 176 | makeconsenus.main() 177 | 178 | -------------------------------------------------------------------------------- /heliano_fisher.R: -------------------------------------------------------------------------------- 1 | library(bedtoolsr) 2 | library(parallel) 3 | 4 | ###set argument##### 5 | args=commandArgs(T) 6 | bedtools_path = args[1] 7 | Genome_size = args[2] 8 | joint_bedpath_df=args[3] 9 | bed_opt=args[4] 10 | MAX_CPU_num = detectCores() -1 11 | CPU_num=as.numeric(args[5]) 12 | CPU_num = ifelse(CPU_num < MAX_CPU_num, CPU_num, MAX_CPU_num) 13 | CPU_num = ifelse(CPU_num<1, 1, CPU_num) 14 | PVALUE=as.numeric(args[6]) 15 | ORF_BED=args[7] 16 | Strategy=args[8] 17 | options(bedtools.path = bedtools_path) 18 | 19 | ##################### 20 | cluster_intervals <- function(bed_data, min_overlap = 0.8){ 21 | add_index = ncol(bed_data)+1 22 | row_number = nrow(bed_data) 23 | if(row_number<2){ 24 | bed_data[1,add_index]=1 25 | colnames(bed_data)[add_index]='cluster' 26 | return(bed_data) 27 | } 28 | ## Define overlap function ## 29 | overlap_percentage <- function(a_start, a_end, b_start, b_end) { 30 | overlap <- max(0, min(a_end, b_end) - max(a_start, b_start)) 31 | a_length <- a_end - a_start 32 | b_length <- b_end - b_start 33 | return(max(overlap / a_length, overlap / b_length)) 34 | } 35 | ## Finish of overlap function ## 36 | prev_interval = unlist(bed_data[1, ]) 37 | cluster_id=1 38 | prev_interval[add_index]=cluster_id 39 | clusters <- list(prev_interval) 40 | Merged_result = lapply(2:row_number, function(i){ 41 | curr_interval <- unlist(bed_data[i, ]) 42 | overlap <- overlap_percentage(as.numeric(prev_interval[2]), as.numeric(prev_interval[3]), 43 | as.numeric(curr_interval[2]), as.numeric(curr_interval[3])) 44 | if (overlap >= min_overlap & curr_interval[1] == prev_interval[1]) { 45 | prev_interval <<- c(curr_interval[1], prev_interval[2], 46 | pmax(as.numeric(prev_interval[3]), as.numeric(curr_interval[3]))) 47 | } else { 48 | prev_interval <<- curr_interval 49 | cluster_id <<- cluster_id+1 50 | } 51 | curr_interval[add_index]=cluster_id 52 | return(curr_interval) 53 | }) 54 | bed_data = as.data.frame(do.call('rbind', c(clusters, Merged_result)), stringsAsFactors=F) 55 | colnames(bed_data)[add_index]='cluster' 56 | return(bed_data) 57 | } 58 | 59 | Genome_size_df=read.csv2(Genome_size, stringsAsFactors = F, header = F, sep = '\t') 60 | joint_df = read.csv2(joint_bedpath_df, stringsAsFactors = F, header = F, sep = '\t') 61 | colnames(joint_df)=c('left', 'right') 62 | 63 | cl = makeCluster(CPU_num) 64 | clusterExport(cl, c('Genome_size_df', 'bedtools_path'), envir = .GlobalEnv) 65 | clusterEvalQ(cl, list(library(bedtoolsr), options(bedtools.path = bedtools_path))) 66 | 67 | significance_df = parApply(cl, joint_df, MARGIN = 1, function(x){ 68 | left_bed = read.csv2(x[1], stringsAsFactors = F, header = F, sep = '\t') 69 | right_bed = read.csv2(x[2], stringsAsFactors = F, header = F, sep = '\t') 70 | fisher_result = bt.fisher(a=left_bed, b=right_bed, g=Genome_size_df, nonamecheck = TRUE, m = TRUE, s = TRUE) 71 | pvalue=fisher_result$right 72 | return(c(x[1], x[2], pvalue)) 73 | }) 74 | 75 | stopCluster (cl) 76 | significance_df=t(significance_df) 77 | colnames(significance_df)=c('leftpath', 'rightpath', 'pvalue') 78 | significance_df=as.data.frame(significance_df, stringsAsFactors = F) 79 | significance_df$pvalue=as.numeric(significance_df$pvalue) 80 | write.table(significance_df, file = 'RawPvalue.txt', quote = F, sep="\t", col.names = F, row.names = F) 81 | 82 | significance_df=significance_df[which(significance_df$pvalue<=PVALUE), ] 83 | 84 | ## make joint and merge pvalue file 85 | cl = makeCluster(CPU_num) 86 | clusterExport(cl, c('bedtools_path', 'bed_opt', 'ORF_BED', 'cluster_intervals'), envir = .GlobalEnv) 87 | clusterEvalQ(cl, list(library(bedtoolsr), options(bedtools.path = bedtools_path))) 88 | 89 | if(Strategy=='1'){ 90 | if(length(rownames(significance_df))){ 91 | parApply(cl, significance_df, MARGIN = 1, function(x){ 92 | pvalue = x[3] 93 | window_df = bt.intersect(a=x[1], b=x[2], nonamecheck = TRUE, s=TRUE, wo=TRUE) 94 | if(length(rownames(window_df))>0){ 95 | Start = ifelse(window_df$V6=='+', window_df$V7, window_df$V14) 96 | Stop = ifelse(window_df$V6=='+', window_df$V14, window_df$V7) 97 | name=paste(window_df$V4, window_df$V11, sep = '-') 98 | Bitscore=(as.numeric(window_df$V5)+as.numeric(window_df$V12))/2 99 | window_df=data.frame(chrm=window_df$V1, start=Start, stop=Stop, 100 | combiname=name, count=1, strand=window_df$V6, 101 | pvalue=1, Bscore=Bitscore, stringsAsFactors=F) 102 | left_name = gsub('.bed', '', basename(x[1])) 103 | right_name = gsub('.bed', '', basename(x[2])) 104 | 105 | window_df = window_df[order(window_df$chrm, as.numeric(window_df$start)), ] 106 | ## Cluster intervals 107 | window_df = cluster_intervals(window_df, min_overlap = 0.8) 108 | ## To select the intervals with highest bitscore 109 | window_df = window_df[ave(window_df$Bscore, window_df$cluster, FUN = max) == window_df$Bscore, ] 110 | cluster_count = length(unique(window_df$cluster)) 111 | window_df$pvalue=pvalue 112 | window_df$count=cluster_count 113 | window_df$repalt='rep' 114 | window_df=window_df[, c(1:8, 10)] 115 | ##################### dedup function ############################ 116 | dedup_func = function(inpt_fisher_df){ 117 | intersection_df = bt.intersect(inpt_fisher_df, inpt_fisher_df, F=1, s=T, wo=T) 118 | 119 | ## To select the one who cover any other lines 120 | intersection_df = intersection_df[which(!(intersection_df$V2==intersection_df$V11 & intersection_df$V3==intersection_df$V12)), 121 | c(1:9)] 122 | intersection_df = unique(intersection_df) 123 | non_overlapped_bed = bt.intersect(inpt_fisher_df, intersection_df, wa=T, f=1, F=1, v=T, s=T) 124 | 125 | if(nrow(intersection_df)>0){ 126 | intersection_df$V9='alt' 127 | } 128 | final_opt = rbind(non_overlapped_bed, intersection_df) 129 | return(final_opt) 130 | } 131 | ################## Function end ################################ 132 | if(file.exists(ORF_BED)){ 133 | ORF_fisherpart = bt.intersect(window_df, ORF_BED, F=1, wa=T) 134 | nonauto_fisherpart = bt.intersect(window_df, ORF_BED, F=.5, wa=T, v = T) 135 | Auto_dedup = data.frame() 136 | Nonauto_dedup = data.frame() 137 | if(nrow(ORF_fisherpart)>0){ 138 | Auto_dedup = dedup_func(ORF_fisherpart) 139 | } 140 | if(nrow(nonauto_fisherpart>0)){ 141 | Nonauto_dedup = dedup_func(nonauto_fisherpart) 142 | } 143 | Dedup_df = rbind(Auto_dedup, Nonauto_dedup) 144 | 145 | }else{ 146 | Dedup_df = dedup_func(window_df) 147 | } 148 | filename=paste(bed_opt, '/',left_name, '-', right_name, '.bed', sep = '') 149 | write.table(Dedup_df, file = filename, quote = F, row.names = F, col.names = F, sep = '\t') 150 | } 151 | }) 152 | 153 | } 154 | }else{ 155 | if(length(rownames(significance_df))){ 156 | parApply(cl, significance_df, MARGIN = 1, function(x){ 157 | pvalue = x[3] 158 | window_df = bt.intersect(a=x[1], b=x[2], nonamecheck = TRUE, s=TRUE, wo=TRUE) 159 | if(length(rownames(window_df))>0){ 160 | Start = ifelse(window_df$V6=='+', window_df$V7, window_df$V14) 161 | Stop = ifelse(window_df$V6=='+', window_df$V14, window_df$V7) 162 | name=paste(window_df$V4, window_df$V11, sep = '-') 163 | Bitscore=(as.numeric(window_df$V5)+as.numeric(window_df$V12))/2 164 | window_df=data.frame(chrm=window_df$V1, start=Start, stop=Stop, 165 | combiname=name, count=1, strand=window_df$V6, 166 | pvalue=1, Bscore=Bitscore, stringsAsFactors=F) 167 | left_name = gsub('.bed', '', basename(x[1])) 168 | right_name = gsub('.bed', '', basename(x[2])) 169 | 170 | window_df = window_df[order(window_df$chrm, as.numeric(window_df$start)), ] 171 | ## Cluster intervals 172 | window_df = cluster_intervals(window_df, min_overlap = 0.8) 173 | ## To select the intervals with highest bitscore for each clusters 174 | window_df = window_df[ave(window_df$Bscore, window_df$cluster, FUN = max) == window_df$Bscore, ] 175 | cluster_count = length(unique(window_df$cluster)) 176 | window_df$pvalue=pvalue 177 | window_df$count=cluster_count 178 | window_df$repalt='rep' 179 | window_df=window_df[, c(1:8, 10)] 180 | filename=paste(bed_opt, '/',left_name, '-', right_name, '.bed', sep = '') 181 | write.table(window_df, file = filename, quote = F, row.names = F, col.names = F, sep = '\t') 182 | } 183 | }) 184 | 185 | } 186 | } 187 | 188 | 189 | stopCluster (cl) 190 | 191 | ## To filter out pairs whose sequences are similar. 192 | fisher_bedfilelist = list.files(bed_opt) 193 | 194 | cl = makeCluster(CPU_num) 195 | clusterExport(cl, c('bedtools_path', 'bed_opt'), envir = .GlobalEnv) 196 | clusterEvalQ(cl, list(library(bedtoolsr), options(bedtools.path = bedtools_path))) 197 | 198 | parSapply(cl, fisher_bedfilelist, function(x){ 199 | fisherbed_file = paste(bed_opt, '/', x, sep = '') 200 | split_list = strsplit(gsub('.bed', '', x),split = '-') 201 | leftname = split_list[[1]][1] 202 | rightname = split_list[[1]][2] 203 | classname = strsplit(leftname, split = '_left_')[[1]][1] 204 | left_blasnbed = paste('./SubBlastnBed/', classname, '_left/', leftname, '.bed', sep = '') 205 | right_blasnbed = paste('./SubBlastnBed/', classname, '_right/', rightname, '.bed', sep = '') 206 | left_bed = read.csv2(left_blasnbed, stringsAsFactors = F, header = F, sep = '\t') 207 | intersection_df = bt.intersect(a=left_blasnbed, b=right_blasnbed, nonamecheck = FALSE, s=FALSE, f=0.8) 208 | proportion = nrow(unique(intersection_df))/nrow(left_bed) 209 | if(proportion>=0.3){ 210 | file.remove(fisherbed_file) 211 | } 212 | }) 213 | stopCluster (cl) 214 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | [![Anaconda Version](https://anaconda.org/zhenlisme/heliano/badges/version.svg)](https://anaconda.org/zhenlisme/heliano/) 2 | [![Anaconda Version](https://img.shields.io/conda/vn/Bioconda/heliano.svg)](https://anaconda.org/bioconda/heliano) 3 | [![Anaconda Version](https://anaconda.org/zhenlisme/heliano/badges/latest_release_relative_date.svg)](https://anaconda.org/zhenlisme/heliano/) 4 | [![Anaconda Version](https://anaconda.org/zhenlisme/heliano/badges/platforms.svg)](https://anaconda.org/zhenlisme/heliano/) 5 | [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](./LICENSE) 6 | 7 | # HELIANO: A fast and accurate tool for detection of Helitron-like elements. 8 | Helitron-like elements (HLE1 and HLE2) are DNA transposons. They have been found in diverse species and seem to play significant roles in the evolution of host genomes. Although known for over twenty years, Helitron sequences are still challenging to identify. Here, we propose HELIANO (Helitron-like elements annotator) as an efficient solution for detecting Helitron-like elements. Please check [wiki](https://github.com/Zhenlisme/heliano/wiki/1.-Home) for detailed usage. 9 | 10 | # Table of contents 11 | - [Update Note](#Update-Note) 12 | - [Dependencies](#dependencies) 13 | - [Installation](#installation) 14 | * [conda](#conda) 15 | * [mamba](#mamba) 16 | * [Manual installation](#manual-installation) 17 | - [Usage](#usage) 18 | - [Test run](#Perform-a-test-run-of-HELIANO) 19 | - [Making Consensus](#Generation-for-consensus-sequences) 20 | - [Dis-denovo prediction](#Dis-denovo-prediction) 21 | - [References](#References) 22 | - [FAQ](#Frequently-asked-questions) 23 | - [Release history](#Release-history) 24 | - [To contact us](#to-contact-us) 25 | 26 | # Update Note: 27 | 1) Since version 1.1.0, HELIANO will use the term HLE1 to refer to the canonical Helitron (called Helitron in v1.0.2) and the term HLE2 to refer to the non-canonical Helitrons (called HLE2 in v1.0.2). 28 | See figure below: 29 | 30 | 31 | 32 | 2) From version 1.1.0, users are allowed to input a pair file as a complementary for LTS-RTS pair information. This will help a lot in searching for HLEs in close species. For more information, see [here](#Dis-denovo-prediction). 33 | # Dependencies 34 | ``` 35 | - python = 3.9.0 36 | - r-base = 4.1 37 | - biopython 38 | - pybedtools = 0.9.0 =py39hd65a603_2 39 | - r-bedtoolsr 40 | - r-seqinr = 4.2_16 = r41h06615bd_0 41 | - bedtools = 2.30.0 42 | - dialign2 = 2.2.1 43 | - mafft 44 | - cd-hit = 4.8.1 45 | - blast = 2.2.31 46 | - emboss = 6.6.0 47 | - hmmer = 3.3.2 48 | - genometools-genometools = 1.6.2 = py39h58cc16e_6 49 | - rnabob = 2.2.1 50 | ``` 51 | # Installation 52 | ## mamba (Recommendation) 53 | If mamba is not installed on your system, you can install it with the following commands easily. 54 | ``` 55 | wget "https://github.com/conda-forge/miniforge/releases/latest/download/Mambaforge-$(uname)-$(uname -m).sh" 56 | bash Mambaforge-$(uname)-$(uname -m).sh -b 57 | ``` 58 | Then you can install HELIANO with mamba. 59 | ``` 60 | #create the HELIANO environment 61 | mamba create -n HELIANO 62 | #activate the HELIANO environment 63 | mamba activate HELIANO 64 | # install 65 | mamba install zhenlisme::HELIANO -c conda-forge -c bioconda 66 | mamba deactivate 67 | ``` 68 | ## conda 69 | ``` 70 | #create the HELIANO environment 71 | conda create -n HELIANO 72 | #activate the HELIANO environment 73 | conda activate HELIANO 74 | # installation 75 | conda install zhenlisme::HELIANO -c conda-forge -c bioconda 76 | conda deactivate 77 | ``` 78 | ## manual installation 79 | Before installation, you need to be sure that all dependencies have been installed on your computer and that their path are defined in your environmental variables. All dependencies could be installed via conda/mamba. 80 | 1. download the latest HELIANO package. 81 | `git clone https://github.com/Zhenlisme/HELIANO.git` 82 | 2. switch to the source code dorectory that you cloned at the last step. 83 | `cd HELIANO/` 84 | 3. run configure file. 85 | `bash configure.sh` 86 | 4. You can find HELIANO in the bin directory. 87 | # Usage 88 | ### Activate the HELIANO conda environment (for conda/mamba installation) 89 | `conda activate HELIANO` 90 | ### Perform a test run of HELIANO 91 | ##### Here we will use the chromosome 18 of Fusarium oxysporum strain Fo5176 as an example, where you can find it in file test.fa . 92 | Perform the following code: 93 | `heliano -g test.fa -is1 0 -is2 0 -o test_opt -w 15000` 94 | ### HELIANO outputs 95 | You will find two main result files when HELIANO program runs successfully. 96 | 1. RC.representative.bed: the predicted HLE1/HLE2 coordinates in bed format (available in the file test.opt.tbl in this repository). 97 | 2. RC.representative.fa: the predicted HLE1/HLE2 sequences in fasta format. 98 | 3. pairlist.tbl: The file for LTS-RTS pair information. 99 | Other files or directories are intermediate outputs. 100 | 1. TIR_count.tbl: Table for counts of terminal inverted repeats of each HLE subfamily. 101 | 2. Boundary.tbl: Table for the conservation of flanking regions of each HLE subfamily. 102 | 3. HLE1/ or HLE2/: Directory for intermediate files when detecting HLE1/HLE2. 103 | ##### Explanation for RC.representative.bed 104 | There are 11 columns in RC.representative.bed file: 105 | |chrm-id|start|end|subfamily|occurence|strand|pvalue|TS_blastn_identity|variant|type|name| 106 | | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | 107 | |CP128282.1|53617|59046|HLE2_left_18-HLE2_right_18|7|-|6.3390e-07|60|HLE2|auto|insertion_HLE2_auto_1| 108 | |CP128282.1|83425|88824|HLE2_left_18-HLE2_right_18|7|-|6.3390e-07|60|HLE2|auto|insertion_HLE2_auto_2| 109 | |CP128282.1|94525|99924|HLE2_left_18-HLE2_right_18|7|+|6.3390e-07|60|HLE2|auto|insertion_HLE2_auto_3| 110 | |CP128282.1|306838|312276|HLE2_left_18-HLE2_right_18|7|+|6.3390e-07|60|HLE2|auto|insertion_HLE2_auto_4| 111 | ##### Detailed explaination for each column. 112 | Notice: The insertions that encode Rep/helicase are considered putative autonomous HLEs. 113 | |Columns|Explaination| 114 | | ---- | ---- | 115 | |chrm-id|chromosome id| 116 | |start|start site of HLE| 117 | |stop|stop site of HLE| 118 | |subfamily|heliano classification| 119 | |occurence|how often this subfamily occurred in genome| 120 | |strand|the insertion is on which strand| 121 | |pvalue|pvalue of fisher's exact test, indicating the significance of the prediction. The lower, the more significant.| 122 | |TS_blastn_identity|the average identity of RTS and LTS to their representative counterparts| 123 | |variant|the insertion is HLE1 or HLE2| 124 | |type|the mobility of HLE, either autonomous (auto) or nonautonomous (nonauto)| 125 | |name|unique identifier for each insertion| 126 | ### Generation for consensus sequences 127 | The HELIANO package also provides a program (heliano_cons) for generating consensus sequences of HLE. 128 | Check the usage of heliano_cons: 129 | `heliano_cons -h` 130 | ``` 131 | usage: heliano_cons [-h] -g GENOME -r REPSENBED -o OPDIR [-n PROCESS] [-v] 132 | 133 | Making consensus for Helitron-like sequences. Please visit https://github.com/Zhenlisme/heliano/ for more information. Email us: zhen.li3@universite-paris-saclay.fr 134 | 135 | optional arguments: 136 | -h, --help show this help message and exit 137 | -g GENOME, --genome GENOME 138 | The genome file in fasta format. 139 | -r REPSENBED, --repsenbed REPSENBED 140 | The representative bed file (RC.representative.bed). 141 | -o OPDIR, --opdir OPDIR 142 | The output directory. 143 | -n PROCESS, --process PROCESS 144 | Maximum of threads to be used. 145 | -v, --version show program's version number and exit 146 | ``` 147 | ### Dis-denovo prediction 148 | Since version 1.1.0, HELIANO enables prediction of HLEs with the help of pre-identified LTS-RTS pair file. 149 | The `pairlist.tbl` can be either obtained from the main directory of your previous run or user-defined. 150 | 151 | You can skip the denovo prediction of the LTS-RTS pair process (will save a lot of time), 152 | ``` 153 | heliano -g test.fa -is1 0 -is2 0 -o test_opt -w 15000 -ts pairlist.tbl --dis_denovo 154 | ``` 155 | Or not skip the de novo prediction of the LTS-RTS process 156 | ``` 157 | heliano -g test.fa -is1 0 -is2 0 -o test_opt -w 15000 -ts pairlist.tbl 158 | ``` 159 | # References 160 | ### If you find HELIANO useful to you, please cite: 161 | Li Z , Gilbert C , Peng H , Pollet N. "Discovery of numerous novel Helitron-like elements in eukaryote genomes using HELIANO." Nucleic Acids Research, 2024. [doi: doi.org/10.1093/nar/gkae679](https://doi.org/10.1093/nar/gkae679). 162 | 163 | Li Z , Pollet N. "HELIANO: a Helitron-like element annotator." Zenodo (2024). [doi: 10.5281/zenodo.10625239](https://doi.org/10.5281/zenodo.10625239) 164 | 165 | # Frequently asked questions 166 | ### 1. How to get fragmented copies of HLEs? 167 | HELIANO is designed to predict complete insertions of Helitron-like elements (HLE), with the limitation that fragmented insertions will not be reported. To identify fragmented insertions, we recommend running RepeatMasker or BLASTN using HELIANO predictions as the query. Before you run RepeatMasker or BLASTN, we suggest masking the HLE query with a trusted non-HLE TE database because other non-HLE TEs might insert into long HLEs, which would inflate sequence length and result in misannotation. 168 | ### 2. How to choose parameters properly? 169 | For a precise and quick search, you can use the stringent parameter '-is1 1 -is2 1 -p 1e-5 -s 30 -pt 1 -sim_tir 100' that considers the preferred insertion sites of HLE. For big or complex genomes (e.g., the maize genome), I just recommend you use the stringent parameter set. But not all HLEs obey their regular preferred insertion sites. If you want to explore more in your interested genome, you can use the loose parameter set, e.g., '-is1 0 -is2 0 -sim_tir 90', and you will have more predictions and a longer execution time. Note that the parameters '-is2' and '-sim_tir' are only for HLE2s, and '-is1' and '-pt' are only for Helitrons. 170 | # Release history 171 | ### [v1.0.1](https://github.com/Zhenlisme/heliano/releases/tag/v1.0.1) 172 | Initial version 173 | ### [v1.0.2](https://github.com/Zhenlisme/heliano/releases/tag/v1.0.2) 174 | Fixed some bugs 175 | ### [v1.1.0](https://github.com/Zhenlisme/heliano/releases/tag/v1.1.0) 176 | 1. Replace the term Helitron with HLE1 and Helentron with HLE2. 177 | 2. Enable to prediction of HLEs based on a pre-identified LTS-RTS pair file. (see -ts and --dis_denovo parameters) 178 | 3. Add a new parameter that allows an auto HLE to have multiple terminal sequences. (see '--multi_ts' parameter) 179 | ### [v1.2.0](https://github.com/Zhenlisme/heliano/releases/tag/v1.2.0) 180 | 1. Add parameter '--nearest' that allows users to find terminal pairs whose LTS and RTS are closest to each other. By default, HELIANO will try to find the furthest pairs. 181 | 2. Add parameter '-dn' that allows users to define the length of nonautonomous HLEs. By default (dn 0), HELIANO will deduce it automatically. 182 | ### [v1.2.1](https://github.com/Zhenlisme/heliano/releases/tag/v1.2.1) 183 | Add the '-flank_sim' parameter, which allows users to set the cut-off to define false positive LTS/RTS. The lower the value, the more stringent. This value was set to 0.7 in previous versions, but it is now set to 0.5 by default. 184 | ### [v1.3.1](https://github.com/Zhenlisme/heliano/releases/tag/v1.3.1) 185 | 1. Resolve the hmmsearch error issue. 186 | 2. Add that "--table" parameter that allows users to adjust the genetic code of test organisms. 187 | 3. Optimize the LTS/RTS selection. When there are alternative terminal sequences on the same autonomous locus, try to use the one with a higher blastn score. 188 | 189 | # To contact us 190 | For any questions, please open an issue in [the issues section](https://github.com/Zhenlisme/heliano/issues) or send me an email to zhen.li3@universite-paris-saclay.fr. 191 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . -------------------------------------------------------------------------------- /heliano.py: -------------------------------------------------------------------------------- 1 | #!_INTERPRETERPYTHON_PATH_ 2 | 3 | import os, re, subprocess, sys, argparse, shutil, random, gc 4 | from Bio import SeqIO 5 | from multiprocessing.pool import ThreadPool 6 | from collections import defaultdict 7 | import pybedtools as BT 8 | 9 | """ 10 | This program is supposed to detect and classify different variants of Helitron-like elements: HLE1 and HLE2. Please follow the homepage of this software for more information: https://github.com/Zhenlisme/heliano. 11 | """ 12 | 13 | # define Structure_search class for motif identification, including stem loop and terminal inverted repeats. 14 | class Structure_search: 15 | def __init__(self, genome, START=0): 16 | self.START = int(START) 17 | self.genome = genome 18 | self.genome_dict = SeqIO.parse(genome, 'fasta') 19 | self.genome_dict = {k.id: k.seq.upper() for k in self.genome_dict} 20 | self.maximum_length = sorted([len(self.genome_dict[i]) for i in self.genome_dict])[-1] 21 | 22 | def stem_loop(self, stem_loop_description, minus_tailone=1): 23 | ## Function to find hairpin structures. Start coord is 1 not 0 24 | rnabobopt = ''.join([os.path.basename(self.genome), '.stemloop.txt']) 25 | with open(rnabobopt, 'w') as rnabf: 26 | rnabob_program = subprocess.Popen(["rnabob", "-c", "-q", "-F", "-s", stem_loop_description, self.genome], 27 | stderr=subprocess.DEVNULL, stdout=rnabf) 28 | rnabob_program.wait() 29 | if not os.path.exists(rnabobopt): 30 | return [] 31 | stem_loop_loc = [] 32 | 33 | complement_dict = {'A': "T", "T": "A", "G": "C", "C": "G", 34 | "K": "M", "M": "K", "Y": "R", "R": "Y", "S": "S", "W": "W", 35 | "B": "V", "V": "B", "H": "D", "D": "H", "N": "N", "X": "X"} 36 | 37 | with open(rnabobopt, 'r') as F: 38 | for line in F: 39 | line = line.strip() 40 | if re.match('\d', line): 41 | splitline = re.split('\s+', line)[:3] 42 | chrid = splitline[2] 43 | ## To avoid rnabob bugs 44 | if int(splitline[1]) < 0: 45 | print(splitline) 46 | continue 47 | ## positive strand 48 | if int(splitline[0]) < int(splitline[1]): 49 | strand = '+' 50 | length = int(splitline[1]) - int(splitline[0]) + 1 51 | start = int(splitline[0]) + self.START 52 | end = start + length - 1 53 | end = end - 1 if minus_tailone else end ## To remove the T nucleotide 54 | ## negative strand 55 | else: 56 | strand = '-' 57 | length = int(splitline[0]) - int(splitline[1]) + 1 58 | start = int(splitline[0]) + self.START - length + 1 59 | end = start + length - 1 60 | start = start + 1 if minus_tailone else start ## To remove the T nucleotide 61 | else: 62 | seq = line.strip('|').split('|') 63 | helix_seq1, loop_seq, helix_seq2, tail_seq = seq 64 | stem_len = len(helix_seq1) 65 | loop_len = len(loop_seq) 66 | ## To revise the rnabob output. rnabob sometimes does not return as long as possible of helix. need to revise it. 67 | midpoint = int(len(loop_seq) / 2) 68 | for i in range(midpoint): 69 | ## if the left nucleotide is reverse-complementary to the right nucleotide 70 | if loop_seq[i] == complement_dict[loop_seq[-i - 1]]: 71 | stem_len += 1 72 | loop_len -= 2 73 | # The loop should exist. 74 | if loop_len >= 1: 75 | stem_loop_loc.append([chrid, str(start), str(end), str(stem_len), str(loop_len), strand]) 76 | os.remove(rnabobopt) 77 | stem_loop_loc = sorted(stem_loop_loc, key=lambda x: [x[0], int(x[1])]) 78 | return stem_loop_loc 79 | 80 | def regularexpression_match(self, pattern, strand='+'): 81 | ## Use helitronscanner lcv file to detect terminal region of helitron 82 | coord_record = [] 83 | for chrm in self.genome_dict: ## start coord is 1 not 0 84 | if strand == '+': 85 | genom_seq = str(self.genome_dict[chrm]).upper() 86 | pCT_start_list = re.finditer(pattern, genom_seq) 87 | for p_coord in pCT_start_list: 88 | start = str(p_coord.start() + self.START + 1) 89 | end = str(p_coord.end() + self.START) 90 | coord_record.append([chrm, start, end]) 91 | else: 92 | genom_seq = str(self.genome_dict[chrm].reverse_complement()).upper() 93 | sequence_length = len(genom_seq) 94 | pCT_start_list = re.finditer(pattern, genom_seq) 95 | for p_coord in pCT_start_list: 96 | end = str(sequence_length - p_coord.start() + self.START) 97 | start = str(sequence_length - p_coord.end() + self.START + 1) 98 | coord_record.append([chrm, start, end]) 99 | coord_record = sorted(coord_record, key=lambda x: [x[0], int(x[1])]) 100 | return coord_record 101 | 102 | def inverted_detection(self, sequencefile, minitirlen, maxtirlen, mintirdist, maxtirdist, seed): 103 | ## start coord is 1 not 0 104 | dbname = ''.join([os.path.basename(sequencefile), '.invdb']) 105 | invttirfile = ''.join([os.path.basename(sequencefile), '.inv.txt']) 106 | ## build database 107 | mkinvdb = subprocess.Popen( 108 | ['gt', 'suffixerator', '-db', sequencefile, '-indexname', dbname, '-mirrored', '-dna', '-suf', '-lcp', 109 | '-bck'], stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL) 110 | mkinvdb.wait() 111 | ## run tirvish 112 | with open(invttirfile, 'w') as invf: 113 | runinvsearch = subprocess.Popen( 114 | ['gt', 'tirvish', '-index', dbname, '-mintirlen', str(minitirlen), '-maxtirlen', str(maxtirlen), 115 | '-similar', str(Args.simtir), '-mintirdist', str(mintirdist), '-maxtirdist', str(maxtirdist), '-mintsd', '0', 116 | '-seed', str(seed), '-vic', '1', '-overlaps', 'all', '-xdrop', '0'], stderr=subprocess.DEVNULL, stdout=invf) 117 | runinvsearch.wait() 118 | invt_list = [] 119 | ## The default output is in gff format, extract coord information and do filteration. 120 | with open(invttirfile, 'r') as F: 121 | for line in F: 122 | if line.startswith('#'): 123 | continue 124 | splitlines = line.rstrip().split('\t') 125 | if splitlines[2] == 'repeat_region': 126 | chrmid = splitlines[0] 127 | id = splitlines[8].replace('ID=', '') 128 | t = 1 129 | elif splitlines[2] == 'terminal_inverted_repeat_element': 130 | sim = re.findall('tir_similarity=(\d+\.\d+)', splitlines[8])[0] 131 | elif splitlines[2] == 'terminal_inverted_repeat': 132 | if t == 1: 133 | left_start = str(int(splitlines[3]) + self.START) 134 | left_end = str(int(splitlines[4]) + self.START) 135 | left_expand = '-'.join([left_start, left_end]) 136 | invt_length_left = int(splitlines[4]) - int(splitlines[3]) + 1 137 | t += 1 138 | else: 139 | right_start = str(int(splitlines[3]) + self.START) 140 | right_end = str(int(splitlines[4]) + self.START) 141 | right_expand = '-'.join([right_start, right_end]) 142 | invt_length_right = int(splitlines[4]) - int(splitlines[3]) + 1 143 | ## length of inverted sequences should be greater than 11 and shorter than 18 144 | if invt_length_left >= 12 and invt_length_right >= 12 and invt_length_left <= 17 and invt_length_right <= 17: 145 | invt_list.append([chrmid, str(left_start), str(right_end), left_expand, right_expand, 146 | (invt_length_right + invt_length_left) / 2, sim]) 147 | 148 | invt_list = sorted(invt_list, key=lambda x: int(x[1])) 149 | os.remove(invttirfile) 150 | os.system('rm %s*' % dbname) 151 | return invt_list 152 | 153 | # define Homologous_search class to find Helitron-like transposase domain and theri auto/non-auto relatives 154 | class Homologous_search: 155 | def __init__(self, rep_hel_hmm, genome, wkdir, headerfile, window, distance_domain, distance_na, pvalue, process_num, codetable): 156 | self.rep_hel_hmm = rep_hel_hmm 157 | self.genome = genome 158 | self.genome_dict = SeqIO.parse(genome, 'fasta') 159 | self.genome_dict = {k.id: k.seq.upper() for k in self.genome_dict} 160 | self.process_num = int(process_num) 161 | self.wkdir = wkdir 162 | self.headerpatternfile = headerfile 163 | self.window = window 164 | self.distance_domain = distance_domain 165 | self.distance_na = defaultdict(lambda :int(distance_na)) 166 | self.pvalue = float(pvalue) 167 | self.cutoff_flank = float(Args.flank_sim) 168 | if Args.terminal_sequence: 169 | self.pairfile = os.path.abspath(Args.terminal_sequence) 170 | sys.stdout.write('You added the pairfile %s.\n' % self.pairfile) 171 | if not os.path.isfile(self.pairfile): 172 | sys.stderr.write("Error: The pair list file doesn't exist, please check!\n") 173 | exit(0) 174 | # To transform the header file to regular expression. 175 | with open(headerfile, 'r') as F: 176 | headerpattern_list = F.read().rstrip().split('\n') 177 | self.headerpattern = '|'.join(headerpattern_list) if not Args.IS1 else '|'.join([''.join(['A', i]) for i in headerpattern_list]) 178 | #self.headerpattern = ''.join(['(?=(', self.headerpattern, '))']) 179 | if not os.path.exists(self.wkdir): 180 | os.mkdir(self.wkdir) 181 | os.chdir(self.wkdir) 182 | else: 183 | sys.stderr.write('Error: Directory %s exists. Please change!\n' % self.wkdir) 184 | exit(0) 185 | 186 | ## To check the pair list file 187 | self.terminalfile_dict = defaultdict(lambda: defaultdict(dict)) 188 | self.prepair_dict = defaultdict(list) 189 | if Args.terminal_sequence: 190 | pairdict = defaultdict(list) 191 | with open(self.pairfile, 'r') as F: 192 | for line in F: 193 | splitline = line.rstrip().split('\t') 194 | pairdict[splitline[0]].append(splitline[1:]) 195 | pairdir = 'Pre_pair/' 196 | if not os.path.exists(pairdir): 197 | os.mkdir(pairdir) 198 | for classname in pairdict: 199 | leftfile = os.path.abspath(''.join([pairdir, classname, '.left.pre.fa'])) 200 | rightfile = os.path.abspath(''.join([pairdir, classname, '.right.pre.fa'])) 201 | self.terminalfile_dict[classname]['left'] = leftfile 202 | self.terminalfile_dict[classname]['right'] = rightfile 203 | recorder_dict = {} 204 | with open(leftfile, 'w') as left_w, open(rightfile, 'w') as right_w: 205 | for line in pairdict[classname]: 206 | leftname, leftseq, rightname, rightseq = line 207 | leftname, rightname = ''.join([leftname, 'pre']), ''.join([rightname, 'pre']) 208 | ## To avoid repeatly writing 209 | if leftname not in recorder_dict: 210 | left_w.write(''.join(['>', leftname, '\n', leftseq, '\n'])) 211 | if rightname not in recorder_dict: 212 | right_w.write(''.join(['>', rightname, '\n', rightseq, '\n'])) 213 | self.prepair_dict[leftname].append(rightname) 214 | recorder_dict[leftname] = 1 215 | recorder_dict[rightname] = 1 216 | 217 | if Args.dis_denovo: 218 | if not self.terminalfile_dict: 219 | sys.stderr.write('Error: The pair list file is either not specified or empty. See parameter "-ts".\n') 220 | exit(0) 221 | else: 222 | sys.stdout.write( 223 | 'You will not search for the terminal structures of HLE in a de-novo way, but by using the pair file: %s.\n' % self.pairfile) 224 | self.bedtoolstmp = os.path.abspath('BedtoolsTMP') 225 | if not os.path.exists(self.bedtoolstmp): 226 | os.mkdir(self.bedtoolstmp) 227 | BT.set_tempdir(self.bedtoolstmp) 228 | 229 | CWD = os.getcwd() 230 | self.genome_size = '%s/Genome.size' % CWD 231 | self.chrm_size = {i:len(self.genome_dict[i]) for i in self.genome_dict} 232 | genome_size = list(self.chrm_size.items()) 233 | genome_size = sorted(genome_size, key=lambda x: x[0]) 234 | with open(self.genome_size, 'w') as F: 235 | F.writelines([''.join([i[0], '\t', str(i[1]), '\n']) for i in genome_size]) 236 | 237 | ## To determine the evalue for short-sequence blastn, set the bit-score cutoff as 30, the evalue cutoff should follow the formula: m*n/(2**30) 238 | sum_genomesize = sum([i[1] for i in genome_size]) 239 | self.evalue_blastn = sum_genomesize * 30 / (2 ** int(Args.score)) 240 | 241 | # To define stem_loop structure ending with CTRR motif of Helitron 242 | self.CTRR_stem_loop_description = '%s/CTRR_stem_loop.descr' % CWD 243 | CTRR_description = """r1 s1 r1' s2\nr1 1:1 NNNNN[10]:[10]NNNNN TGCA\ns1 0 N[7]\ns2 0 N[15]CTRR%s\n""" 244 | # Add 'T' in the end if user limitted the 'A-T' insertion site for Helitron. 245 | CTRR_description = CTRR_description % 'T' if Args.IS1 else CTRR_description % '' 246 | with open(self.CTRR_stem_loop_description, 'w') as F: 247 | F.write(CTRR_description) 248 | 249 | # To define stem_loop structure of HLE2 250 | self.subtir_description = '%s/subtir_stem_loop.descr' % CWD 251 | # Add 'T' in the end if user limitted the 'T-T' insertion site for HLE2. 252 | if Args.IS2: 253 | subtir_description = """r1 s1 r1' s2\nr1 1:1 NNNNN[10]:[10]NNNNN TGCA\ns1 0 N[15]\ns2 0 NNNNN[10]T\n""" 254 | else: 255 | subtir_description = """r1 s1 r1' s2\nr1 1:1 NNNNN[10]:[10]NNNNN TGCA\ns1 0 N[15]\ns2 0 NNNNNN[2]\n""" 256 | with open(self.subtir_description, 'w') as F: 257 | F.write(subtir_description) 258 | 259 | dbdir = 'GenomeDB/' 260 | if not os.path.exists(dbdir): 261 | os.mkdir(dbdir) 262 | self.genomedb = ''.join([CWD, '/', dbdir, os.path.basename(self.genome), '.blastndb']) 263 | makeblastndb = subprocess.Popen(['makeblastdb', '-dbtype', 'nucl', '-in', self.genome, '-out', self.genomedb], 264 | stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL) 265 | makeblastndb.wait() 266 | 267 | ## code table 268 | code_table_dict = {0: (0, "Standard"), 1: (6, "Ciliate Macronuclear and Dasycladacean"), 269 | 2: (15, "Blepharisma Macronuclear"), 3: (22, "Scenedesmus obliquus")} 270 | self.codetable = code_table_dict[codetable] 271 | sys.stdout.write('You are using the (%s) code to predict ORFs.\n' % self.codetable[1]) 272 | def hmmsearch(self, subgenome): 273 | # Run hmmersearch program to search for Helitron-like transposase 274 | orf_file = ''.join([subgenome, '.orf']) 275 | hmm_opt = ''.join([subgenome, '.hmmsearch.out']) 276 | 277 | #The index of getorf output starts from 1, not 0 278 | # Use getorf to predicte open reading frames for a given genome 279 | get_orf = subprocess.Popen(['getorf', '-sequence', subgenome, '-outseq', orf_file, '-minsize', '100', 280 | '-maxsize', '30000', '-table', str(self.codetable[0])], 281 | stderr=subprocess.DEVNULL) 282 | get_orf.wait() 283 | 284 | Rep_dict, Hel_dict = defaultdict(list), defaultdict(list) 285 | Rep_opline, Hel_opline = [], [] 286 | if os.path.getsize(orf_file): 287 | run_hmmsearch = subprocess.Popen( 288 | ['hmmsearch', '--domtblout', hmm_opt, '--noali', '-E', '1e-3', self.rep_hel_hmm, orf_file], 289 | stdout=subprocess.DEVNULL) 290 | run_hmmsearch.wait() 291 | os.remove(orf_file) 292 | else: 293 | return Rep_opline, Hel_opline 294 | if not os.path.exists(hmm_opt): 295 | return Rep_opline, Hel_opline 296 | 297 | # To parser hmmsearch output 298 | with open(hmm_opt, 'r') as F: 299 | for line in F: 300 | if line.startswith('#'): 301 | continue 302 | splitlines = re.split('\s+', line.rstrip()) 303 | domain, sub_class = splitlines[3].split('_') 304 | subchrname = "_".join(splitlines[0].split('_')[:-1]) 305 | chrm_name, START = subchrname.split('startat') 306 | start, end = re.findall('\[(\d+)\s+-\s+(\d+)\]', line)[0] 307 | start = str(int(start) + int(START)) 308 | end = str(int(end) + int(START)) 309 | 310 | aa_start, aa_end = splitlines[19:21] 311 | score = splitlines[7] 312 | c_evalue, i_evalue = splitlines[11:13] 313 | if float(c_evalue) > 1e-5 or float(i_evalue) > 1e-5: 314 | continue 315 | ## To transform amino acide coord to nucleotide coord 316 | if int(end) > int(start): 317 | strand = '+' 318 | nuc_start = int(aa_start) * 3 - 3 + int(start) 319 | nuc_end = int(aa_end) * 3 + int(start) - 1 320 | orf_loc = '-'.join([start, end]) 321 | else: 322 | nuc_end = int(start) - 3 * int(aa_start) + 3 323 | nuc_start = int(start) - 3 * int(aa_end) + 1 324 | strand = '-' 325 | orf_loc = '-'.join([end, start]) 326 | if domain.startswith('Hel'): 327 | Hel_dict[splitlines[0]].append( 328 | [chrm_name, str(nuc_start), str(nuc_end), sub_class, score, strand, orf_loc]) 329 | else: 330 | Rep_dict[splitlines[0]].append( 331 | [chrm_name, str(nuc_start), str(nuc_end), sub_class, score, strand, orf_loc]) 332 | for key in Hel_dict: 333 | hel_candidate = sorted(Hel_dict[key], key=lambda x: float(x[4]))[-1] ## Select the case with highest score. 334 | Hel_opline.append(hel_candidate) 335 | for key in Rep_dict: 336 | rep_candidate = sorted(Rep_dict[key], key=lambda x: float(x[4]))[-1] ## Select the case with highest score. 337 | Rep_opline.append(rep_candidate) 338 | try: 339 | Hel_bed = BT.BedTool([BT.create_interval_from_list(line) for line in Hel_opline]).sort() 340 | Rep_bed = BT.BedTool([BT.create_interval_from_list(line) for line in Rep_opline]).sort() 341 | return Rep_bed, Hel_bed 342 | except: 343 | return [], [] 344 | 345 | def intersect(self, location1, location2, slip=0, lportion=0.0, rportion=0.0, bool_and=1): 346 | # Define intersect function to check if two intervals are intersected or not, similar to bedtools intersect 347 | location1 = sorted([int(i) for i in location1]) 348 | location2 = sorted([int(i) for i in location2]) 349 | if location1[0] - slip > location2[1] or location1[1] < location2[0] - slip: 350 | return False 351 | else: 352 | total_list = sorted([location1[0], location1[1], location2[0], location2[1]]) 353 | portion1 = (total_list[2] - total_list[1] + 1) / ( 354 | location1[1] - location1[0] + 1) ## how much proportion the intersected sequence occupiedonseq1 355 | portion2 = (total_list[2] - total_list[1] + 1) / ( 356 | location2[1] - location2[0] + 1) ## how much proportion the intersected sequence occupiedonseq2 357 | if bool_and: 358 | if portion1 >= lportion and portion2 >= rportion: 359 | return True 360 | else: 361 | return False 362 | else: 363 | if portion1 >= lportion or portion2 >= rportion: 364 | return True 365 | else: 366 | return False 367 | 368 | def merge_bedfile(self, BedInput, window=1500): 369 | # Define function to merge two distance-close genomic features 370 | cluster_bed = BedInput.cluster(d=window, s=True) 371 | merge_dict = defaultdict(list) 372 | merge_list = [] 373 | for line in cluster_bed: 374 | line = list(line) 375 | cluster = line[-1] 376 | merge_dict[cluster].append(line[:-1]) 377 | 378 | for cluster in merge_dict: 379 | ## To record the domain location. 380 | coordlist = merge_dict[cluster] 381 | coord_set = [int(i[1]) for i in coordlist] 382 | coord_set.extend([int(i[2]) for i in coordlist]) 383 | coord_set = sorted(coord_set) 384 | start = coord_set[0] 385 | stop = coord_set[-1] 386 | strand = coordlist[0][5] 387 | ## To determain sub_class, select the case with highest score 388 | sub_class = sorted(coordlist, key=lambda x: float(x[4]))[-1][3] 389 | ## To merge the ORF location 390 | orf_list = sorted([int(b) for i in coordlist for b in i[-1].split('-')]) 391 | orf_coord = '-'.join([str(orf_list[0]), str(orf_list[-1])]) 392 | chrm_id = coordlist[0][0] 393 | merge_list.append([chrm_id, str(start), str(stop), sub_class, orf_coord, strand]) 394 | # merge_list = sorted(merge_list, key=lambda x: [x[0], int(x[1])]) 395 | if merge_list: 396 | merge_bed = BT.BedTool([BT.create_interval_from_list(line) for line in merge_list]).sort() 397 | return merge_bed 398 | else: 399 | return 0 400 | 401 | def parser_hmmsearch(self, Rep_bed, Hel_bed, subgenome): 402 | # To find Rep-Hel structure which might imply a possible Helitron-like transposases. 403 | if not Rep_bed or not Hel_bed: 404 | return [] 405 | 406 | ## To merge helicase or rep domain splicing sites (helitron-like transposase contain introns) 407 | merge_hel = self.merge_bedfile(Hel_bed, window=1500) 408 | merge_rep = self.merge_bedfile(Rep_bed, window=1500) 409 | if not merge_hel or not merge_rep: ## Either hel or rep data is null 410 | return [] 411 | 412 | ## To find rep and helicase gene pairs that rep is less than self.distance_domain bp upstream of hel 413 | joint_rephel = merge_rep.window(merge_hel, l=0, r=int(self.distance_domain), sm=True, sw=True) 414 | bedlist = [] 415 | for line in joint_rephel: 416 | splitlines = list(line) 417 | strand = splitlines[5] 418 | chrm = splitlines[0] 419 | rep_start, rep_end = splitlines[1:3] 420 | hel_start, hel_end = splitlines[7:9] 421 | 422 | # If the helicase and rep domain have a intersection, skip 423 | if self.intersect([int(rep_start), int(rep_end)], [int(hel_start), int(hel_end)], lportion=0.2, rportion=0.2): 424 | continue 425 | rep_orf = splitlines[4].split('-') 426 | hel_orf = splitlines[10].split('-') 427 | loc = sorted([rep_start, rep_end, hel_start, hel_end], key=lambda x: int(x)) 428 | start, end = loc[0], loc[-1] ## They are REP and Helicase domain region 429 | bedlist.append((chrm, int(start), int(end), '-'.join([rep_start, rep_end]), '-'.join([hel_start, hel_end]), 430 | strand, splitlines[3], splitlines[9], 'NA')) 431 | bedlist = list(set(bedlist)) ## To avoid duplicates 432 | bedlist = sorted(bedlist, key=lambda x: [x[0], x[1]]) 433 | return bedlist 434 | 435 | def heltentron_terminal(self, helentron_bed): 436 | # Define function to try to recover Helentron terminal region (stem-loop structure) which is behind the right part of TIRs 437 | extend_seq = [] 438 | opbed_list = [] 439 | extend_file = ''.join([helentron_bed, '.fa']) 440 | extend_dict = {} 441 | extend_dict = defaultdict(list) 442 | ## To output all extend rigions into one single file 443 | #init_num = 1 444 | with open(helentron_bed, 'r') as F: 445 | for line in F: 446 | feature = line.rstrip().split('\t') 447 | chrmid, start, stop, name, score, strand, pvalue, Bscore, classname, mobile_type, insertion_name = feature 448 | start, stop = int(start), int(stop) 449 | if float(Bscore) == 0: ## without terminal signals 450 | opbed_list.append([chrmid, str(start), str(stop), name, score, strand, pvalue, Bscore, classname, mobile_type, insertion_name]) 451 | continue 452 | 453 | if strand == '+': 454 | extend_id = '-'.join([chrmid, str(start), str(stop), 'p']) 455 | if '.2' not in classname: 456 | detect_seq = str(self.genome_dict[chrmid][stop: stop + 80]) 457 | StemStart = stop 458 | else: ## Helentron.2, the stem loop is at 5'end 459 | terminal_start = 0 if start - 80 < 0 else start - 80 460 | detect_seq = str(self.genome_dict[chrmid][terminal_start: start]) 461 | StemStart = terminal_start 462 | ## To remove short seequence 463 | if len(detect_seq) < 17: 464 | continue 465 | ## To remove N rich seq 466 | N_count = detect_seq.count('N') 467 | if N_count >= 5: 468 | continue 469 | ## The last element is the initial start for terminal detection region 470 | extend_dict[extend_id].append([chrmid, str(start), str(stop), name, score, strand, pvalue, Bscore, 471 | classname, mobile_type, insertion_name, StemStart]) 472 | extend_seq.append(''.join(['>', extend_id, '\n', detect_seq, '\n'])) 473 | else: 474 | extend_id = '-'.join([chrmid, str(start), str(stop), 'n']) 475 | if '.2' not in classname: 476 | terminal_start = 0 if start - 80 < 0 else start - 80 477 | detect_seq = str(self.genome_dict[chrmid][terminal_start: start]) 478 | StemStart = terminal_start 479 | else: ## Helentron.2, the stem loop is at 3'end 480 | detect_seq = str(self.genome_dict[chrmid][stop: stop + 80]) 481 | StemStart = stop 482 | ## To remove short seequence 483 | if len(detect_seq) < 17: 484 | continue 485 | ## To remove N rich seq 486 | N_count = detect_seq.count('N') 487 | if N_count >= 5: 488 | continue 489 | ## The last element is the initial start for terminal detection region 490 | extend_dict[extend_id].append([chrmid, str(start), str(stop), name, score, strand, pvalue, Bscore, 491 | classname, mobile_type, insertion_name, StemStart]) 492 | extend_seq.append(''.join(['>', extend_id, '\n', detect_seq, '\n'])) 493 | if not extend_seq: ## means empty 494 | return helentron_bed 495 | with open(extend_file, 'w') as F: 496 | F.writelines(extend_seq) 497 | ## stem loop detection 498 | stem_loop_list = Structure_search(extend_file, START=0).stem_loop(self.subtir_description, minus_tailone=int(Args.IS2)) 499 | stem_loop_dict = defaultdict(list) 500 | [stem_loop_dict[i[0]].append(i) for i in stem_loop_list] 501 | 502 | ## To select the nearest candidate 503 | for extend_id in stem_loop_dict: 504 | for sublist in extend_dict[extend_id]: 505 | chrmid, start, stop, name, score, strand, pvalue, Bscore, classname, mobile_type, insertion_name, e_start = sublist 506 | if extend_id.endswith('p'): 507 | stem_loop = [i for i in stem_loop_dict[extend_id] if i[5] == '+'] 508 | ## order by start position (closer), stem length (longer), loop length (shorter), total length (shorter) 509 | if '.2' not in classname: 510 | stem_loop = sorted(stem_loop, key = lambda x: [x[0], int(x[1]), -int(x[3]), int(x[4]), int(x[2]) - int(x[1])]) 511 | if stem_loop: 512 | stem_start, stem_stop = stem_loop[0][1:3] 513 | stem_stop = int(stem_stop) + int(e_start) 514 | opbed_list.append([chrmid, start, str(stem_stop), name, score, strand, 515 | pvalue, Bscore, classname, mobile_type, insertion_name]) 516 | else: 517 | stem_loop = sorted(stem_loop, key=lambda x: [x[0], -int(x[2]), -int(x[3]), int(x[4]), int(x[2]) - int(x[1])]) 518 | if stem_loop: 519 | stem_start, stem_stop = stem_loop[0][1:3] 520 | stem_start = int(stem_start) + int(e_start) 521 | opbed_list.append([chrmid, str(stem_start), stop, name, score, strand, 522 | pvalue, Bscore, classname, mobile_type, insertion_name]) 523 | if not stem_loop: 524 | opbed_list.append([chrmid, start, stop, name, score, strand, pvalue, Bscore, classname, mobile_type, insertion_name]) 525 | continue 526 | else: 527 | stem_loop = [i for i in stem_loop_dict[extend_id] if i[5] == '-'] 528 | ## order by end position (longer), stem length (longer), loop length (shorter), total length (shorter) 529 | if '.2' not in classname: 530 | stem_loop = sorted(stem_loop, key=lambda x: [x[0], -int(x[2]), -int(x[3]), int(x[4]), int(x[2]) - int(x[1])]) 531 | if stem_loop: 532 | stem_start, stem_stop = stem_loop[0][1:3] 533 | stem_start = int(stem_start) + int(e_start) 534 | opbed_list.append([chrmid, str(stem_start), stop, name, score, strand, 535 | pvalue, Bscore, classname, mobile_type, insertion_name]) 536 | else: 537 | stem_loop = sorted(stem_loop, key=lambda x: [x[0], int(x[1]), -int(x[3]), int(x[4]), 538 | int(x[2]) - int(x[1])]) 539 | if stem_loop: 540 | stem_start, stem_stop = stem_loop[0][1:3] 541 | stem_stop = int(stem_stop) + int(e_start) 542 | opbed_list.append([chrmid, start, str(stem_stop), name, score, strand, 543 | pvalue, Bscore, classname, mobile_type, insertion_name]) 544 | if not stem_loop: 545 | opbed_list.append([chrmid, start, stop, name, score, strand, pvalue, Bscore, classname, mobile_type, insertion_name]) 546 | continue 547 | ### To complement the candidates whose stem loop signal doesn't exist. 548 | remained_cases = set(extend_dict.keys()) - set(stem_loop_dict.keys()) 549 | for key in remained_cases: 550 | for sublist in extend_dict[key]: 551 | opbed_list.append(sublist[:11]) 552 | ### To creat bedtools objective 553 | #opbed = BT.BedTool([BT.create_interval_from_list(line) for line in opbed_list]) 554 | with open(helentron_bed, 'w') as F: 555 | F.write('\n'.join(['\t'.join(line) for line in opbed_list])) 556 | F.write('\n') 557 | os.remove(extend_file) 558 | 559 | def intergrated_program(self, subgenome): 560 | # This function is used to recover terminal signals of Helitron-like elements (TIRs for HLE2; TC... motif and ...CTRR motif for Helitron) 561 | rep_hmmsearch_opt, hel_hmmsearch_opt = self.hmmsearch(subgenome) 562 | ORF_list = self.parser_hmmsearch(rep_hmmsearch_opt, hel_hmmsearch_opt, subgenome) 563 | sys.stdout.write('Find %s rep-hel blocks in %s.\n' % (str(len(ORF_list)), os.path.basename(subgenome).replace('.fa', ''))) 564 | RC_total_candidate = [] 565 | for Helitron_candidate in ORF_list: 566 | ORF_chrmid = Helitron_candidate[0] 567 | ORF_start = int(Helitron_candidate[1]) 568 | ORF_stop = int(Helitron_candidate[2]) 569 | rep_loc = Helitron_candidate[3] 570 | hel_loc = Helitron_candidate[4] 571 | strand = Helitron_candidate[5] 572 | chrm_limit = len(self.genome_dict[ORF_chrmid]) 573 | rep_name, hel_name = Helitron_candidate[6:8] 574 | 575 | ## To decide class name 576 | if hel_name == 'HLE1' and rep_name == 'HLE1': 577 | classname = 'HLE1' 578 | elif hel_name == 'HLE2' and rep_name == 'HLE2': 579 | classname = 'HLE2' 580 | else: 581 | classname = '_or_'.join([rep_name, hel_name]) 582 | ## To produce orf id which will be used as sole identifier of terminal signals. 583 | ORFID = '-'.join([ORF_chrmid, str(ORF_start), str(ORF_stop)]) 584 | 585 | ## To decide to run denovo structural search or not. if not, just save the ORFs 586 | if Args.dis_denovo: 587 | RC_total_candidate.append( 588 | (ORF_chrmid, str(ORF_start), str(ORF_stop), strand, classname, (), (), ORFID)) 589 | continue 590 | 591 | temp_name_for_helitron = '-'.join([ORF_chrmid, str(ORF_start), str(ORF_stop)]) 592 | expansion_all_seqname = ''.join([temp_name_for_helitron, '.expansion.fa']) 593 | left_seqname = ''.join([temp_name_for_helitron, '.left.fa']) 594 | right_seqname = ''.join([temp_name_for_helitron, '.right.fa']) 595 | 596 | # Define regions to search for terminal signals 597 | left_boundary = ORF_start - self.window 598 | right_boundary = ORF_stop + self.window 599 | 600 | ## left and right boundary should be within chromosome ranges 601 | if left_boundary <= 0: 602 | left_boundary = 1 603 | if right_boundary >= chrm_limit: 604 | right_boundary = chrm_limit 605 | 606 | ## To avoid get big tandem heltron-like elements 607 | Helitron_candidate_index = ORF_list.index(Helitron_candidate) 608 | # Left boundary should not touch last Rep-Hel region 609 | if Helitron_candidate_index >= 1: ## not the fist one 610 | last_candidate = ORF_list[Helitron_candidate_index - 1] 611 | last_stop = last_candidate[2] 612 | left_boundary = last_stop if left_boundary < last_stop else left_boundary 613 | # Right boundary should not touch the next Rep-Hel region 614 | if Helitron_candidate_index < len(ORF_list) - 1: ## not the last one 615 | next_candidate = ORF_list[Helitron_candidate_index + 1] 616 | next_start = next_candidate[1] 617 | right_boundary = next_start if right_boundary > next_start else right_boundary 618 | 619 | # To output extended sequences to fasta files 620 | left_seq = str(self.genome_dict[ORF_chrmid][left_boundary - 1: ORF_start]) 621 | right_seq = str(self.genome_dict[ORF_chrmid][ORF_stop: right_boundary]) 622 | expansion_all_seq = str(self.genome_dict[ORF_chrmid][left_boundary - 1: right_boundary]) 623 | with open(expansion_all_seqname, 'w') as F: 624 | F.write(''.join(['>', ORF_chrmid, '\n', expansion_all_seq, '\n'])) 625 | with open(left_seqname, 'w') as F: 626 | F.write(''.join(['>', ORF_chrmid, '\n', left_seq, '\n'])) 627 | with open(right_seqname, 'w') as F: 628 | F.write(''.join(['>', ORF_chrmid, '\n', right_seq, '\n'])) 629 | 630 | # Candiadte is Helitron, try to search for left terminal signals in left extension and right terminal signals in right extension. 631 | if classname == 'HLE1': 632 | if strand == '+': 633 | # left terminal signals are TC... like 634 | TC_list = Structure_search(genome=left_seqname, START=left_boundary - 1).regularexpression_match(self.headerpattern, '+') 635 | # right terminal signals are stem-loop structures ending with CTRR motif. 636 | Stem_loop_list = Structure_search(genome=right_seqname, START=ORF_stop).stem_loop( 637 | self.CTRR_stem_loop_description, minus_tailone=int(Args.IS1)) 638 | Stem_loop_list = [i for i in Stem_loop_list if i[-1] == '+'] ## To select the positive strand motif 639 | # To reduce one if user set 'AT' insertion because the A was added at the begaining of header regular expression 640 | if Args.IS1: 641 | TC_list = [[line[0], str(int(line[1])+1), line[2]] for line in TC_list] 642 | else: 643 | TC_list = Structure_search(genome=right_seqname, START=ORF_stop).regularexpression_match( 644 | self.headerpattern, '-') 645 | Stem_loop_list = Structure_search(genome=left_seqname, START=left_boundary - 1).stem_loop( 646 | self.CTRR_stem_loop_description, minus_tailone=int(Args.IS1)) 647 | Stem_loop_list = [i for i in Stem_loop_list if i[-1] == '-'] ## To select the negative strand motif 648 | if Args.IS1: 649 | TC_list = [[line[0], line[1], str(int(line[2]) - 1)] for line in TC_list] 650 | RC_total_candidate.append(( 651 | ORF_chrmid, str(ORF_start), str(ORF_stop), strand, classname, tuple(TC_list), 652 | tuple(Stem_loop_list), ORFID)) 653 | 654 | # Candidate is HLE2 655 | else: 656 | # Size of terminal inverted sequences should be greater than the size of predicted transposase 657 | mini_dist_tir = ORF_stop - ORF_start 658 | # Size of terminal inverted sequences should be less than the size of extension 659 | max_dist_tir = 2 * int(self.window) + ORF_stop - ORF_start 660 | 661 | invt_list = Structure_search(genome=expansion_all_seqname, START=left_boundary - 1).inverted_detection( 662 | expansion_all_seqname, 9, 20, mini_dist_tir, max_dist_tir, 8) 663 | ## To keep the case that fully covered with ORF region 664 | invt_list = [i for i in invt_list if int(i[3].split('-')[1]) - ORF_start <= 0 and int(i[4].split('-')[0]) - ORF_stop >= 0] 665 | left_list, right_list = [], [] 666 | for inv in invt_list: 667 | if strand == '+': 668 | left_loc = inv[3].split('-') 669 | right_loc = inv[4].split('-') 670 | if Args.IS2: 671 | is_start = int(left_loc[0]) - 2 ## To get the insertion site index. The real index starts from 1, need to transform to python index. 672 | is_seq = str(self.genome_dict[ORF_chrmid][is_start:is_start+1]).upper() 673 | if is_seq == 'T': 674 | left_list.append((ORF_chrmid, int(left_loc[0]), int(left_loc[1]))) 675 | right_list.append((ORF_chrmid, int(right_loc[0]), int(right_loc[1]))) 676 | else: 677 | left_list.append((ORF_chrmid, int(left_loc[0]), int(left_loc[1]))) 678 | right_list.append((ORF_chrmid, int(right_loc[0]), int(right_loc[1]))) 679 | else: 680 | left_loc = inv[4].split('-') 681 | right_loc = inv[3].split('-') 682 | if Args.IS2: 683 | is_start = int(left_loc[1]) 684 | is_seq = str(self.genome_dict[ORF_chrmid][is_start:is_start + 1]).upper() 685 | if is_seq == 'A': ## The complementary of T is A 686 | left_list.append((ORF_chrmid, int(left_loc[0]), int(left_loc[1]))) 687 | right_list.append((ORF_chrmid, int(right_loc[0]), int(right_loc[1]))) 688 | else: 689 | left_list.append((ORF_chrmid, int(left_loc[0]), int(left_loc[1]))) 690 | right_list.append((ORF_chrmid, int(right_loc[0]), int(right_loc[1]))) 691 | RC_total_candidate.append((ORF_chrmid, str(ORF_start), str(ORF_stop), strand, classname, 692 | tuple(left_list), tuple(right_list), ORFID)) 693 | os.remove(expansion_all_seqname) 694 | os.remove(left_seqname) 695 | os.remove(right_seqname) 696 | return RC_total_candidate 697 | 698 | def cdhitest_clust(self, input_fa, opfile, helitron_type, id=0.8): 699 | # This function is for clustering of highly identity sequences 700 | cons_name = '.'.join([helitron_type, 'reduce.temp']) 701 | cluster_file = '.'.join([cons_name, 'clstr']) 702 | run_cluster = subprocess.Popen( 703 | ['cd-hit-est', '-i', input_fa, '-o', cons_name, '-d', '0', '-aS', '0.8', '-c', str(id), '-G', '1', '-g', 704 | '1', '-b', '500', '-T', str(self.process_num), '-M', '0'], stdout=subprocess.DEVNULL) 705 | run_cluster.wait() 706 | 707 | # To get classification information 708 | cluster_dict = {} 709 | with open(cluster_file, 'r') as F: 710 | for line in F: 711 | if line.startswith('>'): 712 | cluster_name = '_'.join([helitron_type, line.strip('>\n').split(' ')[1]]) 713 | else: 714 | insertion_name = line.split('...')[0].split(', >')[1] 715 | cluster_dict[insertion_name] = cluster_name 716 | 717 | opseq = '' 718 | with open(cons_name, 'r') as F: 719 | for line in F: 720 | if line.startswith(">"): 721 | insertion_name = line.strip('>\n') 722 | cluster_name = cluster_dict[insertion_name] 723 | opseq += ''.join(['>', cluster_name, '\n']) 724 | else: 725 | opseq += line 726 | with open(opfile, 'w') as F: 727 | F.write(opseq) 728 | if os.path.exists(cons_name): 729 | os.remove(cons_name) 730 | os.remove(cluster_file) 731 | cluster_file = '.'.join([helitron_type, 'clust.info2']) 732 | with open(cluster_file, 'w') as F: 733 | F.writelines(["".join([k, "\t", cluster_dict[k], '\n']) for k in cluster_dict]) 734 | return cluster_dict 735 | 736 | def split_list(self, numbers, num_groups): 737 | # Calculate target sum for each group 738 | total_sum = sum([i[1] for i in numbers]) 739 | target_sum = total_sum / num_groups 740 | 741 | # Sort numbers in descending order 742 | numbers = sorted(numbers, key=lambda x: -x[1]) 743 | # Split numbers into groups with similar sums 744 | groups = [[] for i in range(num_groups)] 745 | group_sums = [0] * num_groups 746 | for number in numbers: 747 | # Find the group with the smallest current sum and add the number to it 748 | min_sum_index = group_sums.index(min(group_sums)) 749 | groups[min_sum_index].append(number) 750 | group_sums[min_sum_index] += number[1] 751 | return groups 752 | 753 | def split_genome(self, chunk_size=200000000, flanking_size=50000, num_groups=2): 754 | # To split big genomes into small chunks 755 | if not os.path.exists('genomes'): 756 | os.mkdir('genomes') 757 | subgenome_list = [] 758 | for chrm in self.genome_dict: 759 | seq_len = len(self.genome_dict[chrm]) 760 | if seq_len < 1000: ##Skip chrms whose length is shorter than 1000 bp 761 | sys.stdout.write( 762 | "Chrm %s will not be used to detect autonomous HLEs as its length is shorter than 1000 bp\n" % chrm) 763 | continue 764 | subgenome_list.append((chrm, seq_len)) 765 | 766 | num_groups = num_groups if num_groups <= len(subgenome_list) else len(subgenome_list) 767 | ### To split the genomes into several files. 768 | # Calculate target sum for each group 769 | total_sum = sum([i[1] for i in subgenome_list]) 770 | target_sum = total_sum / num_groups 771 | # Sort numbers in descending order 772 | numbers = sorted(subgenome_list, key=lambda x: -x[1]) 773 | # Split numbers into groups with similar sums 774 | groups = [[] for i in range(num_groups)] 775 | group_sums = [0] * num_groups 776 | for number in numbers: 777 | # Find the group with the smallest current sum and add the number to it 778 | min_sum_index = group_sums.index(min(group_sums)) 779 | groups[min_sum_index].append(number) 780 | group_sums[min_sum_index] += number[1] 781 | 782 | ## To split big chrms into smaller chunks. 783 | subgenome_list = [] 784 | init_num = 1 785 | for subgroup in groups: 786 | subgenome = ''.join(['genomes/subgenome', str(init_num), '.fa']) 787 | init_num += 1 788 | with open(subgenome, 'w') as F: 789 | for chrminfo in subgroup: 790 | chrid = chrminfo[0] 791 | seq = self.genome_dict[chrid] 792 | seq_len = len(seq) 793 | num = seq_len // chunk_size 794 | for i in range(num + 1): 795 | start, stop = i * chunk_size, (i + 1) * chunk_size + flanking_size 796 | if start >= seq_len: 797 | continue 798 | if stop > seq_len: 799 | stop = seq_len 800 | subchrm = 'startat'.join([chrid, str(start)]) 801 | chunk_seq = str(self.genome_dict[chrid][start:stop]) 802 | F.write(''.join(['>', subchrm, '\n'])) 803 | F.write(chunk_seq) 804 | F.write('\n') 805 | subgenome_list.append(subgenome) 806 | return subgenome_list 807 | 808 | def autonomous_detect(self): 809 | # main program to search for transposae and terminal signals. 810 | subgenome_list = self.split_genome(chunk_size=200000000, flanking_size=20000, num_groups=200) 811 | if len(subgenome_list) < self.process_num: 812 | processnum = len(subgenome_list) 813 | else: 814 | processnum = self.process_num 815 | sys.stdout.write('Start to search for HLE rep-hel blocks...\n') 816 | # Use python multiple threading 817 | planpool = ThreadPool(processnum) 818 | #processnum = processnum if self.cpu_count > processnum else self.cpu_count 819 | #planpool = Pool(processnum) 820 | run_result = [] 821 | for subgenome in subgenome_list: 822 | run_result.append(planpool.apply_async(self.intergrated_program, args=(subgenome,))) 823 | planpool.close() 824 | planpool.join() 825 | Helitron_list = [] 826 | for result in run_result: 827 | result_get = result.get() 828 | if result_get: 829 | Helitron_list.extend(result_get) 830 | Helitron_list = sorted(Helitron_list, key=lambda x: [x[0], int(x[1]), int(x[2])]) 831 | return Helitron_list 832 | 833 | def blastn(self, query_file, optdir): 834 | # To search for homologous of given sequences 835 | blastn_opt = ''.join([query_file, '.tbl']) 836 | blastn_pro = subprocess.Popen( 837 | ['blastn', '-db', self.genomedb, '-query', query_file, '-num_threads', str(self.process_num), 838 | '-max_target_seqs', '999999999', '-evalue', str(self.evalue_blastn), '-task', 'blastn-short', 839 | '-outfmt', '6 qseqid sseqid pident qstart qend sstart send evalue qlen bitscore', '-out', blastn_opt]) 840 | blastn_pro.wait() 841 | ## if the blastn_opt is empty, return 842 | if not os.path.getsize(blastn_opt): 843 | return 0 844 | ## The blastn output is sorted by queryname. Split blastn outfmt-6 table into bed files. 845 | with open(blastn_opt, 'r') as F: 846 | ## init reading 847 | splitlines = F.readline().rstrip().split('\t') 848 | init_qname = splitlines[0] 849 | chrm, identity, qstart, qend, sstart, send, evalue, qlen, bitscore = splitlines[1:10] 850 | if int(sstart) < int(send): 851 | START = sstart 852 | END = send 853 | strand = '+' 854 | else: 855 | START = send 856 | END = sstart 857 | strand = '-' 858 | deposit_list = [''.join([chrm, '\t', START, '\t', END, '\t', init_qname, '\t', bitscore, '\t', strand, '\n'])] 859 | for line in F: 860 | splitlines = line.rstrip().split('\t') 861 | chrm, identity, qstart, qend, sstart, send, evalue, qlen, bitscore = splitlines[1:10] 862 | if int(sstart) < int(send): 863 | START = sstart 864 | END = send 865 | strand = '+' 866 | else: 867 | START = send 868 | END = sstart 869 | strand = '-' 870 | query_name = splitlines[0] 871 | if query_name == init_qname: 872 | deposit_list.append(''.join([chrm, '\t', START, '\t', END, '\t', init_qname, '\t', bitscore, '\t', strand, '\n'])) 873 | else: 874 | subfile = ''.join([optdir, '/', init_qname, '.bed']) 875 | with open(subfile, 'w') as wF: 876 | wF.writelines(deposit_list) 877 | ## reinit 878 | init_qname = query_name 879 | deposit_list = [''.join([chrm, '\t', START, '\t', END, '\t', init_qname, '\t', bitscore, '\t', strand, '\n'])] 880 | ## The last deposit need to be saved manually 881 | subfile = ''.join([optdir, '/', init_qname, '.bed']) 882 | with open(subfile, 'w') as wF: 883 | wF.writelines(deposit_list) 884 | os.remove(blastn_opt) 885 | return 1 886 | 887 | def merge_overlaped_intervals(self, bedinput, represent_bed, alt_optbed, rep_type = True): 888 | # To merge overlaped nonautonomous candidates 889 | True_pair_list = [] 890 | with open(bedinput, 'r') as RF, open(represent_bed, 'a') as WFr, open(alt_optbed, 'a') as WFalt: 891 | ### To output alternative insertions and extract first line 892 | EMPTY_DEDUCE=0 893 | for line in RF: 894 | EMPTY_DEDUCE=1 895 | splitlines = line.rstrip().split('\t') 896 | chrmid, start, stop, pairname, count, strand, pvalue, Bscore, classname, mobile_type = splitlines 897 | mobile_type, altype = mobile_type.split('-') 898 | if altype == 'alt' and rep_type: 899 | WFalt.write(line) 900 | continue 901 | else: 902 | break 903 | if not EMPTY_DEDUCE: 904 | return {} 905 | alternative_bedlines = [[chrmid, start, stop, pairname, count, strand, pvalue, Bscore, classname, mobile_type]] 906 | compared_line = (chrmid, start, stop, strand) 907 | blockname_init = 1 908 | 909 | output_recorder = {} 910 | for line in RF: 911 | chrmid, start, stop, pairname, count, strand, pvalue, Bscore, classname, mobile_type = line.rstrip().split('\t') 912 | mobile_type, altype = mobile_type.split('-') 913 | ### To output alternative insertions 914 | if altype == 'alt' and rep_type: 915 | WFalt.write(line) 916 | continue 917 | 918 | newline = [chrmid, start, stop, pairname, count, strand, pvalue, Bscore, classname, mobile_type] 919 | Intersection_deduce = self.intersect(compared_line[1:3], [start, stop], lportion=0.8, rportion=0.8, bool_and=0) 920 | if compared_line[0] == chrmid and Intersection_deduce: 921 | merged_coord = sorted([compared_line[1], compared_line[2], start, stop], key=lambda x: int(x)) 922 | compared_line_s, compared_line_e = merged_coord[0], merged_coord[-1] 923 | compared_line = [chrmid, start, compared_line_e, strand] 924 | alternative_bedlines.append(newline) 925 | else: 926 | block_name = '_'.join(['insertion', classname, mobile_type, str(blockname_init)]) 927 | output_recorder[block_name]=1 928 | ## Begin to output the former to alternative file 929 | [i.append(block_name) for i in alternative_bedlines] 930 | if mobile_type=='auto': 931 | print('blocks', alternative_bedlines) 932 | ## Try to select a representative from these alternatives. 933 | RC_list = self.filter(alternative_bedlines, classname=classname, mobile_type=mobile_type) 934 | if RC_list: 935 | for line in RC_list: 936 | WFr.write('\t'.join(line)) 937 | WFr.write('\n') 938 | True_pair_list.append(line[3]) 939 | 940 | blockname_init += 1 941 | alternative_bedlines = [newline] 942 | compared_line = [chrmid, start, stop, strand] 943 | 944 | ## in case the last overlaped series not saved. 945 | block_name = '_'.join(['insertion', classname, mobile_type, str(blockname_init)]) 946 | if block_name not in output_recorder: 947 | [i.append(block_name) for i in alternative_bedlines] 948 | RC_list = self.filter(alternative_bedlines, classname=classname, mobile_type=mobile_type) 949 | if RC_list: 950 | for line in RC_list: 951 | WFr.write('\t'.join(line)) 952 | WFr.write('\n') 953 | True_pair_list.append(line[3]) 954 | return set(True_pair_list) 955 | 956 | def merge_overlaped_autos(self, bedinput, represent_bed, alt_optbed, rep_type = True): 957 | True_pair_list = [] 958 | 959 | with open(bedinput, 'r') as RF, open(represent_bed, 'a') as WF, open(alt_optbed, 'a') as WFalt: 960 | ### To output alternative insertions and extract first line 961 | EMPTY_DEDUCE=0 962 | for line in RF: 963 | EMPTY_DEDUCE=1 964 | splitlines = line.rstrip().split('\t') 965 | chrmid, start, stop, pairname, count, strand, pvalue, Bscore, classname, mobile_type = splitlines[6:16] 966 | mobile_type, altype = mobile_type.split('-') 967 | splitlines[15] = mobile_type 968 | if altype == 'alt' and rep_type: 969 | WFalt.write(line) 970 | continue 971 | else: 972 | break 973 | if not EMPTY_DEDUCE: 974 | return {} 975 | 976 | last_orfid = splitlines[3] 977 | alternative_bedlines = [splitlines[6:16]] 978 | blockname_init = 1 979 | output_recorder = {} 980 | for line in RF: 981 | splitlines = line.rstrip().split('\t') 982 | orfid = splitlines[3] 983 | mobile_type=splitlines[15] 984 | mobile_type, altype = mobile_type.split('-') 985 | splitlines[15] = mobile_type 986 | ### To output alternative insertions 987 | if altype == 'alt' and rep_type: 988 | WFalt.write(line) 989 | continue 990 | if orfid == last_orfid: 991 | alternative_bedlines.append(splitlines[6:16]) 992 | else: 993 | block_name = '_'.join(['insertion', classname, mobile_type, str(blockname_init)]) 994 | output_recorder[block_name] = 1 995 | ## Begin to output the former to alternative file 996 | [i.append(block_name) for i in alternative_bedlines] 997 | ## Try to select a representative from these alternatives. 998 | RC_list = self.filter(alternative_bedlines, classname=classname, mobile_type=mobile_type) 999 | if RC_list: 1000 | for line in RC_list: 1001 | WF.write('\t'.join(line)) 1002 | WF.write('\n') 1003 | True_pair_list.append(line[3]) 1004 | blockname_init += 1 1005 | last_orfid = orfid 1006 | alternative_bedlines = [splitlines[6:16]] 1007 | ## in case the last overlaped series not saved. 1008 | block_name = '_'.join(['insertion', classname, mobile_type, str(blockname_init)]) 1009 | if block_name not in output_recorder: 1010 | [i.append(block_name) for i in alternative_bedlines] 1011 | RC_list = self.filter(alternative_bedlines, classname=classname, mobile_type=mobile_type) 1012 | if RC_list: 1013 | for line in RC_list: 1014 | WF.write('\t'.join(line)) 1015 | WF.write('\n') 1016 | True_pair_list.append(line[3]) 1017 | return set(True_pair_list) 1018 | 1019 | def add_unique_pre_ts(self, pre_lts_fa, pre_rts_fa, new_lts_fa, new_rts_fa): 1020 | pre_lts_dict = SeqIO.parse(pre_lts_fa, 'fasta') 1021 | pre_rts_dict = SeqIO.parse(pre_rts_fa, 'fasta') 1022 | pre_lts_dict = {k.id: k.seq.upper() for k in pre_lts_dict} 1023 | pre_rts_dict = {k.id: k.seq.upper() for k in pre_rts_dict} 1024 | if os.path.isfile(new_lts_fa) and os.path.isfile(new_rts_fa): 1025 | sum_lts_length = sum([len(pre_lts_dict[i]) for i in pre_lts_dict]) 1026 | lts_evalue_blastn = sum_lts_length * 30 / (2 ** 30) 1027 | lts_blastn_opt = 'lts.blastn.tbl' 1028 | lts_blastn_pro = subprocess.Popen( 1029 | ['blastn', '-subject', new_lts_fa, '-query', pre_lts_fa, 1030 | '-max_target_seqs', '5', '-evalue', str(lts_evalue_blastn), '-task', 'blastn-short', 1031 | '-outfmt', '6 qseqid sseqid pident qstart qend sstart send evalue qlen bitscore', '-out', lts_blastn_opt]) 1032 | lts_blastn_pro.wait() 1033 | 1034 | sum_rts_length = sum([len(pre_rts_dict[i]) for i in pre_rts_dict]) 1035 | rts_evalue_blastn = sum_rts_length * 30 / (2 ** 30) 1036 | rts_blastn_opt = 'rts.blastn.tbl' 1037 | rts_blastn_pro = subprocess.Popen( 1038 | ['blastn', '-subject', new_rts_fa, '-query', pre_rts_fa, 1039 | '-max_target_seqs', '5', '-evalue', str(rts_evalue_blastn), '-task', 'blastn-short', 1040 | '-outfmt', '6 qseqid sseqid pident qstart qend sstart send evalue qlen bitscore', '-out', rts_blastn_opt]) 1041 | rts_blastn_pro.wait() 1042 | 1043 | with open(lts_blastn_opt, 'r') as F: 1044 | overlap_lts = {line.split('\t')[0] for line in F} 1045 | with open(rts_blastn_opt, 'r') as F: 1046 | overlap_rts = {line.split('\t')[0] for line in F} 1047 | else: ## the de-novo structural files are empty 1048 | overlap_lts = set() 1049 | overlap_rts = set() 1050 | 1051 | unique_lts = list(set(pre_lts_dict.keys()) - overlap_lts) 1052 | unique_rts = list(set(pre_rts_dict.keys()) - overlap_rts) 1053 | 1054 | ## To find unique pairs 1055 | unique_pair = [] 1056 | for lts in unique_lts: 1057 | for rts in self.prepair_dict[lts]: 1058 | if rts in unique_rts: 1059 | unique_pair.append((lts, rts)) 1060 | ## To pend 1061 | with open(new_lts_fa, 'a') as lts_w, open(new_rts_fa, 'a') as rts_w: 1062 | for pair in unique_pair: 1063 | left, right = pair 1064 | lts_w.write(''.join(['>', left, '\n', str(pre_lts_dict[left]), '\n'])) 1065 | rts_w.write(''.join(['>', right, '\n', str(pre_rts_dict[right]), '\n'])) 1066 | return unique_pair 1067 | 1068 | def transform_orfbedfile(self, orffile, classname): 1069 | orf_alternative_file = ''.join([classname, '.orfonly.alternative.bed']) 1070 | with open(orffile, 'r') as F, open(orf_alternative_file, 'w') as wf: 1071 | init = 1 1072 | for line in F: 1073 | splitlines = line.rstrip().split('\t') 1074 | name = ''.join(['insertion_', classname, '_orfonly_', str(init)]) 1075 | newline = '\t'.join( 1076 | [splitlines[0], splitlines[1], splitlines[2], splitlines[3], '1', splitlines[5], '1', '0', classname, 'orfonly', name]) 1077 | wf.write(newline) 1078 | wf.write('\n') 1079 | init += 1 1080 | 1081 | def prepare_terminal_seq(self, Helitron_list, pair=False, classname='HLE1'): 1082 | if not os.path.exists(classname): 1083 | os.mkdir(classname) 1084 | os.chdir(classname) 1085 | 1086 | left_exist, right_exist = 0, 0 1087 | 1088 | ORF_bedfile = ''.join([classname, '_orf.bed']) 1089 | left_ter_file = ''.join([classname, '_left.fa']) ## the file name will be split by '.' in vsearch function. 1090 | left_ter_reduce_file = ''.join([classname, '.reduce.left.fa']) 1091 | 1092 | right_ter_file = ''.join([classname, '_right.fa']) 1093 | right_ter_reduce_file = ''.join([classname, '.reduce.right.fa']) 1094 | 1095 | ORF_length_list = [] 1096 | 1097 | ## To build container for both left and right pair 1098 | EXTEND=30 1099 | Helitron_pair_list = [] 1100 | with open(ORF_bedfile, 'w') as orfF, open(left_ter_file, 'w') as leftF, open(right_ter_file, 'w') as rightF: 1101 | for line in Helitron_list: 1102 | left_ter_name, right_ter_name = [], [] 1103 | strand = line[3] 1104 | orfF.write(''.join([line[0], '\t', line[1], '\t', line[2], '\t', line[7], '\t', line[4], '\t', strand, '\n'])) 1105 | ORF_length_list.append(int(line[2]) - int(line[1]) + 1) 1106 | left_list = line[5] 1107 | left_seq = [] 1108 | init = 0 1109 | for left in left_list: 1110 | left_exist += 1 1111 | id = '.'.join([line[7], 'left', str(init)]) 1112 | init += 1 1113 | left_ter_name.append(id) 1114 | if strand == '+': 1115 | loc_s = int(left[1]) - 1 1116 | loc_s = loc_s if loc_s >= 0 else 0 1117 | seq = str(self.genome_dict[line[0]][loc_s:int(left[1]) + EXTEND-1].upper()) 1118 | else: 1119 | seq = self.genome_dict[line[0]][int(left[2]) - EXTEND:int(left[2])] 1120 | seq = str(seq.reverse_complement().upper()) 1121 | left_seq.append(''.join(['>', id, '\n', seq, '\n'])) 1122 | 1123 | right_list = line[6] 1124 | right_seq = [] 1125 | init = 0 1126 | for right in right_list: 1127 | right_exist += 1 1128 | id = '.'.join([line[7], 'right', str(init)]) 1129 | init += 1 1130 | right_ter_name.append(id) 1131 | if strand == '-': 1132 | loc_s = int(right[1]) - 1 1133 | loc_s = loc_s if loc_s >= 0 else 0 1134 | seq = self.genome_dict[line[0]][loc_s:int(right[1]) + EXTEND-1] 1135 | seq = str(seq.reverse_complement().upper()) 1136 | else: 1137 | seq = str(self.genome_dict[line[0]][int(right[2]) - EXTEND:int(right[2])].upper()) 1138 | right_seq.append(''.join(['>', id, '\n', seq, '\n'])) 1139 | 1140 | if classname == 'HLE1' and pair: ## pair the left and right terminals that ever appears on the same Helitron region. 1141 | [Helitron_pair_list.append((left, tuple(right_ter_name))) for left in left_ter_name] ## all possibilities. 1142 | elif classname != 'HLE1': 1143 | [Helitron_pair_list.append((left_ter_name[i], right_ter_name[i])) for i in range(len(left_ter_name))] 1144 | leftF.writelines(left_seq) 1145 | rightF.writelines(right_seq) 1146 | 1147 | ## if run denovo search for motifs: 1148 | if not Args.dis_denovo: 1149 | if not left_exist or not right_exist: ## means that neither left nor right terminal signals exist, so skip blastn 1150 | self.transform_orfbedfile(ORF_bedfile, classname=classname) 1151 | os.chdir('../') 1152 | return [] 1153 | else: ### To redunce redundency via cd-hit-est 1154 | left_cluster_dict = self.cdhitest_clust(left_ter_file, left_ter_reduce_file, 1155 | helitron_type=''.join([classname, '_left']), id=0.9) 1156 | right_cluster_dict = self.cdhitest_clust(right_ter_file, right_ter_reduce_file, 1157 | helitron_type=''.join([classname, '_right']), id=0.9) 1158 | else: ## No need to run de-novo terminal structural detection 1159 | left_cluster_dict = {} 1160 | right_cluster_dict = {} 1161 | 1162 | pre_left_file = self.terminalfile_dict[classname]['left'] 1163 | pre_right_file = self.terminalfile_dict[classname]['right'] 1164 | unique_pairlist = [] 1165 | if pre_left_file: ### To pend unique-pre-ts signals 1166 | unique_pairlist = self.add_unique_pre_ts(pre_left_file, pre_right_file, left_ter_reduce_file, right_ter_reduce_file) 1167 | else: 1168 | if Args.dis_denovo: 1169 | ## This means no terminal structures are avaliable. Just output the orf information. 1170 | self.transform_orfbedfile(ORF_bedfile, classname=classname) 1171 | os.chdir('../') 1172 | return [] 1173 | ## To make left-right pairs 1174 | combinid_file = '%s.combinid.txt' % classname 1175 | if pair: 1176 | ### To get the collapsed cluster pairs 1177 | collapsed_pair_dict = defaultdict(list) 1178 | terminal_pair_dict = dict(Helitron_pair_list) 1179 | if classname == 'HLE1': ## pair the left and right terminals that ever appears on the same Helitron region. 1180 | for left_name in terminal_pair_dict: 1181 | right_name_list = terminal_pair_dict[left_name] 1182 | for right_name in right_name_list: 1183 | collapsed_left_clust = left_cluster_dict[left_name] 1184 | collapsed_right_clust = right_cluster_dict[right_name] 1185 | collapsed_pair_dict[collapsed_left_clust].append(collapsed_right_clust) 1186 | else: ## pair inverted repeats 1187 | for left_name in terminal_pair_dict: 1188 | right_name = terminal_pair_dict[left_name] 1189 | collapsed_left_clust = left_cluster_dict[left_name] 1190 | collapsed_right_clust = right_cluster_dict[right_name] 1191 | collapsed_pair_dict[collapsed_left_clust].append(collapsed_right_clust) 1192 | # To reduce redundency 1193 | for key in collapsed_pair_dict: 1194 | collapsed_pair_dict[key] = list(set(collapsed_pair_dict[key])) 1195 | with open(combinid_file, 'w') as F: 1196 | for left in collapsed_pair_dict: 1197 | for right in collapsed_pair_dict[left]: 1198 | F.write(''.join([left, '\t', right, '\n'])) 1199 | ## To output unique-pre-ts pairs 1200 | for pair in unique_pairlist: 1201 | F.write(''.join([pair[0], '\t', pair[1], '\n'])) 1202 | else: 1203 | ## Just make all possibilities 1204 | left_reduced_list = set(left_cluster_dict.values()) 1205 | right_cluster_dict = set(right_cluster_dict.values()) 1206 | with open(combinid_file, 'w') as F: 1207 | for left in left_reduced_list: 1208 | for right in right_cluster_dict: 1209 | F.write(''.join([left, '\t', right, '\n'])) 1210 | ## To output unique-pre-ts pairs, not mixing. 1211 | for pair in unique_pairlist: 1212 | F.write(''.join([pair[0], '\t', pair[1], '\n'])) 1213 | 1214 | ## To evaluate the size range 1215 | max_orf_length = sorted(ORF_length_list)[-1] 1216 | distance_na = int(self.window) * 2 + max_orf_length 1217 | half_distance = int(round(int(distance_na) / 2, 0)) 1218 | self.distance_na[classname] = distance_na if not self.distance_na[classname] else self.distance_na[classname] ## If specified, will use the specified one. 1219 | sys.stdout.write('The length of autonomous %s is expected to be shorter than %s.\n' % (classname, str(distance_na + 100))) 1220 | sys.stdout.write('The length of nonautonomous %s is expected to be shorter than %s.\n' % (classname, str(self.distance_na[classname] + 100))) 1221 | ## To run blastn to get homologies 1222 | left_beddir, right_beddir = 'SubBlastnBed/%s_left' % classname, 'SubBlastnBed/%s_right' % classname 1223 | if not os.path.exists(left_beddir): 1224 | os.makedirs(left_beddir) 1225 | if not os.path.exists(right_beddir): 1226 | os.makedirs(right_beddir) 1227 | lblastn_status = self.blastn(left_ter_reduce_file, left_beddir) 1228 | rblastn_status = self.blastn(right_ter_reduce_file, right_beddir) 1229 | ## To report if blastn runs well 1230 | if lblastn_status and rblastn_status: 1231 | sys.stdout.write('blastn runs well!\n') 1232 | else: 1233 | sys.stdout.write('No similar hits found for LTS/RTS for %s!\n' % classname) 1234 | ## Prepare for fisher's exact test (avoid overloading, to split bedfiles ) 1235 | sys.stdout.write("Prepare for windowing for %s ...\n" % classname) 1236 | subed_dir = '_'.join([classname, 'Windowing']) 1237 | try: 1238 | split_joint_program = subprocess.Popen( 1239 | ['Rscript', SPLIT_JOINT_PRO, left_beddir, right_beddir, combinid_file, subed_dir, 1240 | self.genome_size, str(half_distance), BEDTOOLS_PATH, str(self.process_num)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) 1241 | split_joint_program.wait() 1242 | joint_filepath_blastn = ''.join([subed_dir, '/', 'left_right.path.join']) 1243 | except: 1244 | sys.stderr.write("Error: Windowing program failed...\n") 1245 | exit(0) 1246 | 1247 | ## To run fisher's exact text to select the co-occured left and right terminal signals 1248 | sys.stdout.write("Begin to run fisher's exact test for %s!\n" % classname) 1249 | 1250 | bed_optdir = '%s_BedFisher' % classname 1251 | if os.path.exists(bed_optdir): 1252 | shutil.rmtree(bed_optdir) 1253 | os.mkdir(bed_optdir) 1254 | 1255 | Strategy = '1' if Args.nearest else '0' 1256 | try: 1257 | fisher_program = subprocess.Popen( 1258 | ['Rscript', FISHER_PRO, BEDTOOLS_PATH, self.genome_size, joint_filepath_blastn, bed_optdir, 1259 | str(self.process_num), str(self.pvalue), ORF_bedfile, Strategy], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) 1260 | fisher_program.wait() 1261 | sys.stdout.write("Fisher's exact test finished for %s!\n" % classname) 1262 | except: 1263 | sys.stderr.write("Error: Fisher's exact test failed...\n") 1264 | exit(0) 1265 | 1266 | FisherBed_files = ['/'.join([bed_optdir, file]) for file in os.listdir(bed_optdir)] 1267 | 1268 | ## To merge and sort all Fisher bed files 1269 | fisher_pvalue_file = '%s.joint.pvalue.bed' % classname 1270 | fisher_filelist = [''.join([bed_optdir, '/', file]) for file in os.listdir(bed_optdir) if file.endswith('.bed')] 1271 | with open(fisher_pvalue_file, 'w') as WF: 1272 | for subfisher in fisher_filelist: 1273 | with open(subfisher, 'r') as F: 1274 | content = F.read() 1275 | WF.write(content) 1276 | try: 1277 | sort_pro = subprocess.Popen( 1278 | ['bash', SORT_PRO, fisher_pvalue_file, str(self.process_num)], 1279 | stdout=subprocess.DEVNULL) 1280 | sort_pro.wait() 1281 | sys.stdout.write("Merge and sort fisher result files finished for %s!\n" % classname) 1282 | except: 1283 | sys.stdout.write("Merge and sort fisher result files failed for %s!\n" % classname) 1284 | exit(0) 1285 | 1286 | #############To annotate auto or non-autonomous ############ 1287 | ORF_bed = BT.BedTool(ORF_bedfile) 1288 | ## To get autonomous candidates. 1289 | fisher_pvalue_bed = BT.BedTool(fisher_pvalue_file) 1290 | ## candidates whose significant terminal signals are able to be found. 1291 | orf_fisher_bed = fisher_pvalue_bed.intersect(ORF_bed, nonamecheck=True, F=1, wa=True, s=True, c=True).saveas('Fisher_with_ORF.bed') 1292 | ## To select the intervals that contain only one ORF 1293 | auto_alternative_file = ''.join([classname, '.auto.alternative.bed']) 1294 | 1295 | with open(auto_alternative_file, 'w') as WF: 1296 | with open('Fisher_with_ORF.bed', 'r') as f1: 1297 | for line in f1: 1298 | splitlines = line.rstrip().split('\t') 1299 | if int(splitlines[-1])==1: 1300 | splitlines = line.rstrip().split('\t') 1301 | newline = '\t'.join( 1302 | [splitlines[0], splitlines[1], splitlines[2], splitlines[3], splitlines[4], splitlines[5], 1303 | splitlines[6], splitlines[7], classname, 'auto-%s'%splitlines[8]]) 1304 | WF.write(newline) 1305 | WF.write('\n') 1306 | 1307 | ## To get non-autonomous candidates 1308 | non_autonomous_bed = fisher_pvalue_bed.intersect(ORF_bed, nonamecheck=True, F=0.5, wa=True, v=True).saveas('Nonauto.bed') 1309 | ## candidates whose significant terminal signals are unable to be found. 1310 | auto_alternative_bed = BT.BedTool(auto_alternative_file) 1311 | ORF_without_ter_bed = ORF_bed.intersect(auto_alternative_bed, nonamecheck=True, v=True, s=True, wa=True).saveas('OnlyORF.bed') 1312 | self.transform_orfbedfile('OnlyORF.bed', classname=classname) 1313 | os.chdir('../') 1314 | 1315 | def malign(self, fafile): 1316 | if os.path.getsize(fafile): 1317 | aln_file = ''.join([fafile, '.aln']) 1318 | with open(aln_file, 'w') as mf: 1319 | mul_aln = subprocess.Popen(["mafft", "--auto", "--quiet", fafile], stdout=mf) 1320 | mul_aln.wait() 1321 | 1322 | def flanking_seq(self, fisherfile): 1323 | subwkdir = 'boundary_align' 1324 | pairname = os.path.basename(fisherfile).replace('.bed', '') 1325 | left_extend_file = ''.join([subwkdir, '/', pairname, '.left.fa']) 1326 | right_extend_file = ''.join([subwkdir, '/', pairname, '.right.fa']) 1327 | terminal_file = ''.join([subwkdir, '/', pairname, '.terminal']) 1328 | 1329 | candidate_bed = BT.BedTool(fisherfile).sort() 1330 | candidate_bed = candidate_bed.merge(d=100, c='4,5,6', o='first,mean,first') 1331 | candidate_list = sorted([list(line) for line in candidate_bed], key=lambda x: -float(x[4])) 1332 | if len(candidate_list) < 2: 1333 | return 0 1334 | 1335 | self.filepath_list.append(left_extend_file) 1336 | self.filepath_list.append(right_extend_file) 1337 | self.filepath_list.append(terminal_file) 1338 | 1339 | selected_list = candidate_list[:20] 1340 | with open(left_extend_file, 'w') as LF, open(right_extend_file, 'w') as RF, open(terminal_file, 'w') as TF: 1341 | for line in selected_list: 1342 | chrmid, start, stop, name, score, strand = line 1343 | TF.write(''.join(['>', chrmid, '-', str(start), '-', str(stop), strand.replace('-', '-n').replace('+', '-p'), '\n'])) 1344 | if int(stop) - int(start) > 200: 1345 | left_terminal_seq = str(self.genome_dict[chrmid][int(start):int(start)+100]) 1346 | right_terminal_seq = str(self.genome_dict[chrmid][int(stop) -100:int(stop)]) 1347 | TF.write(''.join([left_terminal_seq, 'N'*10, right_terminal_seq, '\n'])) 1348 | else: 1349 | TF.write(''.join([str(self.genome_dict[chrmid][int(start):int(stop)]), '\n'])) 1350 | 1351 | if strand == '+': 1352 | if int(start) - 50 >= 0: 1353 | seq_stop = int(start) 1354 | seq_start = int(start) - 50 1355 | seq = self.genome_dict[chrmid][seq_start:seq_stop] 1356 | LF.write(''.join(['>', chrmid, '-', str(seq_start), '-', str(seq_stop), '\n'])) 1357 | LF.write(str(seq)) 1358 | LF.write('\n') 1359 | 1360 | if int(stop) + 50 <= self.chrm_size[chrmid]: 1361 | seq_start = int(stop) 1362 | seq_stop = int(stop) + 50 1363 | seq = self.genome_dict[chrmid][seq_start:seq_stop] 1364 | RF.write(''.join(['>', chrmid, '-', str(seq_start), '-', str(seq_stop), '\n'])) 1365 | RF.write(str(seq)) 1366 | RF.write('\n') 1367 | else: 1368 | if int(stop) + 50 <= self.chrm_size[chrmid]: 1369 | seq_start = int(stop) 1370 | seq_stop = int(stop) + 50 1371 | seq = self.genome_dict[chrmid][seq_start:seq_stop].reverse_complement() 1372 | LF.write(''.join(['>', chrmid, '-', str(seq_start), '-', str(seq_stop), '\n'])) 1373 | LF.write(str(seq)) 1374 | LF.write('\n') 1375 | if int(start) - 50 >= 0: 1376 | seq_stop = int(start) 1377 | seq_start = int(start) - 50 1378 | seq = self.genome_dict[chrmid][seq_start:seq_stop].reverse_complement() 1379 | RF.write(''.join(['>', chrmid, '-', str(seq_start), '-', str(seq_stop), '\n'])) 1380 | RF.write(str(seq)) 1381 | RF.write('\n') 1382 | 1383 | def TIR_denection(self, sequencefile): 1384 | sequence_length_dict = SeqIO.parse(sequencefile, 'fasta') 1385 | sequence_length_dict = {k.id: len(k.seq) for k in sequence_length_dict} 1386 | Terminal_dict = defaultdict(lambda :0) 1387 | pairname = os.path.basename(sequencefile).replace('.terminal', '') 1388 | ## start coord is 1 not 0 1389 | dbname = ''.join([os.path.basename(sequencefile), '.invdb']) 1390 | invttirfile = ''.join([os.path.basename(sequencefile), '.inv.txt']) 1391 | ## build database 1392 | mkinvdb = subprocess.Popen( 1393 | ['gt', 'suffixerator', '-db', sequencefile, '-indexname', dbname, '-mirrored', '-dna', '-suf', '-lcp', '-bck'], 1394 | stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL) 1395 | mkinvdb.wait() 1396 | ## run tirvish 1397 | with open(invttirfile, 'w') as invf: 1398 | runinvsearch = subprocess.Popen(['gt', 'tirvish', '-index', dbname, '-mintirlen', '20', '-maxtirlen', '150', 1399 | '-similar', '85', '-mintirdist', '2', '-maxtirdist', '200', '-mintsd', '0', 1400 | '-seed', '12', '-vic', '1', '-overlaps', 'all', '-xdrop', '0'], 1401 | stderr=subprocess.DEVNULL, stdout=invf) 1402 | runinvsearch.wait() 1403 | 1404 | ## The default output is in gff format, extract coord information and do filteration. 1405 | with open(invttirfile, 'r') as F: 1406 | for line in F: 1407 | if line.startswith('#'): 1408 | continue 1409 | splitlines = line.rstrip().split('\t') 1410 | if splitlines[2] == 'repeat_region': 1411 | chrmid = splitlines[0] 1412 | id = splitlines[8].replace('ID=', '') 1413 | t = 1 1414 | elif splitlines[2] == 'terminal_inverted_repeat': 1415 | if t == 1: 1416 | left_start = str(int(splitlines[3])) 1417 | t += 1 1418 | else: 1419 | right_end = str(int(splitlines[4])) 1420 | if self.intersect([1, int(sequence_length_dict[chrmid])], [left_start, right_end], lportion=0.7): 1421 | ## means long terminal inverted repeats detected 1422 | Terminal_dict[chrmid]+=1 1423 | 1424 | os.remove(invttirfile) 1425 | os.system('rm %s*' % dbname) 1426 | Inv_count = len([i for i in Terminal_dict if Terminal_dict[i]>0]) 1427 | Total_num = len(sequence_length_dict.keys()) 1428 | self.Terminal_dict[pairname]=Inv_count/Total_num 1429 | 1430 | def MakeSelection(self, FisherFile_pathlist): 1431 | # This function is to filter out the candidates who might insert into other superfamily of transposons. 1432 | sys.stdout.write('Begin to run boundary check program.\n') 1433 | subwkdir = 'boundary_align' 1434 | if not os.path.exists(subwkdir): 1435 | os.mkdir(subwkdir) 1436 | else: 1437 | shutil.rmtree(subwkdir) 1438 | os.mkdir(subwkdir) 1439 | ## To output the flanking sequences 1440 | self.filepath_list = [] 1441 | 1442 | planpool = ThreadPool(self.process_num) 1443 | for fisherfile in FisherFile_pathlist: 1444 | planpool.apply_async(self.flanking_seq, args=(fisherfile,)) 1445 | planpool.close() 1446 | planpool.join() 1447 | filepath_list = [i for i in self.filepath_list if os.path.getsize(i) and i.endswith('.fa')] 1448 | planpool = ThreadPool(self.process_num) 1449 | 1450 | for fafile in filepath_list: 1451 | planpool.apply_async(self.malign, args=(fafile,)) 1452 | planpool.close() 1453 | planpool.join() 1454 | boundary_identity_tbl = 'Boundary.identity.tbl' 1455 | Boundary_check_pro = subprocess.Popen( 1456 | ['Rscript', BOUNDARY_PRO, os.path.abspath(subwkdir), os.path.abspath(boundary_identity_tbl)], 1457 | stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) 1458 | Boundary_check_pro.wait() 1459 | sys.stdout.write("Boundary check was finished!\n") 1460 | 1461 | ## insertions that only contain orf regions will automatically pass this filter 1462 | 1463 | if os.path.exists(boundary_identity_tbl): 1464 | with open(boundary_identity_tbl, 'r') as F: 1465 | F.readline() ## Skip header 1466 | for line in F: 1467 | name, direction, iden = line.rstrip().split('\t') 1468 | self.Boundary_iden_dict[name][direction] = float(iden) 1469 | 1470 | ## To filter out the candidates who might contain long tirs. 1471 | terminal_file_list = [i for i in self.filepath_list if os.path.getsize(i) and i.endswith('.terminal')] 1472 | planpool = ThreadPool(self.process_num) 1473 | for terminal_file in terminal_file_list: 1474 | planpool.apply_async(self.TIR_denection, args=(terminal_file,)) 1475 | planpool.close() 1476 | planpool.join() 1477 | sys.stdout.write("Inverted repeats detection was finished!\n") 1478 | 1479 | def filter(self, alternative_list, classname, mobile_type): 1480 | ## To do selection for autonomous firstly, because the nonautonomous counterparts will be dertermined by autonomous ones. 1481 | candidate_list = [] 1482 | RC_replist = [] 1483 | if classname == 'HLE1': 1484 | for line in alternative_list: 1485 | pairname = line[3] 1486 | ## insertions that only contain orf regions will automatically pass this filter, because default value is 0. 1487 | if self.Boundary_iden_dict[pairname]['left'] < self.cutoff_flank and self.Boundary_iden_dict[pairname]['right'] < self.cutoff_flank: 1488 | candidate_list.append(line) 1489 | else: ## means HLE2 1490 | for line in alternative_list: 1491 | pairname = line[3] 1492 | left_iden, right_iden = self.Boundary_iden_dict[pairname]['left'], self.Boundary_iden_dict[pairname]['right'] 1493 | if left_iden < self.cutoff_flank: 1494 | ## means regular HLE2, try to find stem-loop terminal markers at 5'end 1495 | candidate_list.append(line) 1496 | elif right_iden < self.cutoff_flank and left_iden >= self.cutoff_flank: 1497 | ## unregular HLE2, try to find stem-loop terminal markers at 3'end 1498 | line[-3] = ''.join([line[-3], '.2']) 1499 | candidate_list.append(line) 1500 | if not candidate_list: 1501 | if mobile_type != 'nonauto': 1502 | ## Might represent a truncated helitron insertion. Just keep the autonomous ones and remove the nonautonomous ones. 1503 | ## Because we are sure that there should be one insertion in autonomous region. 1504 | candidate_list = sorted(alternative_list, key=lambda x: [int(x[2]) - int(x[1]), float(x[6]), -float(x[7])]) ## length (shorter), ## pvalue, then bitscore 1505 | else: 1506 | candidate_list = sorted(candidate_list, key=lambda x: [float(x[6]), int(x[1]) - int(x[2]), -float(x[7])]) ## pvalue, length, then bitscore 1507 | ## To further filter out TIRs 1508 | candidate_list2 = [i for i in candidate_list if self.Terminal_dict[i[3]] <= 0.2] 1509 | if candidate_list2: 1510 | candidate_list = candidate_list2 1511 | else: 1512 | if mobile_type == 'nonauto': 1513 | return [] 1514 | if candidate_list: 1515 | RC_replist.append(candidate_list[0]) 1516 | return RC_replist 1517 | 1518 | def OutputSequence(self, bedinput, faoutput): 1519 | with open(bedinput, 'r') as RF, open(faoutput, 'w') as WF: 1520 | for line in RF: 1521 | splitlines = line.rstrip().split('\t') 1522 | chrmid, start, stop, pairname, score, strand = splitlines[:6] 1523 | insertion_name = splitlines[-1] 1524 | start = int(start) - 1 1525 | start = 0 if start <0 else start 1526 | seq = self.genome_dict[chrmid][start:int(stop)] 1527 | if strand == '+': 1528 | WF.write(''.join(['>', insertion_name, '\n'])) 1529 | WF.write(str(seq)) 1530 | WF.write('\n') 1531 | else: 1532 | WF.write(''.join(['>', insertion_name, '\n'])) 1533 | WF.write(str(seq.reverse_complement())) 1534 | WF.write('\n') 1535 | 1536 | def Convienced_LTS_RTS(self, RCfile, opfile): 1537 | ## To output convinced pair list which can be used as query in another close species genome. 1538 | with open(RCfile, 'r') as F: 1539 | pairlist = {line.rstrip().split("\t")[3] for line in F} 1540 | convienced_dict = defaultdict(list) 1541 | for pair in pairlist: 1542 | tirvalue = self.Terminal_dict[pair] 1543 | if float(tirvalue) <= 0.2: 1544 | if pair in self.Boundary_iden_dict: 1545 | left_value = float(self.Boundary_iden_dict[pair]['left']) 1546 | right_value = float(self.Boundary_iden_dict[pair]['right']) 1547 | classname = pair.split('_left')[0] 1548 | if 'HLE2' in pair: 1549 | if left_value < self.cutoff_flank or right_value < self.cutoff_flank: 1550 | convienced_dict[classname].append(pair) 1551 | else: ## means Helitron 1552 | if left_value < self.cutoff_flank and right_value < self.cutoff_flank: 1553 | convienced_dict[classname].append(pair) 1554 | 1555 | oplist = [] 1556 | for classname in convienced_dict: 1557 | ## To read the left terminal sequence 1558 | left_terminal_file = ''.join([classname, '/', classname, '.reduce.left.fa']) 1559 | left_terminal_dict = SeqIO.parse(left_terminal_file, 'fasta') 1560 | left_terminal_dict = {k.id: k.seq.upper() for k in left_terminal_dict} 1561 | ## To read the right terminal sequence 1562 | right_terminal_file = ''.join([classname, '/', classname, '.reduce.right.fa']) 1563 | right_terminal_dict = SeqIO.parse(right_terminal_file, 'fasta') 1564 | right_terminal_dict = {k.id: k.seq.upper() for k in right_terminal_dict} 1565 | 1566 | for pair in convienced_dict[classname]: 1567 | left, right = pair.split('-') 1568 | left_seq = str(left_terminal_dict[left]) 1569 | right_seq = str(right_terminal_dict[right]) 1570 | oplist.append(''.join([classname, '\t', left, '\t', left_seq, '\t', right,'\t', right_seq, '\n'])) 1571 | with open(opfile, 'w') as F: 1572 | F.writelines(oplist) 1573 | 1574 | def Pre_ts_solo(self, classname, pre_lts_file, pre_rts_file): 1575 | if not os.path.exists(classname): 1576 | os.mkdir(classname) 1577 | os.chdir(classname) 1578 | ORF_bedfile = ''.join([classname, '_orf.bed']) 1579 | ## To evaluate the size range 1580 | distance_na = int(self.window) * 2 1581 | half_distance = int(round(int(distance_na) / 2, 0)) 1582 | self.distance_na[classname] = distance_na if not self.distance_na[classname] else self.distance_na[classname] ## If specified, will use the specified one. 1583 | sys.stdout.write('The length of autonomous %s is expected to be shorter than %s.\n' % (classname, str(distance_na + 100))) 1584 | sys.stdout.write('The length of nonautonomous %s is expected to be shorter than %s.\n' % (classname, str(self.distance_na[classname] + 100))) 1585 | ## To run blastn to get homologies 1586 | left_beddir, right_beddir = 'SubBlastnBed/%s_left' % classname, 'SubBlastnBed/%s_right' % classname 1587 | if not os.path.exists(left_beddir): 1588 | os.makedirs(left_beddir) 1589 | if not os.path.exists(right_beddir): 1590 | os.makedirs(right_beddir) 1591 | self.blastn(pre_lts_file, left_beddir) 1592 | self.blastn(pre_rts_file, right_beddir) 1593 | ## To output combine id 1594 | combinid_file = '%s.combinid.txt' % classname 1595 | with open(combinid_file, 'w') as F: 1596 | F.writelines([''.join([left, '\t', right, '\n']) for left in self.prepair_dict for right in self.prepair_dict[left] if re.match('%s_left'%classname, left)]) 1597 | 1598 | ## Prepare for fisher's exact test (avoid overloading, to split bedfiles ) 1599 | sys.stdout.write("Prepare for windowing for %s ...\n" % classname) 1600 | subed_dir = '_'.join([classname, 'Windowing']) 1601 | try: 1602 | split_joint_program = subprocess.Popen( 1603 | ['Rscript', SPLIT_JOINT_PRO, left_beddir, right_beddir, combinid_file, subed_dir, 1604 | self.genome_size, str(half_distance), BEDTOOLS_PATH, str(self.process_num)], stdout=subprocess.DEVNULL) 1605 | split_joint_program.wait() 1606 | joint_filepath_blastn = ''.join([subed_dir, '/', 'left_right.path.join']) 1607 | except: 1608 | sys.stderr.write("Error: Windowing program failed...\n") 1609 | exit(0) 1610 | 1611 | ## To run fisher's exact text to select the co-occured left and right terminal signals 1612 | sys.stdout.write("Begin to run fisher's exact test for %s!\n" % classname) 1613 | 1614 | bed_optdir = '%s_BedFisher' % classname 1615 | if os.path.exists(bed_optdir): 1616 | shutil.rmtree(bed_optdir) 1617 | os.mkdir(bed_optdir) 1618 | Strategy = '1' if Args.nearest else '0' 1619 | try: 1620 | fisher_program = subprocess.Popen( 1621 | ['Rscript', FISHER_PRO, BEDTOOLS_PATH, self.genome_size, joint_filepath_blastn, bed_optdir, 1622 | str(self.process_num), str(self.pvalue), ORF_bedfile, Strategy], stdout=subprocess.DEVNULL) 1623 | fisher_program.wait() 1624 | sys.stdout.write("Fisher's exact test finished for %s!\n" % classname) 1625 | except: 1626 | sys.stderr.write("Error: Fisher's exact test failed...\n") 1627 | exit(0) 1628 | 1629 | FisherBed_files = ['/'.join([bed_optdir, file]) for file in os.listdir(bed_optdir)] 1630 | 1631 | ## To merge and sort all Fisher bed files 1632 | fisher_pvalue_file = '%s.joint.pvalue.bed' % classname 1633 | fisher_filelist = [''.join([bed_optdir, '/', file]) for file in os.listdir(bed_optdir) if file.endswith('.bed')] 1634 | with open(fisher_pvalue_file, 'w') as WF: 1635 | for subfisher in fisher_filelist: 1636 | with open(subfisher, 'r') as F: 1637 | content = F.read() 1638 | WF.write(content) 1639 | try: 1640 | sort_pro = subprocess.Popen( 1641 | ['bash', SORT_PRO, fisher_pvalue_file, str(self.process_num)], 1642 | stdout=subprocess.DEVNULL) 1643 | sort_pro.wait() 1644 | sys.stdout.write("Merge and sort fisher result files finished for %s!\n" % classname) 1645 | except: 1646 | sys.stdout.write("Merge and sort fisher result files failed for %s!\n" % classname) 1647 | exit(0) 1648 | fisher_pvalue_bed = BT.BedTool(fisher_pvalue_file).saveas('Nonauto.bed') 1649 | os.chdir('../') 1650 | 1651 | def main(self): 1652 | self.Boundary_iden_dict = defaultdict(lambda: defaultdict(lambda: 1)) 1653 | self.Terminal_dict = defaultdict(lambda: 1) 1654 | 1655 | RC_total_candidate_dict = defaultdict(list) 1656 | RC_total_candidate = self.autonomous_detect() 1657 | [RC_total_candidate_dict[line[4]].append(line) for line in RC_total_candidate] 1658 | orf_classname_list = list(RC_total_candidate_dict.keys()) 1659 | unique_pre_ts_classname = [] 1660 | classname_list = [] 1661 | classname_list.extend(orf_classname_list) 1662 | if self.prepair_dict: 1663 | ## means add pre-ts 1664 | unique_pre_ts_classname = list(set(self.terminalfile_dict.keys()) - set(orf_classname_list)) 1665 | classname_list.extend(unique_pre_ts_classname) 1666 | 1667 | Repsentative_file_list = [] 1668 | Alternative_file_list = [] 1669 | ## Loop for each variants. 1670 | for class_name in classname_list: 1671 | op_representative = '%s.representative.bed' % class_name 1672 | opauto_nest_alt = '%s.auto.nest.alt.bed' % class_name 1673 | opnonauto_nest_alt = '%s.nonauto.nest.alt.bed' % class_name 1674 | op_nest_rep = '%s.nest.bed' % class_name 1675 | 1676 | if os.path.exists(op_representative): 1677 | os.remove(op_representative) 1678 | Repsentative_file_list.append(op_representative) 1679 | if os.path.exists(op_nest_rep): 1680 | os.remove(op_nest_rep) 1681 | Alternative_file_list.append(op_nest_rep) 1682 | 1683 | FisherFile_list = [] 1684 | Auto_file_list = [] 1685 | ORFonly_file_list = [] 1686 | RC_list = RC_total_candidate_dict[class_name] 1687 | if RC_list: 1688 | if re.findall('HLE2', class_name): ## need to pair the terminal repeats 1689 | self.prepare_terminal_seq(RC_list, pair=True, classname=class_name) 1690 | else: 1691 | if not Args.pair_helitron: 1692 | self.prepare_terminal_seq(RC_list, pair=False, classname=class_name) 1693 | else: 1694 | self.prepare_terminal_seq(RC_list, pair=True, classname=class_name) 1695 | else: 1696 | self.Pre_ts_solo(classname=class_name, pre_lts_file=self.terminalfile_dict[class_name]['left'], 1697 | pre_rts_file=self.terminalfile_dict[class_name]['right']) 1698 | 1699 | fisher_beddir = ''.join([class_name, '/', class_name, '_BedFisher']) 1700 | if os.path.exists(fisher_beddir): 1701 | FisherFile_list.extend([''.join([fisher_beddir, '/', file]) for file in os.listdir(fisher_beddir)]) 1702 | ## To check that if the boundary of each family can be well aligned. 1703 | ## To check that if the families contain long terminal inverted repeats. 1704 | self.MakeSelection(FisherFile_list) 1705 | 1706 | ## To merge autonomous insertions and select representatives 1707 | pairnamelist = set() 1708 | if RC_list: 1709 | ORF_bed = BT.BedTool(''.join([class_name, '/', class_name, '_orf.bed'])) 1710 | Auto_fisher_file = ''.join([class_name, '/', '%s.auto.alternative.bed' % class_name]) 1711 | 1712 | if os.path.isfile(Auto_fisher_file): 1713 | Auto_fisher_bed = BT.BedTool(Auto_fisher_file) 1714 | else: 1715 | Auto_fisher_bed = BT.BedTool([]) 1716 | Auto_ORF_intersect_file = ''.join([class_name, '/', class_name, 'ORFinterAUTO.bed']) 1717 | ORF_bed.intersect(Auto_fisher_bed, nonamecheck=True, f=1, wo=True, s=True).saveas(Auto_ORF_intersect_file) 1718 | 1719 | if os.path.exists(Auto_fisher_file): 1720 | pairnamelist = self.merge_overlaped_autos(Auto_ORF_intersect_file, op_representative, opauto_nest_alt, rep_type=True) 1721 | ## To output alternative nest insertions 1722 | if os.path.exists(opauto_nest_alt): 1723 | self.merge_overlaped_autos(opauto_nest_alt, op_nest_rep, 'tmp.txt', rep_type=False) 1724 | 1725 | ## To get non-autonomous candidates 1726 | nonauto_bedfile = '%s/Nonauto.bed' % class_name 1727 | nonauto_alternative_file = ''.join([class_name, '/', class_name, '.nonauto.alternative.bed']) 1728 | if os.path.exists(nonauto_bedfile): 1729 | with open(nonauto_alternative_file, 'w') as WF, open(nonauto_bedfile, 'r') as RF: 1730 | for line in RF: 1731 | splitlines = line.rstrip().split('\t') 1732 | ## To filter out ultra-large nonautonomous 1733 | if int(splitlines[2]) - int(splitlines[1]) + 1 > self.distance_na[class_name] + 100: 1734 | continue 1735 | ## To limit outputing nonautonomous candidates who shares the same autonomous boundaries. 1736 | if Args.multi_ts: 1737 | newline = '\t'.join( 1738 | [splitlines[0], splitlines[1], splitlines[2], splitlines[3], splitlines[4], 1739 | splitlines[5], splitlines[6], splitlines[7], class_name, 'nonauto-%s'%splitlines[8]]) 1740 | WF.write(newline) 1741 | WF.write('\n') 1742 | else: 1743 | if splitlines[3] in pairnamelist or 'pre' in splitlines[3]: 1744 | newline = '\t'.join([splitlines[0], splitlines[1], splitlines[2], splitlines[3], splitlines[4], 1745 | splitlines[5], splitlines[6], splitlines[7], class_name, 'nonauto-%s'%splitlines[8]]) 1746 | WF.write(newline) 1747 | WF.write('\n') 1748 | 1749 | ## To merge nonautonomous intervals and do selection. 1750 | if os.path.exists(nonauto_alternative_file): 1751 | self.merge_overlaped_intervals(nonauto_alternative_file, op_representative, opnonauto_nest_alt, rep_type=True) 1752 | ## To output alternative nest insertions 1753 | if os.path.exists(opnonauto_nest_alt): 1754 | self.merge_overlaped_intervals(opnonauto_nest_alt, op_nest_rep, 'tmp.txt', rep_type=False) 1755 | ## To integrate orf file into representative file 1756 | # To obtain orf only insertions 1757 | Orfonly_file = ''.join([class_name, '/', '%s.orfonly.alternative.bed' % class_name]) 1758 | if os.path.exists(Orfonly_file): 1759 | with open(op_representative, 'a') as WF, open(Orfonly_file, 'r') as RF: 1760 | WF.write(RF.read()) 1761 | ## Remove intermediate files 1762 | if os.path.exists(opauto_nest_alt): 1763 | os.remove(opauto_nest_alt) 1764 | if os.path.exists(opnonauto_nest_alt): 1765 | os.remove(opnonauto_nest_alt) 1766 | 1767 | ## To output boundary check file and tir check file 1768 | with open('Boundary.tbl', 'w') as BF: 1769 | for id in self.Boundary_iden_dict: 1770 | for direction in self.Boundary_iden_dict[id]: 1771 | BF.write(''.join([id, '\t', direction, '\t', str(self.Boundary_iden_dict[id][direction]), '\n'])) 1772 | with open('TIR_count.tbl', 'w') as TF: 1773 | for id in self.Terminal_dict: 1774 | TF.write(''.join([id, '\t', str(self.Terminal_dict[id]), '\n'])) 1775 | 1776 | ## To add terminal markers for HLE2 1777 | for helen_file in Repsentative_file_list: 1778 | if re.findall('HLE2', helen_file): 1779 | self.heltentron_terminal(helentron_bed=helen_file) 1780 | 1781 | if os.path.exists('tmp.txt'): 1782 | os.remove('tmp.txt') 1783 | 1784 | op_representative = 'RC.representative.bed' 1785 | with open(op_representative, 'w') as wf: 1786 | for file in Repsentative_file_list: 1787 | if os.path.exists(file): 1788 | with open(file, 'r') as rf: 1789 | [wf.write(line) for line in rf] 1790 | os.remove(file) 1791 | 1792 | op_alternative = 'RC.alternative.bed' 1793 | with open(op_alternative, 'w') as wf: 1794 | for file in Alternative_file_list: 1795 | if os.path.exists(file): 1796 | with open(file, 'r') as rf: 1797 | [wf.write(line) for line in rf] 1798 | os.remove(file) 1799 | 1800 | ## To sort big file 1801 | if not os.path.exists(op_representative): 1802 | with open(op_representative, 'w') as F: 1803 | F.write('') 1804 | if not os.path.exists(op_alternative): 1805 | with open(op_alternative, 'w') as F: 1806 | F.write('') 1807 | try: 1808 | sort_pro = subprocess.Popen(['bash', SORT_PRO, op_representative, str(self.process_num)], 1809 | stdout=subprocess.DEVNULL) 1810 | sort_pro.wait() 1811 | sys.stdout.write("Sort representative files finished ...\n") 1812 | 1813 | sort_pro = subprocess.Popen(['bash', SORT_PRO, op_alternative, str(self.process_num)], 1814 | stdout=subprocess.DEVNULL) 1815 | sort_pro.wait() 1816 | sys.stdout.write("Sort alternative files finished ...\n") 1817 | 1818 | except: 1819 | sys.stdout.write("Sort representative files failed ...\n") 1820 | exit(0) 1821 | sequence_fa = 'RC.representative.fa' 1822 | ## Delete alternative file if empty 1823 | if not os.path.getsize(op_alternative): 1824 | os.remove(op_alternative) 1825 | ## To output fasta format file. 1826 | self.OutputSequence(op_representative, sequence_fa) 1827 | ## To output convinced pair list. 1828 | Convinced_pairlist = 'pairlist.tbl' 1829 | self.Convienced_LTS_RTS(op_representative, Convinced_pairlist) 1830 | 1831 | ## To remove tempary files 1832 | os.remove(self.CTRR_stem_loop_description) 1833 | os.remove(self.subtir_description) 1834 | os.remove(self.genome_size) 1835 | shutil.rmtree(self.bedtoolstmp) 1836 | if os.path.exists('GenomeDB'): 1837 | shutil.rmtree('GenomeDB') 1838 | if os.path.exists('genomes'): 1839 | shutil.rmtree('genomes') 1840 | #for class_name in RC_total_candidate_dict: 1841 | # if os.path.exists(class_name): 1842 | # shutil.rmtree(class_name) 1843 | if os.path.exists("boundary_align"): 1844 | shutil.rmtree("boundary_align") 1845 | if os.path.exists('Boundary.identity.tbl'): 1846 | os.remove('Boundary.identity.tbl') 1847 | 1848 | if __name__ == "__main__": 1849 | parser = argparse.ArgumentParser(description="heliano can detect and classify different variants of Helitron-like elements: HLE1 and HLE2. Please visit https://github.com/Zhenlisme/heliano/ for more information. Email us: zhen.li3@universite-paris-saclay.fr") 1850 | parser.add_argument("-g", "--genome", type=str, required=True, help="The genome file in fasta format.") 1851 | parser.add_argument("-w", "--window", type=int, default=10000, required=False, 1852 | help="To check terminal signals within a given window bp upstream and downstream of ORF ends. default is 10 kb.") 1853 | parser.add_argument("-dm", "--distance_domain", type=int, default=2500, required=False, 1854 | help="The distance between HUH and Helicase domain, default is 2500.") 1855 | parser.add_argument("-dn", "--distance_ts", type=int, default=0, required=False, 1856 | help="The maximum distance between LTS and RTS. If not specified, HELIANO will set it as two times window size plus the maximum ORF length.") 1857 | parser.add_argument("-pt", "--pair_helitron", type=int, default=1, required=False, choices=[0, 1], 1858 | help="For HLE1, its 5' and 3' terminal signal pairs should come from the same autonomous helitorn or not. 0: no, 1: yes (default).") 1859 | parser.add_argument("-is1", "--IS1", type=int, default=0, required=False, choices=[0, 1], 1860 | help="Set the insertion site of autonomous HLE1 as A and T. 0: no, 1: yes (default).") 1861 | parser.add_argument("-is2", "--IS2", type=int, default=0, required=False, choices=[0, 1], 1862 | help="Set the insertion site of autonomous HLE2 as T and T. 0: no, 1: yes (default).") 1863 | parser.add_argument("-sim_tir", "--simtir", type=int, default=100, required=False, choices=[100, 90, 80], 1864 | help="Set the simarity between short inverted repeats(TIRs) of HLE2. Default 100.") 1865 | parser.add_argument("-flank_sim", "--flank_sim", type=float, default=0.5, required=False, choices=[0.4, 0.5, 0.6, 0.7], 1866 | help="The cut-off to define false positive LTS/RTS. The lower the value, the more strigent. Default 0.5.") 1867 | parser.add_argument("-p", "--pvalue", type=float, required=False, default=1e-5, help="The p-value for fisher's exact test. default is 1e-5.") 1868 | parser.add_argument("-s", "--score", type=int, required=False, default=32, 1869 | help="The minimum bitscore of blastn for searching for homologous sequences of terminal signals. From 30 to 55, default is 32.") 1870 | parser.add_argument("--nearest", action='store_true', required=False, 1871 | help="If you use this parameter, you will use the reciprocal-nearest LTS-RTS pairs as final candidates. By default, HELIANO will try to use the reciprocal-farthest pairs.") 1872 | parser.add_argument("-ts", "--terminal_sequence", type=str, required=False, default='', help="The terminal sequence file. You can find it in the output of previous run (named as pairlist.tbl).") 1873 | parser.add_argument("--dis_denovo", action='store_true', required=False, 1874 | help="If you use this parameter, you refuse to search for LTS/RTS de novo, instead you will only use the LTS/RTS information described in the terminal sequence file.") 1875 | parser.add_argument("--multi_ts", action='store_true', required=False, 1876 | help="To allow an auto HLE to have multiple terminal sequences. If you enable this, you might find nonauto HLEs coming from the same auto HLE have different terminal sequences.") 1877 | parser.add_argument("-tb", "--table", type=int, required=False, choices=[0, 1, 2, 3], default=0, 1878 | help="""Code to use for the open reading fram prediction. 0: Standard (default); 1: Ciliate Macronuclear and Dasycladacean; 1879 | 2: Blepharisma Macronuclear; 3: Scenedesmus obliquus""") 1880 | parser.add_argument("-o", "--opdir", type=str, required=True, help="The output directory.") 1881 | parser.add_argument("-n", "--process", type=int, default=2, required=False, help="Maximum number of threads to be used.") 1882 | parser.add_argument("-v", "--version", action='version', version='%(prog)s 1.3.1') 1883 | Args = parser.parse_args() 1884 | if int(Args.score) < 30 or int(Args.score) >= 55: 1885 | sys.stderr.write("Error: The bitscore value should be greater than 30 and less than 55.\n") 1886 | exit(0) 1887 | if int(Args.distance_ts) < 0 or int(Args.window) < 0 or int(Args.distance_domain) < 0: 1888 | sys.stderr.write("Error: Parameter value should not be negative.\n") 1889 | exit(0) 1890 | ## To set and check dependency file path 1891 | HMMFILE = '_HMM_' 1892 | HEADERFILE = '_HEADER_' 1893 | FISHER_PRO = '_FISHER_' 1894 | BOUNDARY_PRO = '_BOUNDARY_' 1895 | SPLIT_JOINT_PRO = '_SPLIT_JOINT_' 1896 | SORT_PRO = '_SORTPRO_' 1897 | try: 1898 | BEDTOOLS_PATH = subprocess.check_output("which bedtools", shell=True).decode().rstrip() 1899 | BEDTOOLS_PATH = '/'.join(BEDTOOLS_PATH.split('/')[:-1]) 1900 | except: 1901 | print("Could not find bedtools path.") 1902 | exit(0) 1903 | try: 1904 | subprocess.check_output("which rnabob", shell=True) 1905 | except: 1906 | print("Could not find rnabob path.") 1907 | exit(0) 1908 | 1909 | try: 1910 | subprocess.check_output("which cd-hit-est", shell=True) 1911 | except: 1912 | print("Could not find cd-hit-est path.") 1913 | exit(0) 1914 | 1915 | try: 1916 | subprocess.check_output("which mafft", shell=True) 1917 | except: 1918 | print("Could not find mafft path.") 1919 | exit(0) 1920 | try: 1921 | subprocess.check_output("which hmmsearch", shell=True) 1922 | except: 1923 | print("Could not find hmmsearch path.") 1924 | exit(0) 1925 | 1926 | try: 1927 | subprocess.check_output("which getorf", shell=True) 1928 | except: 1929 | print("Could not find getorf path.") 1930 | exit(0) 1931 | 1932 | try: 1933 | subprocess.check_output("which gt", shell=True) 1934 | except: 1935 | print('Could not find genometools path.') 1936 | exit(0) 1937 | 1938 | try: 1939 | subprocess.check_output("which dialign2-2", shell=True) 1940 | except: 1941 | print('Could not find dialign2 path.') 1942 | exit(0) 1943 | 1944 | try: 1945 | subprocess.check_output("which blastn", shell=True) 1946 | except: 1947 | print('Could not find genometools path.') 1948 | exit(0) 1949 | 1950 | if not os.path.exists(HMMFILE): 1951 | print("Hmmer model file not found!") 1952 | exit(0) 1953 | if not os.path.exists(HEADERFILE): 1954 | print('header lcv file not found!') 1955 | exit(0) 1956 | if not os.path.exists(BOUNDARY_PRO): 1957 | print('Boundary check program not found!') 1958 | exit(0) 1959 | if not os.path.exists(FISHER_PRO): 1960 | print("Fisher's exact test program not found!") 1961 | exit(0) 1962 | if not os.path.exists(SPLIT_JOINT_PRO): 1963 | print("Split bed file program not found!") 1964 | exit(0) 1965 | 1966 | HomoSearch = Homologous_search(HMMFILE, os.path.abspath(Args.genome), os.path.abspath(Args.opdir), 1967 | HEADERFILE, Args.window, Args.distance_domain, Args.distance_ts, Args.pvalue, 1968 | Args.process, Args.table) 1969 | HomoSearch.main() 1970 | 1971 | --------------------------------------------------------------------------------