comparison damid_to_bedgraph.py @ 0:755cbe6825b5 draft

planemo upload for repository https://github.com/galaxyproject/tools-iuc/tree/master/tools/damid_deseq2_to_bedgraph commit 98722d2ca8205595f032361072aaab450e5f4f83
author mvdbeek
date Fri, 14 Dec 2018 06:27:41 -0500
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:755cbe6825b5
1 from collections import OrderedDict
2
3 import click
4 import numpy as np
5 import pandas as pd
6 import traces
7
8
9 def order_index(df):
10 """
11 Split chr_start_stop in df index and order by chrom and start.
12 """
13 idx = df.index.str.split('_')
14 idx = pd.DataFrame.from_records(list(idx))
15
16 idx.columns = ['chr', 'start', 'stop']
17 idx = idx.astype(dtype={"chr": "object",
18 "start": "int32",
19 "stop": "int32"})
20 coordinates = idx.sort_values(['chr', 'start'])
21 df.index = np.arange(len(df.index))
22 df = df.loc[coordinates.index]
23 df = coordinates.join(df)
24 # index is center of GATC site
25 df.index = df['start'] + 2
26 return df
27
28
29 def interpolate_values(df, sampling_width=100):
30 result = []
31 for chrom in df['chr'].unique():
32 chrom_df = df[df['chr'] == chrom]
33 time_series = traces.TimeSeries(chrom_df['log2FC'])
34 s = pd.DataFrame.from_records(time_series.sample(sampling_width, interpolate='linear'))
35 # Calculate new start and end of interpolated region
36 start = s[0] - int(sampling_width / 2)
37 start.loc[start < 0] = 1
38 end = s[0] + int(sampling_width / 2)
39 result.append(pd.DataFrame(OrderedDict([('chr', chrom), ('start', start), ('end', end), ('score', s[1])])))
40 return pd.concat(result)
41
42
43 @click.command()
44 @click.argument('input_path', type=click.Path(exists=True), required=True)
45 @click.argument('output_path', type=click.Path(exists=False), required=True)
46 @click.option('--resolution', help="Interpolate log2 fold change at this resolution (in basepairs)", default=50)
47 def deseq2_to_bedgraph(input_path, output_path, resolution=50):
48 """Convert deseq2 output on GATC fragments to bedgraph file with interpolated values."""
49 df = pd.read_csv(input_path, sep='\t', header=None, index_col=0, usecols=[0, 2], names=['GATC', 'log2FC'])
50 df = df[~df.index.str.contains('\.')]
51 df = order_index(df)
52 r = interpolate_values(df, sampling_width=resolution)
53 r.to_csv(output_path, sep='\t', header=None, index=None)
54
55
56 if __name__ == '__main__':
57 deseq2_to_bedgraph()