Mercurial > repos > vimalkumarvelayudhan > riboseqr_wrapper
comparison riboseqr/triplet.py @ 0:c34c364ce75d
First commit
| author | Vimalkumar Velayudhan <vimal@biotechcoder.com> |
|---|---|
| date | Tue, 21 Jul 2015 14:48:39 +0100 |
| parents | |
| children | 423ad61697c4 |
comparison
equal
deleted
inserted
replaced
| -1:000000000000 | 0:c34c364ce75d |
|---|---|
| 1 #!/usr/bin/env python | |
| 2 import os | |
| 3 import sys | |
| 4 import argparse | |
| 5 import logging | |
| 6 import rpy2.robjects as robjects | |
| 7 | |
| 8 import utils | |
| 9 | |
| 10 rscript = '' | |
| 11 R = robjects.r | |
| 12 | |
| 13 | |
| 14 def run_rscript(command=None): | |
| 15 """Run R command, log it, append to rscript""" | |
| 16 global rscript | |
| 17 if not command: | |
| 18 return | |
| 19 logging.debug(command) | |
| 20 rscript += '{}\n'.format(command) | |
| 21 output = R(command) | |
| 22 return output | |
| 23 | |
| 24 | |
| 25 def find_periodicity( | |
| 26 rdata_load='Prepare.rda', start_codons='ATG', stop_codons='TAG,TAA,TGA', | |
| 27 fasta_file=None, include_lengths='25:30', analyze_plot_lengths='26:30', | |
| 28 text_legend='Frame 0, Frame 1, Frame 2', rdata_save='Periodicity.rda', | |
| 29 html_file='Periodicity-report.html', output_path=os.getcwd()): | |
| 30 """Plot triplet periodicity from prepared R data file. """ | |
| 31 logging.debug('{}'.format(R('sessionInfo()'))) | |
| 32 cmd = 'suppressMessages(library(riboSeqR))' | |
| 33 run_rscript(cmd) | |
| 34 | |
| 35 logging.debug('Loading saved R data file') | |
| 36 cmd = 'load("{}")'.format(rdata_load) | |
| 37 run_rscript(cmd) | |
| 38 | |
| 39 # R("""options(showTailLines=Inf)""") | |
| 40 starts, stops = (utils.process_args(start_codons, ret_mode='charvector'), | |
| 41 utils.process_args(stop_codons, ret_mode='charvector')) | |
| 42 | |
| 43 cmd = ('fastaCDS <- findCDS(fastaFile={0!r}, startCodon={1}, ' | |
| 44 'stopCodon={2})'.format(fasta_file, starts, stops)) | |
| 45 run_rscript(cmd) | |
| 46 | |
| 47 logging.debug('Potential coding sequences using start codon (ATG) and ' | |
| 48 'stop codons TAG, TAA, TGA') | |
| 49 logging.debug('{}\n'.format(R['fastaCDS'])) | |
| 50 | |
| 51 cmd = """fCs <- frameCounting(riboDat, fastaCDS, lengths={0}) | |
| 52 fS <- readingFrame(rC=fCs, lengths={1}); fS""".\ | |
| 53 format(include_lengths, analyze_plot_lengths) | |
| 54 run_rscript(cmd) | |
| 55 | |
| 56 logging.debug('riboDat \n{}\n'.format(R['riboDat'])) | |
| 57 logging.debug('fCs\n{0}\n'.format(R['fCs'])) | |
| 58 logging.debug('Reading frames for each n-mer\n{}'.format(R['fS'])) | |
| 59 | |
| 60 legend = utils.process_args(text_legend, ret_mode='charvector') | |
| 61 | |
| 62 for fmat in ('pdf', 'png'): | |
| 63 if fmat == 'png': | |
| 64 cmd = '{0}(file="{1}", type="cairo")' | |
| 65 else: | |
| 66 cmd = '{0}(file="{1}")' | |
| 67 run_rscript(cmd.format(fmat, os.path.join( | |
| 68 output_path, '{0}.{1}'.format('Periodicity-plot', fmat)))) | |
| 69 run_rscript('plotFS(fS, legend.text = {0})'.format(legend)) | |
| 70 run_rscript('dev.off()') | |
| 71 | |
| 72 run_rscript('save("fCs", "fS", "riboDat", "fastaCDS", ' | |
| 73 'file="{}", compress=FALSE)'.format(rdata_save)) | |
| 74 | |
| 75 html = '<h2>Triplet periodicity - results</h2><hr>' | |
| 76 html += ('<h4>Results of reading frame analysis</h4>' | |
| 77 '<pre>{}</pre><br>'.format(R['fS'])) | |
| 78 html += ('<p>Lengths used for reading frame analysis - <code>{0}</code>' | |
| 79 '<br>Lengths selected for the plot - <code>{1}</code>' | |
| 80 '</p>'.format(include_lengths, analyze_plot_lengths)) | |
| 81 html += ('<p><img src="Periodicity-plot.png" border="1" ' | |
| 82 'alt="Triplet periodicity plot" />' | |
| 83 '<br><a href="Periodicity-plot.pdf">PDF version</a></p>') | |
| 84 | |
| 85 logging.debug('\n{:#^80}\n{}\n{:#^80}\n'.format( | |
| 86 ' R script for this session ', rscript, ' End R script ')) | |
| 87 | |
| 88 with open(os.path.join(output_path, 'periodicity.R'), 'w') as r: | |
| 89 r.write(rscript) | |
| 90 | |
| 91 html += ('<h4>R script for this session</h4>' | |
| 92 '<p><a href="periodicity.R">periodicity.R</a></p>' | |
| 93 '<p>Next step: <em>Metagene analysis</em></p>') | |
| 94 | |
| 95 with open(html_file, 'w') as f: | |
| 96 f.write(html) | |
| 97 | |
| 98 | |
| 99 if __name__ == '__main__': | |
| 100 | |
| 101 parser = argparse.ArgumentParser( | |
| 102 description='Plot triplet periodicity for different read lengths.') | |
| 103 | |
| 104 # required arguments | |
| 105 flags = parser.add_argument_group('required arguments') | |
| 106 flags.add_argument( | |
| 107 '--rdata_load', required=True, | |
| 108 help='riboSeqR data from input preparation step (Prepare.rda)') | |
| 109 flags.add_argument( | |
| 110 '--fasta_file', required=True, | |
| 111 help='FASTA file of the reference transcriptome') | |
| 112 | |
| 113 # optional arguments | |
| 114 parser.add_argument( | |
| 115 '--start_codons', | |
| 116 help='Start codon(s) to use. (default: %(default)s)', default='ATG') | |
| 117 parser.add_argument( | |
| 118 '--stop_codons', help='Stop codon(s) to use. (default: %(default)s)', | |
| 119 default='TAG, TAA, TGA') | |
| 120 parser.add_argument( | |
| 121 '--include_lengths', | |
| 122 help='Lengths of ribosome footprints to be included ' | |
| 123 '(default: %(default)s)', default='25:30') | |
| 124 parser.add_argument( | |
| 125 '--analyze_plot_lengths', | |
| 126 help='Lenghts of reads to be analyzed for frame-shift and plotting ' | |
| 127 '(default: %(default)s)', default='26:30') | |
| 128 parser.add_argument( | |
| 129 '--text_legend', | |
| 130 help='Text for legend used in the plot (default: %(default)s)', | |
| 131 default='Frame 0, Frame 1, Frame 2') | |
| 132 parser.add_argument( | |
| 133 '--rdata_save', help='File to write RData to (default: %(default)s)', | |
| 134 default='Periodicity.rda') | |
| 135 parser.add_argument('--html_file', help='Output file for results (HTML)') | |
| 136 parser.add_argument('--output_path', | |
| 137 help='Files are saved in this directory') | |
| 138 parser.add_argument( | |
| 139 '--debug', help='Produce debug output', action='store_true') | |
| 140 | |
| 141 args = parser.parse_args() | |
| 142 if args.debug: | |
| 143 logging.basicConfig(format='%(module)s: %(levelname)s - %(message)s', | |
| 144 level=logging.DEBUG, stream=sys.stdout) | |
| 145 logging.debug('Supplied Arguments\n{}\n'.format(vars(args))) | |
| 146 | |
| 147 if not os.path.exists(args.output_path): | |
| 148 os.mkdir(args.output_path) | |
| 149 | |
| 150 find_periodicity( | |
| 151 rdata_load=args.rdata_load, start_codons=args.start_codons, | |
| 152 stop_codons=args.stop_codons, fasta_file=args.fasta_file, | |
| 153 include_lengths=args.include_lengths, | |
| 154 analyze_plot_lengths=args.analyze_plot_lengths, | |
| 155 text_legend=args.text_legend, | |
| 156 rdata_save=args.rdata_save, html_file=args.html_file, | |
| 157 output_path=args.output_path) | |
| 158 logging.debug("Done!") |
