-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdistance_analysis.py
More file actions
178 lines (153 loc) · 5.59 KB
/
distance_analysis.py
File metadata and controls
178 lines (153 loc) · 5.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
from argparse import ArgumentParser
from operator import itemgetter
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import sys
from itertools import combinations
from scaffold import Longreads
parser = ArgumentParser()
parser.add_argument("inputfiles", help="Input Files in Error-Rate or PAF format", nargs="+")
parser.add_argument("summaryfile", help="Contig distance summary file")
parser.add_argument("linename", help="Name of cell line")
parser.add_argument("--blacklistfile", help="File containing long read ids where certain contig mappings should be ignored.")
parser.add_argument("--include_ambigious", help="Include ambigious contigs", action="store_true", default=False)
args = parser.parse_args()
reads = {}
greads = {}
cgreads = []
ambigious_contigs = set()
blacklist = {}
blacklist_fullread = set()
blacklist_contigs = set()
if args.blacklistfile:
with open(args.blacklistfile) as f:
for line in f:
sline = line.split()
if sline[0] == "contig":
blacklist_contigs.add(sline[1])
if sline[1] == "all":
blacklist_fullread.add(sline[0])
else:
blacklist[sline[0]] = sline[1]
lrs = Longreads(args.inputfiles, blacklist, args.linename)
lrs.filter_contigcounts(2)
lrs.turn_longreads_around()
lrs.sort_contigs_in_reads()
lrs = lrs.lreads
#print(greads)
distances = {}
# get distances of all neighbouring overlaps
'''
for rid in greads:
oviter = iter(greads[rid]["overlaps"])
#print(ov)
try:
ovold = next(oviter)
if ovold["contig"].startswith("chr"):
continue
except StopIteration:
continue
while True:
try:
ovnew = next(oviter)
if ovnew["contig"].startswith("chr"):
continue
except StopIteration:
break
#print("distance between " + ovold["contig"] + " and " + ovnew["contig"] + ": " + str(ovnew["scr"] - ovold["ecr"]- ovold["lc"] + ovold["ecc"] - ovnew["scc"]))
if ovnew["contig"] == ovold["contig"]:
continue
if ovnew["strand"] == ovold["strand"]:
distance = ovnew["scr"] - ovold["ecr"]- (ovold["lc"] - ovold["ecc"]) - ovnew["scc"] + 1
else:
continue
if int(ovold["contig"].rstrip(args.linename)) < int(ovnew["contig"].rstrip(args.linename)):
cstring = ovold["contig"] + "_" + ovnew["contig"]
else:
cstring = ovnew["contig"] + "_" + ovold["contig"]
if cstring in distances:
distances[cstring].append(distance)
else:
distances[cstring] = [distance]
ovold = ovnew
'''
# get distances of all overlaps
for rid in lrs:
for item in combinations(lrs[rid]['maps'], 2):
ovold, ovnew = item
if ovnew["name"].startswith("chr") or ovold["name"].startswith("chr"):
continue
if ovnew["name"] in ambigious_contigs or ovold["name"] in ambigious_contigs:
continue
if "_" in ovnew["name"] or "_" in ovold["name"]:
continue
if ovnew["name"] == ovold["name"]:
continue
if ovnew["strand"] == 1 or ovold["strand"] == 1:
continue
distance = ovnew["scr"] - ovold["ecr"]- (ovold["lenc"] - ovold["ecc"]) - ovnew["scc"] + 1
cstring = ovold["name"] + "_" + ovnew["name"]
if cstring in distances:
distances[cstring].append(distance)
else:
distances[cstring] = [distance]
#print(combo)
for key, value in distances.items():
#print(str(key) + " " + str(value))
if len(value)>1:
#print(str(key) + "\t" + str(value))
pass
distances2 = {}
with open(args.summaryfile) as f:
for line in f:
sline = line.split()
ctg1 = sline[0].split("_")[0].strip("+").strip("-")
ctg2 = sline[0].split("_")[1].strip("+").strip("-")
if line.startswith("-"):
continue
if sline[1] == "NA":
continue
if float(sline[4]) > 2:
continue
moddist = float(sline[1])
#if int(ctg1.rstrip(args.linename)) < int(ctg2.rstrip(args.linename)):
cstr = ctg1+"_"+ctg2
#else:
# cstr = ctg2+"_"+ctg1
if cstr in distances2:
if abs(moddist) < abs(distances2[cstr]):
distances2[cstr] = moddist
else:
distances2[cstr] = moddist
for name, dist in distances.items():
if name in distances2:
dist2 = distances2[name]
else:
dist2 = "-"
name1, name2 = name.split("_")
print("\t".join([name1, name2, str(dist), str(dist2)]))
df = pd.DataFrame.from_dict([distances, distances2])
#df.rename(index=
dc = df.T.rename(columns={0:'longread',1:'shortread'})
dc["longread_mean"] = dc.longread.apply(np.mean)
#dc['longread'] = np.mean(dc.longread)
dd = dc.dropna()
#get interesting differences
#print(dd[abs(dd['longread_mean'] - dd['shortread']) > 150])
#print(dd)
sthsth = []
for item in dd['longread_mean']:
sthsth.append(item < 0)
for idx, item in enumerate(dd['shortread']):
sthsth[idx] = sthsth[idx] or item < 0
#for name in dd[sthsth].index.values:
# print(name)
#print(dd[dd['longread_mean'] <= -20])
#print(dd.index.values)
plt.scatter(dd['longread_mean'], dd['shortread'],s= 6, alpha = 0.7)
plt.xlabel("Long Read Distances (mean: " + "{:.3f}".format(np.mean(dd['longread_mean'])) + ")")
#plt.xlabel("Long Read Distances")
plt.ylabel("Short Read Distances (mean: " + "{:.3f}".format(np.mean(dd['shortread'])) + ")")
#plt.ylabel("Short Read Distances")
plt.savefig('distances_scatter.pdf')