-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCOPsExtension.py
226 lines (186 loc) · 10.3 KB
/
COPsExtension.py
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
"""
"""
#=========================================================================================
# Licence, Reference and Credits
#=========================================================================================
__copyright__ = "Copyright (C) CCPN project (https://www.ccpn.ac.uk) 2014 - 2022"
__credits__ = ("Ed Brooksbank, Joanna Fox, Victoria A Higman, Luca Mureddu, Eliza Płoskoń",
"Timothy J Ragan, Brian O Smith, Gary S Thompson & Geerten W Vuister")
__licence__ = ("CCPN licence. See https://ccpn.ac.uk/software/licensing/")
__reference__ = ("Skinner, S.P., Fogh, R.H., Boucher, W., Ragan, T.J., Mureddu, L.G., & Vuister, G.W.",
"CcpNmr AnalysisAssign: a flexible platform for integrated NMR analysis",
"J.Biomol.Nmr (2016), 66, 111-124, http://doi.org/10.1007/s10858-016-0060-y")
#=========================================================================================
# Last code modification
#=========================================================================================
__modifiedBy__ = "$modifiedBy: Luca Mureddu $"
__dateModified__ = "$dateModified: 2022-06-29 11:57:45 +0100 (Wed, June 29, 2022) $"
__version__ = "$Revision: 3.1.0 $"
#=========================================================================================
# Created
#=========================================================================================
__author__ = "$Author: Harrison Wang $"
__date__ = "$Date: 2022-05-20 12:59:02 +0100 (Fri, May 20, 2022) $"
#=========================================================================================
# Start of code
#=========================================================================================
import typing
from ccpn.util.Logging import getLogger
import pandas as pd
from ccpn.core.NmrResidue import NmrResidue
from ccpn.core.lib.Notifiers import Notifier
from ccpn.AnalysisAssign.modules.backboneExtensions.BackboneAssignmentExtensionABC import BackboneAssignmentExtensionFrame
from ccpn.AnalysisAssign.modules.backboneExtensions.COPs_analysis_CCPN.cops_analysis import cops_analyze
from ccpn.ui.gui.widgets.PulldownListsForObjects import SpectrumGroupPulldown, DataTablePulldown, PeakListPulldown
from ccpn.ui.gui.widgets.CompoundWidgets import CheckBoxCompoundWidget
from ccpn.framework.Application import getApplication, getMainWindow, getProject, getCurrent
from ccpn.AnalysisAssign.lib.scoring import getNmrResidueMatches
_cwWidth = 200
class COPsExtensionFrame(BackboneAssignmentExtensionFrame):
"""
COPs Extension for the Analysis Backbone Assignment
"""
NAME = 'COPs Analysis'
isGuiActive = True
def __init__(self, guiModule, *args, **Framekwargs):
self.application = getApplication()
self.mainWindow = getMainWindow()
self.project = getProject()
self.current = getCurrent()
BackboneAssignmentExtensionFrame.__init__(self, guiModule, **Framekwargs)
self.guiModule.findAndDisplayMatches = self.findAndDisplayMatches
self.ca = None
def registerNotifiers(self):
self._resChangedNotifier = Notifier(self.project,
[Notifier.RENAME, Notifier.DELETE],
'NmrResidue', self._change_Res)
self._peakChangedNotifier = Notifier(self.project,
[Notifier.CHANGE, Notifier.RENAME, Notifier.DELETE, Notifier.CREATE],
'Peak', self._change_Peak)
def initWidgets(self):
row = 0
self.SGWidget = SpectrumGroupPulldown(self, mainWindow=self.mainWindow, fixedWidths=(_cwWidth, _cwWidth), grid=(row,0))
row += 1
self.DTWidget = DataTablePulldown(self, mainWindow=self.mainWindow, fixedWidths=(_cwWidth,_cwWidth), grid=(row, 0))
row += 1
self.PLWidget = PeakListPulldown(self, mainWindow=self.mainWindow, fixedWidths=(_cwWidth, _cwWidth), grid=(row, 0))
row += 1
self.calculate_CB = CheckBoxCompoundWidget(self,
grid=(row, 0),
fixedWidths=(_cwWidth, _cwWidth),
orientation='left',
labelText='Calculate CB',
checked=False
)
def findAndDisplayMatches(self, nmrResidue):
"""Find and displays the matches to nmrResidue"""
assignMatrix = self.getAssignedMatrix(nmrResidue)
if self.isGuiActive:
assignMatrix = self._getCopAssignedMatrix(nmrResidue, assignMatrix)
## Native behaviour
self.guiModule._createMatchStrips(nmrResidue, assignMatrix)
def getAssignedMatrix(self, nmrResidue):
"""
:param nmrResidue:
:return:
"""
# If NmrResidue is a -1 offset NmrResidue, set queryShifts as value from self.interShifts dictionary
# Set matchShifts as self.intraShifts
if nmrResidue.relativeOffset == -1:
if nmrResidue not in self.guiModule.interShifts:
queryShifts = []
else:
queryShifts = [shift for shift in self.guiModule.interShifts[nmrResidue]
if (shift and not shift.isDeleted) and shift.nmrAtom and (
shift.nmrAtom.name in self.guiModule.nmrAtomsToMatch)]
matchShifts = self.guiModule.intraShifts
# If NmrResidue is not an offset NmrResidue, set queryShifts as value from self.intraShifts dictionary
# Set matchShifts as self.interShifts
elif nmrResidue.relativeOffset == 0 or nmrResidue.relativeOffset is None:
if nmrResidue not in self.guiModule.intraShifts:
queryShifts = []
else:
queryShifts = [shift for shift in self.guiModule.intraShifts[nmrResidue]
if (shift and not shift.isDeleted) and shift.nmrAtom.name in self.guiModule.nmrAtomsToMatch]
matchShifts = self.guiModule.interShifts
# If NmrResidue has offset other than -1 or 0/None, tell user that we are not able to match
else:
getLogger().warning(
"Assignment matching not supported for NmrResidue offset %s. Matching display skipped"
% nmrResidue.relativeOffset
)
return
assignMatrix = getNmrResidueMatches(queryShifts, matchShifts, 'averageQScore')
return assignMatrix
def _initialize_analyzer(self):
sg_pid, pl_pid = self.SGWidget.getText(), self.PLWidget.getText()
sg = self.application.project.getByPid(sg_pid)
pl = self.application.project.getByPid(pl_pid)
try:
self.ca = cops_analyze(self.application, sg, peak_list=pl)
except:
raise ValueError("Check set spectrum group and/or peak list!")
def updateMatchesByLineshape(self, cops_analyzer: cops_analyze, this_Residue: NmrResidue,
assignMatrix: typing.Dict[float, NmrResidue],
df: pd.DataFrame) -> typing.Dict[float, NmrResidue]:
# compresses the dataframe to contain slices for only residues found in AssignMatrix.
res_pids = [i.pid for i in assignMatrix.values()]
slices_list = df[df['residues'].isin(res_pids)]
this_data = df[df['residues'] == this_Residue.pid]
if len(this_data)>0:
this_data = this_data.iloc[0]['1D_slice']
else:
getLogger().warning("No matches by Lineshape found. Returning native matches")
return assignMatrix
# compute correlation score and sets new element in DataFrame
lineshape_correlations = cops_analyzer.find_best_correlation(this_data, slices_list)
slices_list['correlation'] = lineshape_correlations
# updates the keys of assignMatrix with new scores
new_assignMatrix = {}
for matchscore, nmrRes in assignMatrix.items():
try:
corr = float(max(slices_list['correlation'][slices_list['residues']==nmrRes.pid]))
except:
corr = 0
# a better correlation value results in a smaller update score.
update_score = 1.5-corr
# The correlation values are steepened.
new_assignMatrix[(1-10**(-10*matchscore))*update_score]=nmrRes
return new_assignMatrix
def _getCopAssignedMatrix(self, nmrResidue, assignMatrix, plot=True):
""" Overriden _getAssignedMatrix method to allow the COP analysis."""
sg_pid, dt_pid, pl_pid = self.SGWidget.getText(), self.DTWidget.getText(), self.PLWidget.getText()
sg = self.application.project.getByPid(sg_pid)
pl = self.application.project.getByPid(pl_pid)
dt = self.application.project.getByPid(dt_pid)
if dt is not None:
data = dt.data
if not self.ca:
self.ca = cops_analyze(self.application, sg, data_table=data)
else:
if not self.ca:
self.ca = cops_analyze(self.application, sg, data_table=None, peak_list=pl)
data = self.ca.tb
self.ca.set_CB(self.calculate_CB.isChecked())
assignMatrix = self.updateMatchesByLineshape(self.ca, nmrResidue, assignMatrix, data)
if plot: # TODO Plotting should be an option.
fig = self.ca.plot_matches(nmrResidue, assignMatrix)
fig.show()
return assignMatrix
def _change_Res(self, data):
print("RES CHANGE")
if not self.ca:
self._initialize_analyzer()
self.ca.updateNmrResidue(data['trigger'], data['object'], oldPid=data['oldPid'])
def _change_Peak(self, data):
print("PEAK CHANGE")
if not self.ca:
self._initialize_analyzer()
self.ca.updatePeak(data['trigger'], data['object'])
def close(self):
""" de-register anything left or close table etc"""
self._resChangedNotifier.unRegister()
self._peakChangedNotifier.unRegister()
## Register the Extension in the BackboneAssignmentModule
from ccpn.AnalysisAssign.modules.BackboneAssignmentModule import BackboneAssignmentModule
BackboneAssignmentModule.registerExtension(BackboneAssignmentModule, COPsExtensionFrame)