Skip to content

Commit 49f5f82

Browse files
Bugfix concorrenza visualizzazione
1 parent 2be42d6 commit 49f5f82

File tree

3 files changed

+73
-71
lines changed

3 files changed

+73
-71
lines changed

correlation_window.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -56,10 +56,10 @@ def create_table(self, obj):
5656
tableWidget.setSortingEnabled(False)
5757

5858
rowPosition = tableWidget.rowCount() # necessary even when there are no rows in the table
59+
df_of_interacton = pd.DataFrame([edge1s, freqs1, inter_labels, edge2s, freqs2, corr_vals, p_vals]).transpose()
60+
df = df.append(df_of_interacton)
5961

60-
df = df.append(pd.DataFrame([edge1s, freqs1, inter_labels, edge2s, freqs2, corr_vals, p_vals]).transpose())
61-
62-
self.parent.log("{} {} interactions correlates/anti-correlates".format(len(df), inter))
62+
self.parent.log("{} {} interactions correlates/anti-correlates".format(len(df_of_interacton), inter))
6363

6464
df = df.sort_values([0, 3, 5], ascending=(True, True, False))
6565

@@ -147,11 +147,11 @@ def show_corr_fn(self):
147147
else:
148148
anti_set.add(edge2)
149149

150-
self.parent.visualize(selection="edge1", color="white", int_type=inter, edge_set=sele_set)
150+
self.parent.visualize(selection="edge1", color="white", int_type=inter)
151151
if len(corr_set) > 0:
152-
self.parent.visualize(selection="edge2", color="blue", int_type=inter, edge_set=corr_set)
152+
self.parent.visualize(selection="edge2", color="blue", int_type=inter)
153153
if len(anti_set) > 0:
154-
self.parent.visualize(selection="edge2", color="red", int_type=inter, edge_set=anti_set)
154+
self.parent.visualize(selection="edge2", color="red", int_type=inter)
155155
self.parent.log("Selection edge1 contains all the residues from the edges selected in the first column",
156156
timed=False)
157157
self.parent.log("Selection edge2 contains all the residues from the edges selected in the second column",

main_window.py

Lines changed: 34 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -288,7 +288,7 @@ def refresh_sele(self):
288288
else:
289289
self.widg.visualize_btn.setText("Execute Ring")
290290

291-
def visualize(self, selection=None, color=None, int_type=None, edge_set=None):
291+
def visualize(self, selection=None, color=None, int_type=None):
292292
from pymol import stored
293293

294294
if selection:
@@ -332,8 +332,7 @@ def draw():
332332
stored.tmp = ""
333333
cmd.iterate_state(state=state, selection=obj,
334334
expression='stored.tmp = stored.coords.setdefault("{}/{}/{}"'
335-
'.format(chain, resi, name), [x,y,z])',
336-
)
335+
'.format(chain, resi, name), [x,y,z])')
337336

338337
interactions_per_type = dict()
339338

@@ -343,33 +342,41 @@ def draw():
343342
node2 = Node(nodeId2)
344343
edge = Edge(node1, node2)
345344

346-
try:
347-
freq = conn_freq[intType][edge] * 100
348-
except KeyError:
349-
freq = 0.5 * 100
345+
# Global filters
346+
if node1.id_tuple() not in stored.chain_resi or node2.id_tuple() not in stored.chain_resi:
347+
continue
350348

349+
# Apply filters if selection is not present
351350
if not selection:
351+
try:
352+
freq = conn_freq[intType][edge] * 100
353+
except KeyError:
354+
freq = 0.5 * 100
355+
# Interchain
352356
if self.widg.interchain.isChecked() and node1.chain == node2.chain:
353357
continue
358+
# Intrachain
354359
if self.widg.intrachain.isChecked() and node1.chain != node2.chain:
355360
continue
361+
# Frequency
362+
if not self.widg.min_freq.value() <= freq <= self.widg.max_freq.value():
363+
continue
364+
else:
365+
# Apply filter if selection is present
366+
if not (int_type == intType or int_type == "ALL"):
367+
continue
356368

357-
if node1.id_tuple() in stored.chain_resi and node2.id_tuple() in stored.chain_resi \
358-
and (selection or self.widg.min_freq.value() <= freq <= self.widg.max_freq.value()) \
359-
and ((selection and (int_type == intType or int_type == "ALL") and
360-
edge in edge_set) or not selection):
361-
interactions_per_type.setdefault(intType, [])
362-
363-
t = tuple()
364-
if "," in atom1:
365-
t += (atom1,)
366-
else:
367-
t += ("{}/{}/{}".format(node1.chain, str(node1.resi), atom1),)
368-
if "," in atom2:
369-
t += (atom2,)
370-
else:
371-
t += ("{}/{}/{}".format(node2.chain, str(node2.resi), atom2),)
372-
interactions_per_type[intType].append(t)
369+
interactions_per_type.setdefault(intType, [])
370+
t = tuple()
371+
if "," in atom1:
372+
t += (atom1,)
373+
else:
374+
t += ("{}/{}/{}".format(node1.chain, str(node1.resi), atom1),)
375+
if "," in atom2:
376+
t += (atom2,)
377+
else:
378+
t += ("{}/{}/{}".format(node2.chain, str(node2.resi), atom2),)
379+
interactions_per_type[intType].append(t)
373380

