File size: 6,562 Bytes
5e797a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
"""FCC related functions

NOTE: This functions were ported directly from `https://github.com/haddocking/fcc`!
"""


class Element:
    """Defines a 'clusterable' Element"""

    __slots__ = ["name", "cluster", "neighbors"]

    def __init__(self, name):
        self.name = name
        self.cluster = 0
        self.neighbors = set()

    def add_neighbor(self, neighbor):
        """Adds another element to the neighbor list"""
        self.neighbors.add(neighbor)

    def assign_cluster(self, clust_id):
        """Assigns the Element to Cluster. 0 if unclustered"""
        self.cluster = clust_id


class Cluster:
    """Defines a Cluster. A Cluster is created with a name and a center (Element class)"""

    __slots__ = ["name", "center", "members"]

    def __init__(self, name, center):
        self.name = name
        self.center = center

        self.members = []

        self.populate()

    def __len__(self):
        return len(self.members) + 1  # +1 Center

    def populate(self):
        """
        Populates the Cluster member list through the
        neighbor list of its center.
        """

        name = self.name
        # Assign center
        ctr = self.center
        ctr.assign_cluster(name)

        mlist = self.members
        # Assign members
        ctr_nlist = (n for n in ctr.neighbors if not n.cluster)
        for e in ctr_nlist:
            mlist.append(e)
            e.assign_cluster(name)

    def add_member(self, element):
        """
        Adds one single element to the cluster.
        """
        line = self.members
        line.append(element)
        element.assign_cluster(self.name)


def cluster_elements(e_pool, threshold):
    """
    Groups Elements within a given threshold
    together in the same cluster.
    """

    cluster_list = []
    threshold -= 1  # Account for center
    ep = e_pool
    cn = 1  # Cluster Number
    while 1:
        # Clusterable elements
        ce = [e for e in ep if not ep[e].cluster]
        if not ce:  # No more elements to cluster
            break

        # Select Cluster Center
        # Element with largest neighbor list
        ctr_nlist, ctr = sorted(
            [(len([se for se in ep[e].neighbors if not se.cluster]), e) for e in ce]
        )[-1]

        # Cluster until length of remaining elements lists are above threshold
        if ctr_nlist < threshold:
            break

        # Create Cluster
        c = Cluster(cn, ep[ctr])
        cn += 1
        cluster_list.append(c)

    return ep, cluster_list


def output_clusters(handle, cluster):
    """Outputs the cluster name, center, and members."""

    write = handle.write

    for c in cluster:
        write("Cluster %s -> %s " % (c.name, c.center.name))
        for m in sorted(c.members, key=lambda k: k.name):
            write("%s " % m.name)
        write("\n")


def load_matrix(matrix_path) -> list[tuple[int, int, float, float]]:
    """Read in a four column matrix (1 2 0.123 0.456\n)

    Parameters
    ----------
    matrix_path : str or Path
        Path to the matrix file

    Returns
    -------
    matrix : list[tuple[int, int, float, float]]
        Content of the matrix
    """
    matrix: list[tuple[int, int, float, float]] = []
    with open(matrix_path, "r") as fin:
        for line in fin:
            ref, mobi, d_rm, d_mr = line.split()
            ref = int(ref)
            mobi = int(mobi)
            d_rm = float(d_rm)
            d_mr = float(d_mr)
            matrix.append((ref, mobi, d_rm, d_mr))
    return matrix


def create_elements(matrix, cutoff_param, strictness):
    """Creates an dictionary of Elements.

    The strictness factor is a <float> that multiplies by the cutoff
    to produce a new cutoff for the second half of the matrix. Used to
    allow some variability while keeping very small interfaces from clustering
    with anything remotely similar.
    """

    cutoff_param = float(cutoff_param)
    partner_cutoff = float(cutoff_param) * float(strictness)

    elements = {}

    # Loop over matrix rows
    for row in matrix:
        ref, mobi, d_rm, d_mr = row

        # Create or Retrieve Elements
        if ref not in elements:
            r = Element(ref)
            elements[ref] = r
        else:
            r = elements[ref]

        if mobi not in elements:
            m = Element(mobi)
            elements[mobi] = m
        else:
            m = elements[mobi]

            # Assign neighbors
        if d_rm >= cutoff_param and d_mr >= partner_cutoff:
            r.add_neighbor(m)
        if d_mr >= cutoff_param and d_rm >= partner_cutoff:
            m.add_neighbor(r)

    return elements


def parse_contact_file(f_list, ignore_chain):
    """Parses a list of contact files."""

    if ignore_chain:
        contacts = [
            [int(line[0:5] + line[6:-1]) for line in open(con_f)]
            for con_f in f_list
            if con_f.strip()
        ]
    else:
        contacts = [
            set([int(line) for line in open(con_f)])
            for con_f in f_list
            if con_f.strip()
        ]

    return contacts


def calculate_fcc(list_a, list_b):
    """
    Calculates the fraction of common elements between two lists
    taking into account chain IDs
    """

    cc = len(list_a.intersection(list_b))
    cc_v = len(list_b.intersection(list_a))

    return cc, cc_v


def calculate_fcc_nc(list_a, list_b):
    """
    Calculates the fraction of common elements between two lists
    not taking into account chain IDs. Much Slower.
    """

    largest, smallest = sorted([list_a, list_b], key=len)
    ncommon = len([ele for ele in largest if ele in smallest])
    return ncommon, ncommon


def calculate_pairwise_matrix(contacts, ignore_chain):
    """Calculates a matrix of pairwise fraction of common contacts (FCC).
    Outputs numeric indexes.

    contacts: list_of_unique_pairs_of_residues [set/list]

    Returns pairwise matrix as an iterator, each entry in the form:
    FCC(cplx_1/cplx_2) FCC(cplx_2/cplx_1)
    """

    contact_lengths = []
    for con in contacts:
        try:
            ic = 1.0 / len(con)
        except ZeroDivisionError:
            ic = 0
        contact_lengths.append(ic)

    if ignore_chain:
        calc_fcc = calculate_fcc_nc
    else:
        calc_fcc = calculate_fcc

    for i in range(len(contacts)):

        for k in range(i + 1, len(contacts)):
            cc, cc_v = calc_fcc(contacts[i], contacts[k])
            fcc, fcc_v = cc * contact_lengths[i], cc * contact_lengths[k]
            yield i + 1, k + 1, fcc, fcc_v