374381
for intType, interactions in interactions_per_type.items():
375382
draw_links(interactions,
@@ -386,7 +393,10 @@ def draw():
386393
self.slider_radius_change()
387394
self.slider_transp_change()
388395

389-
cmd.async_(draw)
396+
if selection is None:
397+
cmd.async_(draw)
398+
else:
399+
draw()
390400

391401
def create_node_edges_sele(self, model_name, is_sele, obj):
392402
members = ""

utilities.py

Lines changed: 33 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -297,45 +297,35 @@ def draw_links(interactions, color, object_name, coords, state):
297297
def calculate_correlation(obj, frames, min_presence=0.05, max_presence=0.95, coeff_thresh=0.5, p_thresh=0.3,
298298
int_type="HBOND"):
299299
all_cm = dict()
300-
try:
301-
if int_type == "ALL":
302-
for interaction in intTypeMap.keys():
303-
all_cm[interaction] = pd.read_csv('/tmp/ring/md/{}.cm_{}'.format(obj, interaction), sep=' ',
304-
header=None)
305-
else:
306-
all_cm[int_type] = pd.read_csv('/tmp/ring/md/{}.cm_{}'.format(obj, int_type), sep=' ', header=None)
307-
except FileNotFoundError:
308-
return
300+
nodes = []
301+
if int_type == "ALL":
302+
to_read = intTypeMap.keys()
303+
else:
304+
to_read = [int_type]
309305

310-
contacts_sparse = dict()
311-
for j in range(1, frames + 1):
312-
if int_type == "ALL":
313-
interactions = intTypeMap.keys()
314-
else:
315-
interactions = [int_type]
316-
for interaction in interactions:
317-
df = all_cm[interaction][all_cm[interaction][0] == j]
318-
nodes = df[1]
306+
for interaction in to_read:
307+
all_cm[interaction] = pd.read_csv('/tmp/ring/md/{}.cm_{}'.format(obj, interaction), sep=' ',
308+
header=None)
309+
if len(nodes) == 0:
310+
nodes = all_cm[interaction][all_cm[interaction][0] == 1][1]
319311
nodes = [Node(x) for x in nodes]
312+
313+
conn_freq = get_freq(obj)
314+
contacts_sparse = dict()
315+
for frame in range(0, frames):
316+
for interaction in to_read:
317+
df = all_cm[interaction][all_cm[interaction][0] == frame + 1]
320318
df = df.iloc[:, 2:]
321319
matrix = df.values
322320
matrix[np.triu_indices(matrix.shape[0])] = 0
323-
for i in np.argwhere(matrix > 0):
324-
node1 = nodes[i[0]]
325-
node2 = nodes[i[1]]
321+
for i, j in np.argwhere(matrix > 0):
322+
node1 = nodes[i]
323+
node2 = nodes[j]
326324
edge = Edge(sorted([node1, node2]))
327-
contacts_sparse.setdefault(edge, dict())
328-
contacts_sparse[edge].setdefault(j - 1, 0)
329-
contacts_sparse[edge][j - 1] += 1
330-
331-
to_pop = []
332-
for k, v in contacts_sparse.items():
333-
presence = len(v) / frames
334-
if not min_presence < presence < max_presence:
335-
to_pop.append(k)
336-
337-
for k in to_pop:
338-
contacts_sparse.pop(k)
325+
if min_presence < conn_freq[interaction][edge] < max_presence:
326+
contacts_sparse.setdefault(edge, dict())
327+
contacts_sparse[edge].setdefault(frame, 0)
328+
contacts_sparse[edge][frame] += 1
339329

340330
z = np.zeros((len(contacts_sparse), frames))
341331
for i, contacts_for_frame in enumerate(contacts_sparse.values()):
@@ -345,14 +335,15 @@ def calculate_correlation(obj, frames, min_presence=0.05, max_presence=0.95, coe
345335
coeffs_matr = np.ones((z.shape[0], z.shape[0])) * np.nan
346336
p_matr = np.ones((z.shape[0], z.shape[0])) * np.nan
347337

348-
for i in range(z.shape[0]):
349-
for j in range(z.shape[0]):
350-
if i != j:
351-
corr_coeff, p_val = pearsonr(z[i], z[j])
352-
if p_val < p_thresh and (corr_coeff > coeff_thresh or corr_coeff < -coeff_thresh):
353-
coeffs_matr[i, j] = corr_coeff
354-
p_matr[i, j] = p_val
338+
indexes = np.triu_indices(z.shape[0], k=1)
339+
for i, j in zip(indexes[0], indexes[1]):
355340

341+
corr_coeff, p_val = pearsonr(z[i], z[j])
342+
if p_val < p_thresh and (corr_coeff > coeff_thresh or corr_coeff < -coeff_thresh):
343+
coeffs_matr[i, j] = corr_coeff
344+
p_matr[i, j] = p_val
345+
p_matr[np.tril_indices_from(p_matr)] = p_matr[np.triu_indices_from(p_matr)]
346+
coeffs_matr[np.tril_indices_from(coeffs_matr)] = coeffs_matr[np.triu_indices_from(coeffs_matr)]
356347
return list(contacts_sparse.keys()), coeffs_matr, p_matr
357348

358349

@@ -476,4 +467,5 @@ def export_network_graph(model):
476467

477468

478469
if __name__ == '__main__':
479-
export_network_graph('2h9r')
470+
# export_network_graph('2h9r')
471+
calculate_correlation("trj_cl", 20)

0 commit comments

Comments
 (0)