ccpn.core.lib package

Subpackages

Submodules

ccpn.core.lib.AssignmentLib module

Library functions for (semi)automatic assignment routines

ccpn.core.lib.AssignmentLib.assignAlphas(nmrResidue: ccpn.core.NmrResidue.NmrResidue, peaks: List[ccpn.core.Peak.Peak], axisCode='C')[source]

Assigns CA and CA-1 NmrAtoms to dimensions of pairs of specified peaks, assuming that one has a height greater than the other, e.g. in an HNCA or HNCACB experiment.

ccpn.core.lib.AssignmentLib.assignBetas(nmrResidue: ccpn.core.NmrResidue.NmrResidue, peaks: List[ccpn.core.Peak.Peak], axisCode='C')[source]

Assigns CB and CB-1 NmrAtoms to dimensions of specified peaks.

ccpn.core.lib.AssignmentLib.copyPeakAssignments(refPeak, peaks)[source]
ccpn.core.lib.AssignmentLib.copyPeakListAssignments(referencePeakList: ccpn.core.PeakList.PeakList, matchPeakList: ccpn.core.PeakList.PeakList)[source]

Takes a reference peakList and assigns NmrAtoms to dimensions of a match peakList based on matching axis codes.

ccpn.core.lib.AssignmentLib.filterIntraResidual(nmrAtomsForDimensions: List[ccpn.core.NmrAtom.NmrAtom])[source]

Takes a N-list of lists of nmrAtoms, where N is the number of peak dimensions and only returns those which belong to residues that show up in at least to of the dimensions (This is the behaviour in v2, if I am correct).

ccpn.core.lib.AssignmentLib.findClosePeaks(peak, matchPeakList, tolerance=0.02)[source]

Takes an input peak and finds all peaks in the matchPeakList that are close in space to the position of the input peak. A close peak is defined as one for which the euclidean distance between its position and that of the input peak is less than the specified tolerance. AxisCodes are used to match dimensions between peaks to ensure correct distance calculation.

ccpn.core.lib.AssignmentLib.getAllSpinSystems(project: ccpn.core.Project.Project, nmrResidues: List[ccpn.core.NmrResidue.NmrResidue], chains: List[ccpn.core.Chain.Chain], shiftLists: List[ccpn.core.ChemicalShiftList.ChemicalShiftList]) {}[source]
ccpn.core.lib.AssignmentLib.getBoundNmrAtomPairs(nmrAtoms, nucleus) list[source]

Takes a set of NmrAtoms and a nucleus e.g. ‘H’ or ‘C’ and returns a list of unique pairs of nmrAtoms in the input that are bound to each other.

ccpn.core.lib.AssignmentLib.getNmrAtomPrediction(ccpCode: str, value: float, isotopeCode: str, strict: bool = False) list[source]

Takes a ccpCode, a chemical shift value and an isotope code and returns a dictionary of atom type predictions to confidence values..

ccpn.core.lib.AssignmentLib.getNmrResiduePrediction(nmrResidue: ccpn.core.NmrResidue.NmrResidue, chemicalShiftList: ccpn.core.ChemicalShiftList.ChemicalShiftList, prior: float = 0.05, chemicalShifts=None) list[source]

Takes an NmrResidue and a ChemicalShiftList and returns a dictionary of the residue type to confidence levels for that NmrResidue.

ccpn.core.lib.AssignmentLib.getSpinSystemsLocation(project: ccpn.core.Project.Project, nmrResidues: List[ccpn.core.NmrResidue.NmrResidue], chain: ccpn.core.Chain.Chain, chemicalShiftList: ccpn.core.ChemicalShiftList.ChemicalShiftList) list[source]

Determines location of a set of NmrResidues in the specified chain using residue type predictions.

ccpn.core.lib.AssignmentLib.isInterOnlyExpt(experimentType: str) bool[source]

Determines if the specified experiment is an inter-residual only experiment

ccpn.core.lib.AssignmentLib.matchingNmrAtomsForPeakDimension(peak: ccpn.core.Peak.Peak, dim: int, nmrAtoms: List[ccpn.core.NmrAtom.NmrAtom], doubleTolerance: bool = False, shifts: Optional[dict] = None) Set[ccpn.core.NmrAtom.NmrAtom][source]

Find the nmrAtoms that match a dimension of one peak, both with respect to isotopeCode and tolerance setting.

:return A (sub-)set of nmrAtoms that match

ccpn.core.lib.AssignmentLib.matchingNmrAtomsForPeaks(peaks: List[ccpn.core.Peak.Peak], nmrAtoms: List[ccpn.core.NmrAtom.NmrAtom], doubleTolerance: bool = False) list[source]

Return the sub-set of nmrAtoms that fit to the dimensions of the peaks. All peaks should have the same dimensionality This function does the actual calculation and does not involve filtering like in nmrAtoms_for_peaks, where more filters can be specified in the future.

:return a list of the sets matching nmrAtoms per dimension

ccpn.core.lib.AssignmentLib.nmrAtomPairsByDimensionTransfer(peakLists: Sequence[ccpn.core.PeakList.PeakList]) dict[source]

From one or more peakLists belonging to the same spectrum, get a dictionary of magnetisationTransferTuple (See Spectrum.magnetisationTransfers for documentation) to a set of NmrAtom pairs that are coupled by the magnetisation transfer. If the two dimensions have the same nucleus, the NmrAtom pairs are sorted, otherwise they are in the dimension order.

Peak.assignedNmrAtoms is used to determine which NmrAtoms are connected

ccpn.core.lib.AssignmentLib.nmrAtomsForPeaks(peaks: List[ccpn.core.Peak.Peak], nmrAtoms: List[ccpn.core.NmrAtom.NmrAtom], intraResidual: bool = False, doubleTolerance: bool = False)[source]

Get a set of nmrAtoms that fit to the dimensions of the peaks.

ccpn.core.lib.AssignmentLib.peaksAreOnLine(peaks: List[ccpn.core.Peak.Peak], dimIndex: int)[source]

Returns True when multiple peaks are located on a line in the dimension defined by dimIndex.

ccpn.core.lib.AssignmentLib.propagateAssignments(peaks: Optional[List[ccpn.core.Peak.Peak]] = None, referencePeak: Optional[ccpn.core.Peak.Peak] = None, current: Optional[object] = None, tolerances: Optional[List[float]] = None)[source]

Propagates dimensionNmrAtoms for each dimension of the specified peaks to dimensions of other peaks.

ccpn.core.lib.AssignmentLib.refitPeaks(peaks: Sequence[ccpn.core.Peak.Peak], fitMethod: str = 'gaussian', singularMode=True)[source]
ccpn.core.lib.AssignmentLib.sameAxisCodes(peaks: List[ccpn.core.Peak.Peak], dim: int)[source]

Checks whether all peaks have the same axisCode for in the given dimension.

ccpn.core.lib.AssignmentLib.withinTolerance(nmrAtom: ccpn.core.NmrAtom.NmrAtom, position: float, shiftList: ccpn.core.ChemicalShiftList.ChemicalShiftList, tolerance: float, shifts: Optional[dict] = None)[source]

Decides whether the shift of the nmrAtom is within the tolerance to be assigned to the peak dimension.

ccpn.core.lib.AxisCodeLib module

Module Documentation here

ccpn.core.lib.AxisCodeLib.axisCodeMatch(axisCode, refAxisCodes)[source]

Get refAxisCode that best matches axisCode

ccpn.core.lib.AxisCodeLib.doAxisCodesMatch(axisCodes, refAxisCodes)[source]

Return True if axisCodes match refAxisCodes else False

ccpn.core.lib.AxisCodeLib.getAxisCodeMatch(axisCodes, refAxisCodes, exactMatch=False, allMatches=False, checkBoundAtoms=False) collections.OrderedDict[source]

Return an OrderedDict containing the mapping from the refAxisCodes to axisCodes

There may be multiple matches, or None for each axis code.

Set allMatches to True to return all, or False for only the best match in each case

e.g. for unique axis codes:

getAxisCodeMatch((‘Hn’, ‘Nh’, ‘C’), (‘Nh’, ‘Hn’), allMatches=False)

-> { ‘Hn’: ‘Hn’

‘Nh’: ‘Nh’ ‘C’ : None

}

getAxisCodeMatch((‘Hn’, ‘Nh’, ‘C’), (‘Nh’, ‘Hn’), allMatches=True)

-> { ‘Hn’: (‘Hn’,)

‘Nh’: (‘Nh’,) ‘C’ : ()

}

for similar repeated axis codes, possibly from matching isotopeCodes:

getAxisCodeMatch((‘Nh’, ‘H’), (‘H’, ‘H1’, ‘N’), allMatches=False)

-> { ‘Nh’: ‘N’

‘H’ : ‘H’

}

getAxisCodeMatch((‘Nh’, ‘H’), (‘H’, ‘H1’, ‘N’), allMatches=True)

-> { ‘Nh’: (‘N’,)

‘H’ : (‘H’, ‘H1’) <- in this case the first match is always the highest

}

ccpn.core.lib.AxisCodeLib.getAxisCodeMatchIndices(axisCodes, refAxisCodes, exactMatch=False, allMatches=False, checkBoundAtoms=False)[source]

Return a tuple containing the indices for each axis code in axisCodes in refAxisCodes

Only the best match is returned for each code, elements not found in refAxisCodes will be marked as ‘None’

e.g. for unique axis codes:

indices = getAxisCodeMatchIndices((‘Hn’, ‘Nh’, ‘C’), (‘Nh’, ‘Hn’))

-> (1, 0, None)

i.e axisCodes[0] = ‘Hn’ which maps to refAxisCodes[indices[0]] = ‘Hn’

for similar repeated axis codes, possibly from matching isotopeCodes:

getAxisCodeMatchIndices((‘Nh’, ‘H’), (‘H’, ‘H1’, ‘N’))

-> (2, 0)

ccpn.core.lib.Cache module

Cache object and cached / cached.clear decorators

Typical usage:

@cached('_myFuncCache', maxItems=100)  # cache for 100 items gets created if it does not exist
def myFunc(obj, arg1, arg2, kwd1=True)
    # some action here
    return result

On cleaning up:

@cached.clear('_myFuncCache')
def cleaningUp(self)
    # action here

or alternatively in your code:

if hasattr(obj, '_myFuncCache'):
    cache = getattr(obj, '_myFuncCache')
    cache.clear()
class ccpn.core.lib.Cache.Cache(maxItems=None, name='', debug=False)[source]

Bases: object

A cache object;

  • Retains (item, value) pairs; item must be a hash-able object (e.g. tuple)

  • Retains either maxItem or unlimited number of objects.

  • maxItem == 0 disables caching

  • Clearing cache is responsibility of the instantiating code; e.g. by decorating a cleanup function with cached.clear(attributeName); see above in description for example.

add(item, value)[source]

add item,value to the cache

clear()[source]

Clear all items from the cache

get(item)[source]

Get item from cache; return None if not present

hasItem(item)[source]

Return True of item is in cache

pop()[source]

Remove oldest item from stack

resize(maxItems)[source]

Resize the cache to contain maxItems

ccpn.core.lib.Cache.cached(attributeName, maxItems=0, debug=False, doSignatureExpansion=True)[source]

A decorator for initiating cached function call Works on functions that pass an object as the first argument; e.g. self attributeName defines the cache object doSignatureExpansion: flag to do a full signature expansion of the arguments

if False: use (repr(args), repr(kwds)) as hash

cached.clear (defined below) is a decorator to clear the cache

ccpn.core.lib.CallBack module

Module Documentation here

class ccpn.core.lib.CallBack.CallBack(theObject: Optional[Any] = None, object: Optional[Any] = None, index: Optional[int] = None, targetName: Optional[str] = None, trigger: Optional[list] = None, row: Optional[int] = None, col: Optional[int] = None, rowItem: Optional[dict] = None, rowObject: Optional[Any] = None, *args, **kwargs)[source]

Bases: collections.OrderedDict

CLICK = 'click'
COL = 'col'
CURRENT = 'current'
DOUBLECLICK = 'doubleclick'
INDEX = 'index'
OBJECT = 'object'
ROW = 'row'
ROWITEM = 'rowItem'
ROWOBJECT = 'rowObject'
TARGETNAME = 'targetName'
THEOBJECT = 'theObject'
TRIGGER = 'trigger'

ccpn.core.lib.CcpnDataSetParameters module

Functions to read/write parameters to a dataSet. The dataSet parameters are stored/restored as a ccpn_parameter saveframe in nef files. The value is stored as a ccpn_value item in the saveframe or as a ccpn_dataframe loop.

ccpn.core.lib.CcpnDataSetParameters.getCcpnNefParameter(project: Project, structureData, serial, name, parameterName)[source]

Get the required structureData parameter from the project Returns a python object/pandas dataFrame of the ccpn nef log for use in nef import/export If a dataFrame cannot be found, logs an error and returns None

Columns defined by the dataframe

Raises an error if there are any issues reading dataSet parameters

Parameters
  • project – instance of type Project

  • structureData – structureData name

  • serial – structureData serial

  • name – data item name

Returns

pandas dataFrame or None

ccpn.core.lib.CcpnDataSetParameters.setCcpnNefParameter(project: Project, structureData, serial, name, parameterName, value, overwrite=False)[source]

Set the required structureData parameter in the project for use in nef import/export

Raises an error if name or value are of the wrong types Returns False if the structureData parameter already exists and overwrite is False

Parameters
  • project – instance of type Project

  • structureData – structureData name

  • serial – structureData serial

  • name – data item name

  • value – pandas dataFrame or None

  • overwrite – True/False

Returns

True if successful

ccpn.core.lib.CcpnSorting module

Ccpn-specific variant of functions for sorting and comparison.

ccpn.core.lib.CcpnSorting.stringSortKey(key: str) tuple[source]

Sort key for strings.

Usage: sorted(aList, key=stringSortKey) or aList.sort(key=stringSortKey)

Custom CCPN version of stringSortKey that sorts Pids on their individual components.

Advanced:

Splits on embedded dots before further processing, and Returns an alternating tuple of (possibly empty) strings interspersed with (float,string) tuples, where the float is the converted value of the substring. First and last element are always strings.

If the entire string evaluates to a float, the result is (‘’, ‘(floatVal, stringVal), ‘’)

Otherwise the numeric tuples are (intVal, subStringVal). Substrings recognised as integers are an optional series of ‘ ‘, an optional sign, and a series of digits - or REGEX ‘[ ]*[+-]?d+’ For this type the key tuple is extended by (0,’’), # so that end-of-key sorts as 0 rather thn coming first.

Example of sorting order [‘’, ‘NaN’, ‘-1’, ‘-1A’, ‘0.0’, ‘1’, ‘2’, ‘15’, ‘3.2e12’, ‘Inf’, ‘Ahh’, ‘b’, ‘b2’, ‘b12’, ‘bb’, ‘ciao’]

ccpn.core.lib.CcpnSorting.universalSortKey(key)[source]

Custom universalSortKey, used to sort a list of mixed-type Python objects.

Usage: sorted(aList, key=universalSortKey) or aList.sort(key=universalSortKey)

Uses the local stringSortKey variant for strings and CCPN WrapperObjects sorted together

ccpn.core.lib.CcpnSparkyIo module

Module Documentation here

class ccpn.core.lib.CcpnSparkyIo.CcpnSparkyReader(application, specificationFile: Optional[str] = None, mode: str = 'standard', testing: bool = False)[source]

Bases: object

assignNmrChain(nmrChain)[source]
importConnectedNmrResidues(project, nmrChain)[source]
importPeakLists(project, saveBlock, sparkyDict)[source]
importSparkyMolecule(project, sparkyDict)[source]
importSparkyProject(project, sparkyDict)[source]

Import entire project from dataBlock into empty Project

importSpectra(project, saveBlock, parentBlock=None)[source]
initParser(project, input_path, spectrum)[source]
parseSparkyFile(path)[source]
processValue(value)[source]
class ccpn.core.lib.CcpnSparkyIo.CcpnSparkyWriter(project: ccpn.core.Project.Project, specificationFile: Optional[str] = None, mode: str = 'strict', programName: Optional[str] = None, programVersion: Optional[str] = None)[source]

Bases: object

class ccpn.core.lib.CcpnSparkyIo.SparkyDict(name='root')[source]

Bases: ccpn.util.nef.GenericStarParser.NamedOrderedDict

Top level container for general STAR object tree

getBlocks(value, firstOnly=False)[source]
getData(name='data', firstOnly=False)[source]
getDataValues(value, firstOnly=False)[source]
getParameter(name='name', firstOnly=False)[source]
exception ccpn.core.lib.CcpnSparkyIo.SparkySyntaxError[source]

Bases: ValueError

class ccpn.core.lib.CcpnSparkyIo.SparkyToken(type, value)

Bases: tuple

type

Alias for field number 0

value

Alias for field number 1

class ccpn.core.lib.CcpnSparkyIo.TypeBlock(name='root')[source]

Bases: ccpn.core.lib.CcpnSparkyIo.SparkyDict

class ccpn.core.lib.CcpnSparkyIo.UnquotedValue[source]

Bases: str

A plain string - the only difference is the type: ‘UnquotedValue’. Used to distinguish values from STAR files that were not quoted. STAR special values (like null, unknown, …) are only recognised if unquoted strings

ccpn.core.lib.CcpnSparkyIo.getSparkyTokenIterator(text)[source]

Iterator that returns an iterator over all STAR tokens in a generic STAR file

ccpn.core.lib.CcpnStarIo module

ccpn.core.lib.CcpnStarIo.makeCSLDataFrame(bmrbLines)[source]
ccpn.core.lib.CcpnStarIo.makeCSLfromDF(project, df)[source]
Parameters

df – Pandas dataFrame from parsing an NmrStar 3 File.

Returns

ChemicalShiftList Object

Creates a V3 ChemicalShiftList and associated V3 objects from a dataFrame created parsing an NmrStar 3 File. The reader assumes the dataframe contains tags as specified in the bmrb dictionary. See reference. TAGs reference: https://bmrb.io/dictionary/tag.php?tagcat=Atom_chem_shift

+——————————|-----------------------------------------+ + CCPN V3 Object/property | BMRB *.TAG (*prefix: _Atom_chem_shift) + +------------------------------|—————————————–+ chemicalShiftList:

name => Entry_ID

nmrChain(s):

name => Entity_assembly_ID

NmrResidue(s):

sequenceCode => seq_ID or Auth_seq_ID (if present) residueType => Comp_ID

NmrAtom(s):

name => Atom_ID isotopeCode => Atom_isotope_number + Atom_type

ChemicalShift(s):

value => Val valueError => Val_er comment => Details

Others not stored. Maybe save in ChemicalShift internal?

Assembly_atom_ID Assign_fig_of_merit Assigned_chem_shift_list_ID Ambiguity_code Ambiguity_set_ID Auth_asym_ID Occupancy_ID Resonance_ID

# TODO: NmrAtom Name => use Auth_atom_ID and Ambiguity_code to create an NEF-compliant nomenclature

ccpn.core.lib.ContextManagers module

Module Documentation here

class ccpn.core.lib.ContextManagers.AntiAliasedPaintContext(painter)[source]

Bases: ccpn.core.lib.ContextManagers.PaintContext

class ccpn.core.lib.ContextManagers.BlankedPartial(func, obj=None, trigger=None, preExecution=False, *args, **kwds)[source]

Bases: object

Wrapper (like partial) to call func(**kwds) with blanking optionally trigger the notification of obj, either pre- or post execution.

class ccpn.core.lib.ContextManagers.PaintContext(painter)[source]

Bases: object

context manager for closing painters correctly

class ccpn.core.lib.ContextManagers.Timeout(seconds: int = 60, timeoutMessage: str = '', loggingType='warning')[source]

Bases: object

A simple No-UI context manager to wrap a long operation, which is not necessarily a loop.

– Do an operation until time runs out –

Usage:

# – Single thread – # with timeout(seconds=60, timeoutMessage=’time is over’) as t:

# do a long operation # if not finished before time runs out then it stops …

ccpn.core.lib.ContextManagers.apiNotificationBlanking(application=None)[source]

Block api ‘change’ notifier, re-enable at the end of the function block.

ccpn.core.lib.ContextManagers.catchExceptions(application=None, errorStringTemplate='Error: "%s"', popupAsWarning=True, printTraceBack=False)[source]

Catches exceptions in try except; logging it as warning;

errorStringTemplate: string with one ‘%s’; used to output the exception to logger as warning popupAsWarning: flag to report output as a warning popup

raises the error again in debug mode

ccpn.core.lib.ContextManagers.ccpNmrV3CoreSetter(doNotify=True)[source]

A decorator wrap the property setters method in an undo block and triggering the ‘change’ notification if doNotify=True

ccpn.core.lib.ContextManagers.ccpNmrV3CoreSimple()[source]

A decorator wrap the property setters method in an undo block Notifiers are not explicitly triggered

ccpn.core.lib.ContextManagers.ccpNmrV3CoreUndoBlock(action='change')[source]

A decorator wrap the property setters method in an undo block and triggering the action notification; default is ‘change’ but occasionally may use ‘rename’

ccpn.core.lib.ContextManagers.checkDeleted()[source]

A decorator to wrap the property getter/setter methods with a check on deletion flag

ccpn.core.lib.ContextManagers.deleteObject()[source]

A decorator to wrap the delete(self) method of the V3 core classes calls self._finalise(‘delete’) prior to deletion

GWV first try EJB 20181130: modified

ccpn.core.lib.ContextManagers.deleteV3Object()[source]

A decorator to wrap the delete(self) method of the V3 core classes calls self._finalise(‘delete’) prior to deletion

ccpn.core.lib.ContextManagers.deleteWrapperWithoutSideBar()[source]

A decorator to wrap the delete(self) method of the V3 core classes calls self._finalise(‘delete’) prior to deletion

ccpn.core.lib.ContextManagers.echoCommand(obj, funcName, *params, values=None, defaults=None, parName=None, propertySetter=False, **objectParameters)[source]
ccpn.core.lib.ContextManagers.inactivity(application=None, project=None)[source]

Block all notifiers, apiNotifiers, undo and echo-ing re-enable at the end of the function block. We allow passing in of application and project, as this is used in the initialisation when not all is proper yet.

ccpn.core.lib.ContextManagers.logCommandManager(prefix, funcName, *args, **kwds)[source]

Echo commands as prefix.funcName( **kwds )

ccpn.core.lib.ContextManagers.newObject(klass)[source]

A decorator wrap a newObject method’s of the various classes in an undo block and calls result._finalise(‘create’). Checks for appropriate klass; passes on None if that is the result of the decorated function call

ccpn.core.lib.ContextManagers.newObjectList(klasses)[source]

A decorator wrap a newObject method’s of the various classes in an undo block and calls result._finalise(‘create’) for each object in the results list klasses is a list of strings of type klass.__class__.__name__ to remove restriction on circular imports The primary object (first in the list) is returned and must be the first type in klasses list

ccpn.core.lib.ContextManagers.newV3Object()[source]

A decorator to wrap the creation of pure v3 method of the V3 core classes calls self._finalise(‘create’) post-creation

ccpn.core.lib.ContextManagers.notificationBlanking(application=None)[source]

Block all notifiers, re-enable at the end of the function block.

ccpn.core.lib.ContextManagers.notificationEchoBlocking(application=None)[source]

Disable echoing of commands to the terminal, re-enable at the end of the function block.

ccpn.core.lib.ContextManagers.notificationSuspend(application=None)[source]

Suspend notifiers until the end of the current function block.

ccpn.core.lib.ContextManagers.notificationUnblanking()[source]

Unblock all notifiers, disable at the end of the function block. Used inside notificationBlanking if a notifier is required for a single event

ccpn.core.lib.ContextManagers.queueStateChange(verify)[source]

A decorator to wrap a state change event with a verify function

ccpn.core.lib.ContextManagers.rebuildSidebar(application)[source]

This context manager clears and blocks the sidebar and rebuilds it afterwards

ccpn.core.lib.ContextManagers.renameObject()[source]

A decorator to wrap the rename(self) method of the V3 core classes calls self._finaliseAction(‘rename’) after the rename

EJB 20191023: modified original contextManager to be decorator to match new/delete

ccpn.core.lib.ContextManagers.renameObjectContextManager(self)[source]

A decorator to wrap the rename(self) method of the V3 core classes calls self._finaliseAction(‘rename’, ‘change’) after the rename

ccpn.core.lib.ContextManagers.renameObjectNoBlanking(self)[source]

A decorator to wrap the rename(self) method of the V3 core classes calls self._finaliseAction(‘rename’, ‘change’) after the rename

ccpn.core.lib.ContextManagers.sidebarBlocking(application=None, blockSidebarOnly=False)[source]

Block updating of the sidebar (if present) until end of function block.

ccpn.core.lib.ContextManagers.undoBlock(application=None)

Wrap all the contained operations into a single undo/redo event.

ccpn.core.lib.ContextManagers.undoBlockWithSideBar(application=None)[source]

Wrap all the contained operations into a single undo/redo event.

ccpn.core.lib.ContextManagers.undoBlockWithoutSideBar(application=None)[source]

Wrap all the contained operations into a single undo/redo event. To be deprecated. Use just undoBlock

ccpn.core.lib.ContextManagers.undoStackBlocking(application=None, project=None)[source]

Block addition of items to the undo stack, re-enable at the end of the function block. New user items can be added to the undo stack after blocking is re-enabled.

Example:

with undoStackBlocking() as addUndoItem:
    ...
    do something here
    ...
    addUndoItem(undo=partial(<function>, <args and kwargs>),
                redo=partial(<function>, <args and kwargs>))
    do more here

Multiple undoItems can be appended.

ccpn.core.lib.ContextManagers.undoStackRevert(application=None)[source]

Revert the contents of the undo stack if an error occurred

usage:

e.g.
with undoStackRevert() as revertStack:

…process

if error:

# set the error state of the context manager revertStack(True)

‘revertStack’ could of course be any name, but best to keep relevant.

ccpn.core.lib.ContextManagers.waypointBlocking(application=None)[source]

Block addition of new waypoints

ccpn.core.lib.DataFrameObject module

Module Documentation here

class ccpn.core.lib.DataFrameObject.DataFrameObject(table=None, dataFrame=None, objectList=None, columnDefs=None)[source]

Bases: object

appendObject(obj, multipleAttr=None)[source]
changeObject(obj)[source]
property columnDefinitions

- None, mutable -

property columns

- None, immutable -

property dataFrame

- None, mutable -

emptyRow()[source]

Create a blank row for populating undefined tables :return dict - based on headings:

find(table, text, column='Pid', multiRow=False)[source]
findObject(table, obj, column='_object')[source]

Return the row of the specified object

property headings

- None, immutable -

property numColumns

- None, immutable -

objAttr(headerText, obj)[source]
objectExists(obj)[source]
property objects

- None, immutable -

removeObject(obj)[source]
renameObject(obj, oldPid)[source]
property setEditValues

- None, immutable -

setObjAttr(headerText, obj, value)[source]
property table

- None, mutable -

property userHeadings

- None, immutable -

property visibleColumnHeadings

- None, immutable -

ccpn.core.lib.DataIo-obsolete module

ccpn.core.lib.DataStore module

Code to:
  • implement path redirections $DATA, $ALONGSIDE, $INSIDE

  • implement a DataStore object to handle Spectrum file paths properly

  • thereby wraps the silly dataStore and dataUrl data structures

Replaced:
  • core.lib.util.expandDollarFilePath

  • cor.lib.util._fetchDataUrl

class ccpn.core.lib.DataStore.AlongsideRedirection(**kwargs)[source]

Bases: ccpn.core.lib.DataStore.RedirectionABC

apiName = 'alongsideData'
expand = False
identifier = '$ALONGSIDE'
property path

- None, immutable -

class ccpn.core.lib.DataStore.DataRedirection(**kwargs)[source]

Bases: ccpn.core.lib.DataStore.RedirectionABC

apiName = 'remoteData'
expand = True
identifier = '$DATA'
property path

- None, mutable -

class ccpn.core.lib.DataStore.DataStore(**kwargs)[source]

Bases: ccpn.util.traits.CcpNmrJson.CcpNmrJson

This class wraps the implementation of $DATA, $ALONGSIDE, $INSIDE redirections

aPath()[source]

Return aPath instance of self, decoded for $DATA, $ALONGSIDE, $INSIDE redirections

apiDataStore
apiDataStoreDir
apiDataStoreName
apiDataStorePath
autoRedirect
autoVersioning
classVersion = 1.0
dataFormat

A trait that defines a string object, casts from bytes object and is json serialisable

errorMessage()[source]

Error message displayed on logger

exists()[source]

Return True if self.aPath() (i.e. expanded) exists

expandPath(path=None)[source]

return path decoded for $DATA, $ALONGSIDE, $INSIDE redirections returns Path instance

hasPathDefined()[source]

Return True if path has been defined

classmethod newFromPath(path, autoRedirect=False, autoVersioning=False, appendToName=None, withSuffix=None, dataFormat=None)[source]

Create and return a new instance from path; optionally append to name and set suffix

property path

- None, mutable - Return a Path representation of self, optionally encoded with $DATA, $ALONGSIDE, $INSIDE redirections

pathRedirections

Fixing default_value problem

redirectPath(path=None)[source]

Redefine path into $DATA, $ALONGSIDE, $INSIDE redirections return Path instance

spectrum
useBuffer
warningMessage()[source]

Error message displayed on logger

class ccpn.core.lib.DataStore.DataStoreTrait(**kwds)[source]

Bases: ccpn.util.traits.CcpNmrTraits.Instance

Specific trait for a Datastore instance encoding the path and dataFormat of the (binary) spectrum data. None indicates no spectrum data file path has been defined

class jsonHandler[source]

Bases: ccpn.util.traits.TraitJsonHandlerBase.CcpNmrJsonClassHandlerABC

klass

alias of ccpn.core.lib.DataStore.DataStore

class ccpn.core.lib.DataStore.InsideRedirection(**kwargs)[source]

Bases: ccpn.core.lib.DataStore.RedirectionABC

apiName = 'insideData'
expand = False
identifier = '$INSIDE'
property path

- None, immutable -

class ccpn.core.lib.DataStore.PathRedirections(*args, **kwargs)[source]

Bases: list

Class to maintain the path redirections $DATA, $ALONGSIDE, $INSIDE

property alongsidePath

- None, immutable -

property dataPath

- None, mutable -

getApiMappings()[source]

Return a list with (apiName, indentifier) tuples

getPaths()[source]

Return a list of (identifier, path) tuples

property insidePath

- None, immutable -

class ccpn.core.lib.DataStore.RedirectionABC(**kwargs)[source]

Bases: ccpn.util.traits.CcpNmrJson.CcpNmrJson

Base class for maintaining a single redirection

apiName = None
expand = False
expandPath()[source]

expand path to handle None, zero-length and ‘.’

identifier = None
property path

- None, immutable -

ccpn.core.lib.Documentation module

Generation of Sphinx automatic documentation

ccpn.core.lib.Documentation.getNamedSubdirectories(path, matchExpression=None) List[str][source]

Get a list of all subdirectories of path whose basename starts with one of the prefixes

Does not look inside the selected subdirectories

ccpn.core.lib.Documentation.refreshSphinxDocumentation()[source]

(Re)create sphinx documentation. Locations are hardwired

ccpn.core.lib.LabellingLib module

Labelling scheme handling. Functions to get labelling fraction

ccpn.core.lib.LabellingLib.atomLabelledFraction(sample: ccpn.core.Sample.Sample, atom2IsotopeCode: Dict[ccpn.core.Atom.Atom, str]) float[source]

Get fraction of cases in sample where the atoms have the indicated isotopeCodes. Equivalent groups of atoms e.g. Leu HB%, CD%, HD1% or HD%, will be averaged over their constituent atoms. Non-stereo assigned atoms, e.g. Leu HBx or HDy% will also be averaged, treating HBx as HB% and HDy% as HD%. This will be misleading if the components have very different labelling levels, but it remains the lesser evil.

:params sample Sample to use for determining labeling

:params atom2IsotopeCode {atom:isotopeCode} dictionary for atoms to look at.

ccpn.core.lib.LabellingLib.getLabellingScheme(schemeName: str) Optional[Dict][source]

Get labelling scheme dictionary from scheme name (or None if none is found

TODO NBNB probably needs more parameters and a different location

ccpn.core.lib.LabellingLib.residueLabelledFraction(atomName2IsotopeCode: Dict[str, str], residueType: Optional[str] = None, labellingScheme: Optional[Dict] = None, isotopeCode2Fraction: Optional[Dict[str, float]] = None) float[source]

Get fraction matching isotopeCodes for atoms in a single residue from labeling scheme and/or uniform labeling. Position-specific labeling is NOT considered. If residueType or labellingScheme is absent, or if an atom name is not found in the labelling scheme, the isotopeCode2Fraction dictionary is used for that atom(s). If any atom has no labelling information anywhere, the function returns None.

:params atomName2IsotopeCode {atomName:isotopeCode} dictionary defining the labelling pattern to evaluate, e.g. {‘CA’:’13C’, ‘CB’:’12C’, ‘CG’:’13C’}. The atom name may may end in ‘%’, referring to equivalent atoms e.g. Leu HB%, CD%, HD1% or HD%, in which case the labelling is averaged over the components. Non-stereo assigned atoms, e.g. Leu HBx or HDy% will also be averaged, treating HBx as HB% and HDy% as HD%. This will be misleading if the components have very different labelling levels, but it is the lesser evil.

:params residueType Type of residue that atoms belong to. If absent only uniform labelling is considered.

:params labellingScheme Labelling scheme dictionary (see example below). If absent only uniform labelling is considered.

:params isotopeCode2Fraction gives default uniform isotope

percentages, as for SampleComponent.uniformIsotopeFractions (q.v.). Example value: {‘12C’:0.289, ‘13C’:0.711, ‘1H’:0.99985, ‘2H’:0.00015}

Example of labeling scheme dictionary

‘MyScheme’: {
‘_name’:’MyScheme’,
‘GLY’:[
{ ‘_weight’:0.2,
‘CA’:{‘13C’:0.5, ‘12C’:0.5}
‘C’:{‘13C’:0.99,’12C’:0.01}
},
{
‘_weight’:0.5,
‘CA’:{‘13C’:0.0, ‘12C’:1.0}
‘C’:{‘13C’:0.0,’12C’:1.0}
},
{
‘_weight’:0.3,
‘C’:{‘13C’:0.95, ‘12C’:0.05},
‘HA2’:{‘1H’:0.7, ‘2H’:0.3},
‘HA3’:{‘1H’:0.7, ‘2H’:0.3} }
],
‘ALA’: [
],
},

The first isotopomer is 50% 13C CA and 99% 13C carbonyl, and defaults to the uniform labelling
fraction for 1H and 15N.

The second isotopomer is 100% C12 for both CA and carbonyl, and defaults to the uniform
labelling fraction for 1H and 15N

The third isotopomer is 95% 13C for carbonyl, 30% deuterium labelled (i.e. 70% 1H) for the
aliphatic protons, and defaults to the uniform labelling fraction for nitrogen, CA, and NH
protons.
ccpn.core.lib.LabellingLib.sampleComponentLabelledFraction(sampleComponent: ccpn.core.SampleComponent.SampleComponent, atom2IsotopeCode: Dict[ccpn.core.Atom.Atom, str]) float[source]

Get labelled fraction from SampleComponent. All atoms must be from a chain compatible with SampleComponent.

NB for x/y and % wildcard atoms, labelling is averaged over the component atoms. If only some of these are specifically labelled or in a labelling scheme, the rest will be assumed to have the default labelling of the sampleComponent. This may sometimes give misleading results, but it is the best available default behaviour

ccpn.core.lib.MoleculeLib module

Library functions for Molecule-related data

ccpn.core.lib.MoleculeLib.duplicateAtomBonds(chainMap: Dict[ccpn.core.Chain.Chain, ccpn.core.Chain.Chain])[source]

Duplicate atom-atom bonds within source chains to target chains, skipping those that already exist.

Input is a map from source chains to corresponding target chains.

Atoms are mapped on matching Pids (with different chain codes

ccpn.core.lib.MoleculeLib.expandChainAtoms(chain, replaceStarWithPercent=True, addPseudoAtoms=True, addNonstereoAtoms=True, setBoundsForAtomGroups=True, atomNamingSystem='PDB_REMED', pseudoNamingSystem='AQUA')[source]

Called after creating a new chain.

Create new atoms corresponding to the ChemComp AtomSets. Eg.

  • A simple AtomSet named H1% consisting of H1, H2, H3 atoms

will give a new V3 Atom called H1% of atomType=’equivalent’ and its components are the atomSet.atoms.

  • A nested atomSets such as H% consisting of H1%, H2%, H3% atomSets

will give a new V3 Atom called H% of atomType=’equivalent’ and its components are the V3 atoms H1%, H2%, H3%

Use atom.componentAtoms to get the children atoms as a tuple:

H1% –> (H1, H2, H3) HG% –> (HG1%, HG2%)

From any “real” atom, use atom.compoundAtoms to get the parent atoms as a tuple.

H1 –> (H1%)

Parameters

chain – V3 Chain object,

:return extended chain

Extra arguments:
param replaceStarWithPercent

bool: True. Default Replace * with % if the char is in the atom name. E.g. H1* to become H1%.

param addPseudoAtoms

bool: True. Default Add new atoms with alternative names to the one derived from the atomSets. E.g. MD, QG, MG. This will create a atom with same atom components as the standard from the chemComp atomSet. Therefore it’s a duplicated! These atoms might not be present in the original ChemComp definitions

param addNonstereoAtoms

bool: True. Default Add new atoms for Non-stereoAtoms E.g. for a VAL, HGx%, HGy% These atoms might not be present in the original ChemComp definition

param setBoundsForAtomGroups

bool: True. Default set the newly created atoms from the AtomSets to be “bound” as the real atoms E.g. H1%-C1 to be like H1-C1 and atoms derived from nested AtomSet like HG*-CG* etc.

param atomNamingSystem

str: ‘PDB_REMED’. Default To be deprecated. Will be only NEF atomNamingSystem

param pseudoNamingSystem

str: ‘AQUA’. Default To be deprecated. Will be only NEF atomNamingSystem

ccpn.core.lib.MoleculeLib.extraBoundAtomPairs(project: ccpn.core.Project.Project, selectSequential: Optional[bool] = None) List[Tuple[ccpn.core.Atom.Atom, ccpn.core.Atom.Atom]][source]

Get pairs of bound Atoms whose bonds are NOT defined through the residue topology. The result and each individual atom pair are both sorted

Returns sequential bond pairs if selectSequential is True, non-sequential bond pairs if selectSequential is False, and both if selectSequential is None

ccpn.core.lib.MoleculeLib.sequenceMatchOffset(reference: collections.OrderedDict, sequence: collections.OrderedDict) Optional[int][source]

Check if residues in sequence match those in reference, directly or with an offset. Reference and sequence are OrderedDict(sequenceCode:residueType) Both integer and string sequenceCodes (or a mixture) will give correct results - other types of key will not.

Returns 0 if all(reference.get(key) == val for key, val in sequence.items())

Otherwise tries to convert keys in sequence and reference to integers and checks if all (reference.get(key+offset) == val for key, val in sequence.items()) for some offset.

Returns the offset is a match is found,, None if no match is found

ccpn.core.lib.Notifiers module

Notifier extensions, wrapping it into a class that also acts as the called function, dispatching the ‘user’ callback if required.

The Notifier can be defined relative to any valid V3 core object, as well as the current object as it first checks if the triggered signature is valid.

The triggers CREATE, DELETE, RENAME and CHANGE can be combined in the call signature, preventing unnecessary code duplication. They are translated into multiple notifiers of the ‘Project V3-machinery’ (i.e., the Rasmus callbacks)

The callback function is passed a callback dictionary with relevant info (see docstring of Notifier class. This idea was copied from the Traitlets package.

April 2017: First design by Geerten Vuister

class ccpn.core.lib.Notifiers.Notifier(theObject: Any, triggers: list, targetName: str, callback: Callable[[...], Optional[str]], setterObject=None, onceOnly=False, debug=False, **kwargs)[source]

Bases: ccpn.core.lib.Notifiers.NotifierABC

Notifier class:

triggers callback function with signature: callback(callbackDict [, *args] [, **kwargs])

Notifier.CREATE className theObject, object, targetName: valid child className of theObject

targetName, trigger (any for project instances) notifier

Notifier.DELETE className theObject, object, targetName: valid child className of theObject

targetName, trigger (any for project instances) notifier

Notifier.RENAME className theObject, object targetName: valid child className of theObject

targetName, oldPid, (any for project instances) trigger

Notifier.CHANGE className theObject, object targetName: valid child className of theObject

targetName, (any for project instances) trigger, notifier

Notifier.OBSERVE attributeName theObject,targetName targetName: valid attribute name of theObject
or ANY value, previousValue, NB: should only be used in isolation; i.e. not

trigger, notifier combined with other triggers

Notifier.CURRENT attributeName theObject,targetName theObject should be current object

value, previousValue, targetName: valid attribute name of current trigger, notifier NB: should only be used in isolation; i.e. not

combined with other triggers

Implemention:

Uses current notifier system from Project and Current;filters for child objects of type targetName in theObject. TargetName does need to denote a valid child-class or attribute of theObject, except for Project instances which can be triggered by all classes (see Table).

The callback provides a dict with several key, value pairs and optional arguments and/or keyword arguments if defined in the instantiation of the Notifier object. (idea following the Traitlets concept). Note that this dict also contains a reference to the Notifier object itself; this way it can be used to pass-on additional implementation specific information to the callback function.

ANY = '<Any>'
CHANGE = 'change'
CREATE = 'create'
CURRENT = 'current'
DELETE = 'delete'
GETPID = 'pid'
NOTIFIER = 'notifier'
OBJECT = 'object'
OBSERVE = 'observe'
OLDPID = 'oldPid'
PREVIOUSVALUE = 'previousValue'
RENAME = 'rename'
TARGETNAME = 'targetName'
THEOBJECT = 'theObject'
TRIGGER = 'trigger'
VALUE = 'value'
unRegister()[source]

unregister the notifiers

class ccpn.core.lib.Notifiers.NotifierABC(theObject, triggers, targetName, callback, setterObject=None, debug=False, **kwargs)[source]

Bases: object

Abstract base class for Notifier and GuiNotifier classes

property id

- None, immutable -

isRegistered() bool[source]

:return True if notifier is still registered; i.e. active

property project

- None, immutable - Return the project

setBlanking(flag: bool)[source]

Set blanking on/off

setDebug(flag: bool)[source]

Set debug output on/off

triggersOn(trigger) bool[source]

Return True if notifier triggers on trigger

unRegister()[source]

Reset the attributes

class ccpn.core.lib.Notifiers.NotifierBase[source]

Bases: object

A class confering notifier management routines

deleteAllNotifiers()[source]

Unregister all the notifiers

deleteNotifier(notifier: ccpn.core.lib.Notifiers.Notifier)[source]

unregister notifier; remove it from the list and delete it :param notifier: Notifier instance

hasNotifier(notifier: Optional[ccpn.core.lib.Notifiers.Notifier] = None) bool[source]

return True if theObject has set notifier or has any notifier (when notifier==None)

Parameters

notifier – Notifier instance or None

Returns

True or False

searchNotifiers(objects=[], triggers=None, targetName=None)[source]

Search whether a notifier with the given parameters is already in the list. The triggers CREATE, DELETE, RENAME and CHANGE can be combined in the call signature

Parameters
  • theObject – valid V3 core object or current object to watch

  • triggers – list of trigger keywords

  • targetName – valid className, attributeName or ANY

Returns

None or list of existing notifiers

setBlankingAllNotifiers(flag)[source]

Set blanking of all the notifiers of theObject to flag

setGuiNotifier(theObject: AbstractWrapperObject, triggers: list, targetName: str, callback: Callable[[...], Optional[str]], **kwargs) ccpn.core.lib.Notifiers.Notifier[source]

Set Notifier for Ccpn V3 object theObject

Parameters
  • theObject – V3 object to register a notifier with

  • triggers – list of triggers to trigger callback

  • targetName – valid className, attributeName or None (See Notifier doc string for details)

  • callback – callback function with signature: callback(obj, parameter2 [, *args] [, **kwargs])

  • kwargs – optional keyword,value arguments to callback

Returns

a GuiNotifier instance

setNotifier(theObject: AbstractWrapperObject, triggers: list, targetName: str, callback: Callable[[...], Optional[str]], **kwargs) ccpn.core.lib.Notifiers.Notifier[source]

Set Notifier for Ccpn V3 object theObject

Parameters
  • theObject – V3 object to register a notifier with

  • triggers – list of triggers to trigger callback

  • targetName – valid className, attributeName or None (See Notifier doc string for details)

  • callback – callback function with signature: callback(obj, parameter2 [, *args] [, **kwargs])

  • **kwargs

    optional keyword,value arguments to call back

Returns

a Notifier instance

ccpn.core.lib.Notifiers.skip(*args, **kwargs)[source]

Do nothing

ccpn.core.lib.OrderedSpectrumViews module

ejb - orderedSpectrumViews, orderedSpectra store the current orderedSpectrumViews in the internal data store _ccpnInternalData so it is hidden from external users

accessed with the methods:

strip.getSpectra() returns tuple(spectra) or None strip.getSpectrumViews() returns tuple(spectrumViews) or None

use order = <tuple> to set the list

class ccpn.core.lib.OrderedSpectrumViews.OrderedItemsABC(parent=None, undoEnabled=True)[source]

Bases: object

Class handler for ordering of a list of items

If parent is specified, the ordering is stored in the _ccpnInternalData of parent, and will be persistent when saving a project. Otherwise it is stored internally.

property order: Optional[Tuple]

- Tuple=None, mutable - The current indexing list

Returns

tuple of ints

orderedItems(items: List | Tuple, resize=False) Optional[Tuple][source]

Return the tuple of items ordered by the stored indexing. resize is True/False. If True the stored ordering will shrink to the length of the list, otherwise the extra elements are kept so that order of longer lists is remembered.

Parameters
  • items – list/tuple of items

  • resize – True/False

Returns

tuple of spectrumViews/spectra

class ccpn.core.lib.OrderedSpectrumViews.OrderedSpectrumViews(parent=None, undoEnabled=True)[source]

Bases: ccpn.core.lib.OrderedSpectrumViews.OrderedItemsABC

Class handler for ordering of a list of spcetra/spectrumViews

See OrderedItemsABC for more details

orderedItems(items: List | Tuple, resize=False) Optional[Tuple][source]

The spectrumViews/spectra attached to the strip, ordered by the stored indexing items is the list of items to be ordered, originally designed for spectra/spectrumViews, but any list/tuple can be used.

resize is True/False. If True the stored ordering will shrink to the length of the list, otherwise the extra elements are kept so that order of longer lists is remembered.

Parameters
  • items – list/tuple of items

  • resize – True/False

Returns

tuple of spectrumViews/spectra

ccpn.core.lib.OrderedSpectrumViews.mainTest()[source]

A few quick tests for the ordering

ccpn.core.lib.PeakClustering module

This module contains clustering routines.

class ccpn.core.lib.PeakClustering.DFSPeakClusterer(peaks, tolerances, **kwargs)[source]

Bases: ccpn.core.lib.PeakClustering.PeakClustererABC

findClusters(*args, **kwargs)[source]

Find clusters using a cluster-graph approach. - Ref 1) https://en.wikipedia.org/wiki/Graph_theory - Ref 2) https://en.wikipedia.org/wiki/Cluster_graph

info = 'Depth-first search (DFS) algorithm for peak clustering by pointPositions'
name = 'DFS_PeakClusterer'
class ccpn.core.lib.PeakClustering.PeakClustererABC(peaks, tolerances, **kwargs)[source]

Bases: object

Base class for peak clustering

abstract findClusters(*args, **kwargs) Tuple[Tuple[Peak, ...], ...][source]

The main method to find clusters given a list of peaks. Implement method in subclass. :param args: any :param kwargs: any :return: A tuple of tuples of peaks. Each tuple represents a cluster.

info = 'The algorithm textual information'
name = 'PeakClustererABC'
setClusterIdToPeaks(clusters)[source]
Parameters

clusters – A tuple of tuples of peaks. Each tuple is a cluster.

Returns

None. Adds the enumeration as cluster Id to the peaks

ccpn.core.lib.PeakListLib module

Module Documentation here

ccpn.core.lib.Pid module

Pid (Project ID) class for within-project unique ID strings. Version-3 Pid routines

class ccpn.core.lib.Pid.Pid(string: str, **kwds)[source]

Bases: str

Pid routines, adapted from path idea in: Python Cookbook, A. Martelli and D. Ascher (eds), O’Reilly 2002, pgs 140-142

A Pid is a string with extra functionality. It consists of a non-empty type substring separated by a mandatory ‘:’ character from an optional id substring, consisting of field substrings separated by dots. The isValid function checks for validity

The type, id, and list of fields are available as properties.

New Pids can be created by pid.clone, by pid.extend (which creates a new Pid with additional fields) and by Pid.new, which combines a type and a list of fields into a new Pid, converting the values to string as necessary.

Pids can also be created by modifying individual fields relative to a source pid. pid.modify(index, value) will set the value of the field at index, whereas pid.increment(index, value) (resp. decrement) will convert the field at index to an integer (where possible) and increment (decrement) it by ‘value’.

Examples:

pid = Pid.new(‘Residue’,’mol1’,’A’, 502) # elements need not be strings; but will be converted -> Residue:mol1.A.502 (Pid instance)

which is equivalent to:

pid = Pid(‘Residue:mol1.A.502’) -> Residue:mol1.A.502 (Pid instance)

Behaves as a string: pid == ‘Residue:mol1.A.502’ -> True

pid.str -> ‘Residue:mol1.A.502’ (str instance)

pid.type -> ‘Residue’ (str instance)

pid.id -> ‘mol1.A.502’ (str instance)

pid2 = pid.modify(1, ‘B’, type=’Atom’) -> Atom:mol1.B.502 (Pid instance)

but also: pid3 = Pid(‘Residue’).extend(‘mol2’) -> Residue:mol2 (Pid instance)

pid4 = pid.decrement(2,1) -> Residue:mol1.A.501 (Pid instance) or pid4 = pid.increment(2,-1) NB fails on elements that cannot be converted to int’s

pid5 = pid.clone() # equivalent to pid5 = Pid(pid) -> Residue:mol1.A.502 (Pid instance)

pid==pid5 -> True

‘502’ in pid.fields -> True

502 in pid.fields -> False # all pid elements are strings

property asString

- None, immutable - Convenience: return as string rather than object; allows to do things as obj.pid.asString() rather then str(obj.pid)

clone() ccpn.core.lib.Pid.Pid[source]

Return copy of pid

decrement(index: int, value: int = 1) ccpn.core.lib.Pid.Pid[source]

Return new pid with position index decremented by value Assumes integer valued id at position index

definesInstance(klass)[source]

Returns True if pid.type defines an instance of V3-object klass

extend(*args: object)[source]

Make copy with additional fields

property fields: Tuple[str, ...]

- Tuple[str, …], immutable - id part of pid as a tuple of fields

property id: str

- str, immutable - return id part of pid

increment(index: str, value: int = 1) ccpn.core.lib.Pid.Pid[source]

Return new pid with position index incremented by value Assumes integer valued id at position index

static isValid(text: str) bool[source]
modify(index: int, newId: object, newType: Optional[str] = None) ccpn.core.lib.Pid.Pid[source]

Return new pid with position index modified by newId or newType replaced

static new(*args: object) ccpn.core.lib.Pid.Pid[source]

Return Pid object from arguments; args[0] can be a CoreClass object (e.g. Spectrum, Peak, etc) Apply str() on all arguments Have to use this as intermediate as str baseclass of Pid only accepts one argument

toClipboard()[source]

Copy a single quoted Pid to clipboard.

property type: str

- str, immutable - return type part of pid

ccpn.core.lib.Pid.createId(*args) str[source]

make id from list of successive keys. Keys are converted to string, and illegal characters are converted to altCharacter

ccpn.core.lib.Pid.createPid(head: str, *args: str) ccpn.core.lib.Pid.Pid[source]

make pid from head and list of successive keys. Head may be an existing pid, or a naked string Keys are converted to string, and illegal characters are converted to altCharacter The head is not checked - it should be either a valid pid or a class code

ccpn.core.lib.Pid.decodePid(sourceObject, thePid: ccpn.core.lib.Pid.Pid) Optional[ccpn.core.lib.Pid.Pid][source]

try to decode thePid relative to sourceObject return decoded pid object or None on not found or Error

ccpn.core.lib.Pid.splitId(idString) List[Optional[str]][source]

Split idString into tuple of component elements, mapping altCharacter back to separator and replacing empty strings with None

ccpn.core.lib.ProjectArchiver module

Code for Project archiving Replaced former Api.packageProject and _unpackCcpnTarfile

class ccpn.core.lib.ProjectArchiver.ProjectArchiver(projectPath)[source]

Bases: object

A class to manage the archives of a project

property archiveDirectory: ccpn.util.Path.Path

- ccpn.util.Path.Path, immutable - :return: absolute path to directory with archives as a Path instance

property archives: list

- list, immutable - :return: a list of archive (.tgz) tar files

makeArchive() ccpn.util.Path.Path[source]

Make a new time-stamped archive from project. :return: absolute path to the new archives as a Path instance

or None on IOerror

restoreArchive(archivePath) ccpn.util.Path.Path[source]

Restore project from archivePath. :return: the path to the restored project or None on IOerror

ccpn.core.lib.ProjectSaveHistory module

Project-History related routines

class ccpn.core.lib.ProjectSaveHistory.ProjectSaveHistory(**kwargs)[source]

Bases: ccpn.util.traits.CcpNmrJson.CcpNmrJson

A simple class to maintain a project save history as a list, to be saved to and restored from a json file stores (version, datetime, user, platform, comment) tuples

class RecordListHandler[source]

Bases: ccpn.util.traits.TraitJsonHandlerBase.TraitJsonHandlerBase

Record-list handling by Json

decode(obj, trait, value)[source]

uses value to generate and set the new (or modified) obj

class SaveRecord(version, datetime, user, platform, comment)

Bases: tuple

comment

Alias for field number 4

datetime

Alias for field number 1

platform

Alias for field number 3

user

Alias for field number 2

version

Alias for field number 0

addSaveRecord(version=None, comment=None)[source]

Add a save record to the history; get version from application if None :return self

classVersion = 1.0
exists() bool[source]

Return true if project save history file exists

property lastSavedVersion: ccpn.framework.Version.VersionString

- ccpn.framework.Version.VersionString, immutable - Return the program version of which the project was last saved as a VersionString instance

path = Path('.')
records

Fixing default_value problem

restore()[source]

Restore self from a json file. Check for prior ‘ed’-formatted file :return self

save()[source]

Save to (json) file

ccpn.core.lib.ProjectSaveHistory.fetchProjectSaveHistory(projectPath)[source]

Return a ProjectSaveHistory instance from a project path

ccpn.core.lib.ProjectSaveHistory.getProjectSaveHistory(projectPath)[source]

Return a ProjectSaveHistory instance from a project path, or None if it doesn’t exist

ccpn.core.lib.ProjectSaveHistory.newProjectSaveHistory(projectPath)[source]

Create and return a new ProjectSaveHistory instance

ccpn.core.lib.RestraintLib module

General utilities for Restraints

ccpn.core.lib.RestraintLib.dihedralName(project, restraintItem: tuple) str[source]

Get dihedral angle name from four-element atomId tuple

ccpn.core.lib.SpectrumLib module

Spectrum-related definitions, functions and utilities

class ccpn.core.lib.SpectrumLib.MagnetisationTransferTuple(dimension1, dimension2, transferType, isIndirect)

Bases: tuple

dimension1

Alias for field number 0

dimension2

Alias for field number 1

isIndirect

Alias for field number 3

transferType

Alias for field number 2

class ccpn.core.lib.SpectrumLib.NoiseEstimateTuple(mean, std, min, max, noiseLevel)

Bases: tuple

max

Alias for field number 3

mean

Alias for field number 0

min

Alias for field number 2

noiseLevel

Alias for field number 4

std

Alias for field number 1

class ccpn.core.lib.SpectrumLib.SpectrumDimensionTrait(trait=None, default_value=[], minlen=0, maxlen=9223372036854775807, **kwargs)[source]

Bases: ccpn.util.traits.CcpNmrTraits.List

A trait to implement a Spectrum dimensional attribute; e.g. like spectrumFrequencies

get(obj, cls=None)[source]
isDimensional = True
set(obj, value)[source]
validate(obj, value)[source]

Validate the value

ccpn.core.lib.SpectrumLib.WhittakerSmooth(y, w, lambda_, differences=1)[source]

Whittaker Smooth algorithm no licence, source from web Penalized least squares algorithm for background fitting

input

x: input data (i.e. chromatogram of spectrum) w: binary masks (value of the mask is zero if a point belongs to peaks and one otherwise) lambda_: parameter that can be adjusted by user. The larger lambda is, the smoother the resulting background differences: integer indicating the order of the difference of penalties

output

the fitted background vector

ccpn.core.lib.SpectrumLib.airPLS(y, lambda_=100, porder=1, itermax=15)[source]

airPLS algorithm no licence, source from web Adaptive iteratively reweighted penalized least squares for baseline fitting

input

x: input data (i.e. chromatogram of spectrum) lambda_: parameter that can be adjusted by user. The larger lambda is, the smoother the resulting background, z porder: adaptive iteratively reweighted penalized least squares for baseline fitting

output

the fitted background vector

ccpn.core.lib.SpectrumLib.align2HSQCs(refSpectrum, querySpectrum, refPeakListIdx=- 1, queryPeakListIdx=- 1)[source]
ccpn.core.lib.SpectrumLib.als(y, lam=100, p=0.001, nIter=10)[source]

Implements an Asymmetric Least Squares (Asl) Smoothing baseline correction algorithm H C Eilers, Paul & F M Boelens, Hans. (2005). Baseline Correction with Asymmetric Least Squares Smoothing. Unpubl. Manuscr. .

y = signal lam = smoothness, 10**2 ≤ λ ≤ 10**9. p = asymmetry, 0.001 ≤ p ≤ 0.1 is a good choice for a signal with positive peaks. niter = Number of iteration, default 10.

ccpn.core.lib.SpectrumLib.arPLS(y, lambda_=500000.0, ratio=1e-06, itermax=50)[source]

arPLS algorithm Baseline correction using asymmetrically reweighted penalized least squares smoothing. http://pubs.rsc.org/en/Content/ArticleLanding/2015/AN/C4AN01061B#!divAbstract

Parameters
  • y – The 1D spectrum

  • lambda – (Optional) Adjusts the balance between fitness and smoothness. A smaller lamda_ favors fitness. Default is 1.e5.

  • ratio – (Optional) Iteration will stop when the weights stop changing. (weights_(i) - weights_(i+1)) / (weights_(i)) < ratio. Default is 1.e-6.

Returns

The smoothed baseline of y.

ccpn.core.lib.SpectrumLib.arPLS_Implementation(y, lambdaValue=50000.0, maxValue=1000000.0, minValue=- 1000000.0, itermax=10, interpolate=True)[source]

Implementation of the arPLS algorithm :param maxValue = maxValue of the baseline noise :param minValue = minValue of the baseline noise :param interpolate: Where are the peaks: interpolate the points from neighbours otherwise set them to 0.

ccpn.core.lib.SpectrumLib.checkSpectrumPropertyValue(iterable: bool, unique: bool = False, allowNone: bool = False, types: tuple = (), enumerated: tuple = (), mapping=None)[source]

Decorator to check values of the Spectrum class property setters

Parameters
  • iterable – True, False: indicates that value should be an iterable

  • unique – True, False: indicates if iterable items should be unique

  • allowNone – True, False indicates if None value is allowed

  • types – a tuple of allowed types for value; value is cast into first type

  • enumerated – a tuple/list indicating that value should be one of the items of the tuple

  • mapping – an optional (originalValue, mappedValue) mapping dict; applied to the value or values-items

ccpn.core.lib.SpectrumLib.estimateNoiseLevel1D(y, f=10, stdFactor=0.5) Tuple[float, float][source]
Parameters
  • y – the y region of the spectrum.

  • f – percentage of the spectrum to use. If given a portion known to be just noise, set it to 100.

  • stdFactor – 0 to don’t adjust the initial guess.

Returns

tuple (float, float) of estimated noise threshold as max and min

ccpn.core.lib.SpectrumLib.estimateSNR(noiseLevels, signalPoints, factor=2.5)[source]

SNratio = factor*(height/|NoiseMax-NoiseMin|) :param noiseLevels: (max, min) floats :param signalPoints: iterable of floats estimated to be signal or peak heights :param factor: default 2.5 :return: array of snr for each point compared to the delta noise level

ccpn.core.lib.SpectrumLib.estimateSignalRegion(y, nlMax=None, nlMin=None)[source]
ccpn.core.lib.SpectrumLib.fetchPeakPicker(spectrum)[source]

Get a peakPicker; either by restore from spectrum or the default relevant for spectrum :return a PeakPicker instance or None on errors

ccpn.core.lib.SpectrumLib.get1DdataInRange(x, y, xRange)[source]
Parameters
  • x

  • y

  • xRange

Returns

x,y within the xRange (minXrange,maxXrange)

ccpn.core.lib.SpectrumLib.getAssignmentTolerances(isotopeCode) float[source]

:return assignmentTolerance for isotopeCode or defaultAssignment tolerance if not defined

ccpn.core.lib.SpectrumLib.getClippedRegion(spectrum, strip, sort=False)[source]

Return the clipped region, bounded by the (ppmPoint(1), ppmPoint(n)) in visible order

If sorting is True, returns a tuple(tuple(minPpm, maxPpm), …) for each region else returns tuple(tuple(ppmLeft, ppmRight), …)

Parameters
  • spectrum

  • strip

Returns

ccpn.core.lib.SpectrumLib.getContourEstimate(spectrum)[source]

Get an estimate of the contour settings from the spectrum Calculated from a random subset of points

ccpn.core.lib.SpectrumLib.getContourLevelsFromNoise(spectrum, setPositiveContours=False, setNegativeContours=False, useDefaultMultiplier=True, useDefaultLevels=True, useDefaultContourBase=False, useSameMultiplier=True, defaultMultiplier=1.414214, defaultLevels=10, defaultContourBase=10000.0)[source]

Calculate the noise level, base contour level and positive/negative multipliers for the given spectrum

ccpn.core.lib.SpectrumLib.getDefaultSpectrumColours(self: Spectrum) Tuple[str, str][source]

Get default positivecontourcolour, negativecontourcolour for Spectrum (calculated by hashing spectrum properties to avoid always getting the same colours Currently matches getDefaultColours in dataSource that is set through the api

ccpn.core.lib.SpectrumLib.getNoiseEstimate(spectrum)[source]

Get an estimate of the noiseLevel from the spectrum

noiseLevel is calculated as abs(mean) + 3.5 * SD

Calculated from a random subset of points

ccpn.core.lib.SpectrumLib.getNoiseEstimateFromRegion(spectrum, strip)[source]

Get the noise estimate from the visible region of the strip

Parameters
  • spectrum

  • strip

Returns

ccpn.core.lib.SpectrumLib.getSpectrumNoise(spectrum)[source]

Get the noise level for a spectrum. If the noise level is not already set it will be set at an estimated value.

Input

spectrum

Output

Float

ccpn.core.lib.SpectrumLib.nmrGlueBaselineCorrector(data, wd=20)[source]
Parameters

data – 1D ndarray One dimensional NMR data with real value (intensities) wd : float Median window size in pts.

Returns

same as data

ccpn.core.lib.SpectrumLib.polynomialFit(x, y, order: int = 3)[source]

polynomial Fit algorithm :param x: x values :param y: y values :param order: polynomial order :return: fitted baseline

ccpn.core.lib.SpectrumLib.setContourLevelsFromNoise(spectrum, setNoiseLevel=True, setPositiveContours=True, setNegativeContours=True, useDefaultMultiplier=True, useDefaultLevels=True, useDefaultContourBase=False, useSameMultiplier=True, defaultMultiplier=1.414214, defaultLevels=10, defaultContourBase=10000.0)[source]

Calculate the noise level, base contour level and positive/negative multipliers for the given spectrum

ccpn.core.lib.SpectrumPrototypes module

ccpn.core.lib.Summary module

Module Documentation here

ccpn.core.lib.Summary.assignableAtomCount(chain)[source]

Counts atoms that are not marked as exchanging with water Compound atoms (e.g. MB, QGB, HB%, HBx or HBy) are not counted For groups of equivalent atoms only the atom name ending in ‘1’ is counted Sometimes-equivalent atom groups (rotating aromatic rings) count as equivalent

ccpn.core.lib.Summary.assignedAtomCount(chain)[source]
ccpn.core.lib.Summary.assignedAtomPercentage(chain)[source]
ccpn.core.lib.Summary.fullyAssignedPeakCount(peakList)[source]
ccpn.core.lib.Summary.fullyAssignedPeakPercentage(peakList)[source]
ccpn.core.lib.Summary.partlyAssignedPeakCount(peakList)[source]
ccpn.core.lib.Summary.partlyAssignedPeakPercentage(peakList)[source]

ccpn.core.lib.Undo module

General undo handle supporting undo/redo stack

PyApiGen.py inserts the following line:

from ccpn.core.lib.Undo import _deleteAllApiObjects, restoreOriginalLinks, no_op

class ccpn.core.lib.Undo.Undo(maxWaypoints=50, maxOperations=10000, debug=False, application=None)[source]

Bases: collections.deque

Implementation of an undo and redo stack, with possibility of waypoints. A waypoint is the level at which an undo happens, and each of them could consist of multiple individual undo operations.

To create a waypoint use newWaypoint().

canRedo() bool[source]

True if a redo operation can be performed

canUndo() bool[source]

True if an undo operation can be performed

clear()[source]

Clear and reset undo object

clearRedoItems()[source]

Clear the items above the current next index, if there has been an error adding items

decreaseBlocking()[source]

Reduce level of blocking - when level reaches zero, undo is unblocked

decreaseWaypointBlocking()[source]

Reduce level of blocking - when level reaches zero, undo is unblocked

increaseBlocking()[source]

Set one more level of blocking

increaseWaypointBlocking()[source]

Set one more level of blocking

isDirty()[source]
markClean()[source]
markSave()[source]
markUndoClear()[source]
newItem(undoMethod, redoMethod, undoArgs=None, undoKwargs=None, redoArgs=None, redoKwargs=None)[source]

Add item to the undo stack.

property newItemsAdded

- None, immutable - Return the number of new items that have been added to the undo deque since the last new waypoint was created

newWaypoint()[source]

Start new waypoint

numItems()[source]

Return the number of undo items currently on the undo deque

redo()[source]

Redo one waypoint - or one operation if waypoints are not set.

For now errors are handled by printing a warning and clearing the undo object

undo()[source]

Undo one operation - or one waypoint if waypoints are set

For now errors are handled by printing a warning and clearing the undo object

property undoItemBlocking

- None, immutable - Undo blocking. If true (non-zero) undo setting is blocked. Allows multiple external functions to set blocking without trampling each other

Modify with increaseBlocking/decreaseBlocking only

property undoItemBlockingLevel

- None, immutable - Undo blocking Level. If true (non-zero) undo setting is blocked. Allows multiple external functions to set blocking without trampling each other

Modify with increaseBlocking/decreaseBlocking only

property undoList

- None, immutable -

property waypointBlocking

- None, immutable - Undo blocking. If true (non-zero) undo setting is blocked. Allows multiple external functions to set blocking without trampling each other

Modify with increaseBlocking/decreaseBlocking only

class ccpn.core.lib.Undo.UndoEvents(value)[source]

Bases: enum.Enum

An enumeration.

UNDO_ADD = 4
UNDO_CLEAR = 3
UNDO_MARK_CLEAN = 6
UNDO_MARK_SAVE = 5
UNDO_REDO = 2
UNDO_UNDO = 1
class ccpn.core.lib.Undo.UndoObserver[source]

Bases: object

Class to store functions to call when undo stack operations are performed

add(callback)[source]
call(action)[source]
clear()[source]
remove(callback)[source]
ccpn.core.lib.Undo.no_op()[source]

Does nothing - for special undo situations where only one direction must act

ccpn.core.lib.Undo.resetUndo(memopsRoot, maxWaypoints=50, maxOperations=10000, debug: bool = False, application=None)[source]

Set or reset undo stack, using passed-in parameters. NB setting either parameter to 0 removes the undo stack.

Set obj values using obj2Value dictionary

ccpn.core.lib.Util module

CCPN-level utility code independent of model content

class ccpn.core.lib.Util.AtomIdTuple(chainCode, sequenceCode, residueType, atomName)

Bases: tuple

atomName

Alias for field number 3

chainCode

Alias for field number 0

residueType

Alias for field number 2

sequenceCode

Alias for field number 1

ccpn.core.lib.Util.commandParameterString(*params, values: Optional[dict] = None, defaults: Optional[dict] = None)[source]

Make parameter string to insert into function call string.

params are positional parameters in order, values are keyword parameters. If the defaults dictionary is passed in, only parameters in defaults are added to the string, and only if the value differs from the default. This allows you to pass in values=locals(). The order of keyword parameters follows defaults if given, else values, so you can get ordered parameters by passing in ordered dictionaries.

Wrapper object values are replaced with their Pids

Example:

commandParameterString(11, values={a:1, b:<Note NO:notename>, c:2, d:3, e:4},

defaults=OrderedDict(d=8, b=None, c=2))

will return

“11, d=3, b=’NO:notename’”

ccpn.core.lib.Util.commandParameterStringValues(*params, values: Optional[dict] = None, defaults: Optional[dict] = None)[source]

Make parameter string to insert into function call string.

params are positional parameters in order, values are keyword parameters. If the defaults dictionary is passed in, only parameters in defaults are added to the string, and only if the value differs from the default. This allows you to pass in values=locals(). The order of keyword parameters follows defaults if given, else values, so you can get ordered parameters by passing in ordered dictionaries.

Wrapper object values are replaced with their Pids

Example:

commandParameterString(11, values={a:1, b:<Note NO:notename>, c:2, d:3, e:4},

defaults=OrderedDict(d=8, b=None, c=2))

will return

“11, d=3, b=’NO:notename’”

ccpn.core.lib.Util.funcCaller() Optional[str][source]

return the name of the current function (actually the parent caller to this function, hence the index of ‘1’) :return: string name

ccpn.core.lib.Util.getParentObjectFromPid(project, pid)[source]

Get a parent object from a pid, which may represent a deleted object.

Returns

Parent object or None on error/non-existence

Example:

pid = ‘NA:A.40.ALA.CB’ getParentObjectFromPid(pid) -> ‘NR:A.40.ALA’

ccpn.core.lib.Util.getParentPid(childPid) ccpn.core.lib.Pid.Pid[source]

Get the pid of parent of childPid; only uses Pid definitions (i.e. does not involve the actual objects) :returns Pid instance defining parent

ccpn.core.lib.Util.pid2PluralName(pid: str) str[source]

Get plural class name, (e.g. ‘peaks’, ‘spectra’ from short-form or long-form, Pid string Unrecognised strings are returned unchanged

ccpn.core.lib.peakUtils module

class ccpn.core.lib.peakUtils.Dictlist[source]

Bases: dict

ccpn.core.lib.peakUtils.estimate1DPeakFWHM(peak)[source]

Estimate the 1D peak Full Width at Half Maximum.

width: The width for the peak in points. widthHeight: The height of the contour lines at which the width was evaluated. limits: tuple, Interpolated positions of left and right intersection points of a

horizontal line at the respective evaluation height.

ccpn.core.lib.peakUtils.estimateVolumes(peaks: Sequence[Peak | str], volumeIntegralLimit=2.0)[source]

Estimate the volumes for the peaks :param peaks: list of peaks as pids or strings :param volumeIntegralLimit: integral width as a multiple of lineWidth (FWHM)

ccpn.core.lib.peakUtils.exponenial_func(x, a, b)[source]
ccpn.core.lib.peakUtils.find_nearest(array, value)[source]
ccpn.core.lib.peakUtils.getMultipletLinewidth(peak, dim)[source]
ccpn.core.lib.peakUtils.getMultipletPosition(multiplet, dim, unit='ppm')[source]
ccpn.core.lib.peakUtils.getNmrResidueDeltas(nmrResidue, nmrAtomsNames, spectra, mode='positions', atomWeights=None)[source]
Parameters
  • nmrResidue

  • nmrAtomsNames – nmr Atoms to compare. str ‘H’, ‘N’, ‘CA’ etc

  • spectra – compare peaks only from given spectra

Returns

ccpn.core.lib.peakUtils.getNmrResiduePeakHeight(nmrResidue, nmrAtomsNames, spectra)[source]
Parameters
  • nmrResidue

  • nmrAtomsNames – nmr Atoms to compare. str ‘H’, ‘N’, ‘CA’ etc

  • spectra – compare peaks only from given spectra

Returns

ccpn.core.lib.peakUtils.getNmrResiduePeakProperty(nmrResidue, nmrAtomsNames, spectra, theProperty='height')[source]
Parameters
  • nmrResidue

  • nmrAtomsNames – nmr Atoms to compare. str ‘H’, ‘N’, ‘CA’ etc

  • spectra – compare peaks only from given spectra

  • theProperty – ‘height’ or ‘volume’

Returns

ccpn.core.lib.peakUtils.getPeakAnnotation(peak, dim, separator=', ')[source]
ccpn.core.lib.peakUtils.getPeakLinewidth(peak, dim)[source]

Return the lineWidth in dimension ‘dim’ for the peakTable entries

ccpn.core.lib.peakUtils.getPeakPosition(peak, dim, unit='ppm')[source]
ccpn.core.lib.peakUtils.getRawDataFrame(nmrResidues, nmrAtomsNames, spectra, theProperty)[source]
ccpn.core.lib.peakUtils.getSpectralPeakHeightForNmrResidue(spectra, peakListIndexes: Optional[list] = None) pandas.core.frame.DataFrame[source]
return: Pandas DataFrame with the following structure:

Index: ID for the nmrResidue(s) assigned to the peak ; Columns => Spectrum series values sorted by ascending values, if series values are not set, then the

spectrum name is used instead.

SP1 | SP2 | SP3

NR_ID | | |

————+———–+———–+———-

A.1.ARG | 10 | 100 | 1000

ccpn.core.lib.peakUtils.getSpectralPeakHeights(spectra, peakListIndexes: Optional[list] = None) pandas.core.frame.DataFrame[source]
ccpn.core.lib.peakUtils.getSpectralPeakVolumeForNmrResidue(spectra, peakListIndexes: Optional[list] = None) pandas.core.frame.DataFrame[source]
return: Pandas DataFrame with the following structure:

Index: ID for the nmrResidue(s) assigned to the peak ; Columns => Spectrum series values sorted by ascending values, if series values are not set, then the

spectrum name is used instead.

SP1 | SP2 | SP3

NR_ID | | |

————+———–+———–+———-

A.1.ARG | 10 | 100 | 1000

ccpn.core.lib.peakUtils.getSpectralPeakVolumes(spectra, peakListIndexes: Optional[list] = None) pandas.core.frame.DataFrame[source]
ccpn.core.lib.peakUtils.movePeak(peak, ppmPositions, updateHeight=True)[source]

Move a peak based on it’s delta shift and optionally update to the height at the new position

ccpn.core.lib.peakUtils.oneSiteBindingCurve(x, kd, bmax)[source]
ccpn.core.lib.peakUtils.peakParabolicInterpolation(peak: Peak, update=False)[source]

return a (position, height, heightError) tuple using parabolic interpolation of the peak.position

Parameters
  • peak – a core.Peak instance or Pid or valid pid-string

  • update – flag indicating peak position and height to be updated

Returns

(position, height) tuple; position is a list with length spectrum.dimensionCount

ccpn.core.lib.peakUtils.recalculatePeaksHeightAtPosition(peaks)[source]
ccpn.core.lib.peakUtils.snap1DPeaksAndRereferenceSpectrum(peaks, maximumLimit=0.1, useAdjacientPeaksAsLimits=False, doNeg=False, figOfMeritLimit=1, spectrum=None, autoRereferenceSpectrum=False)[source]

Snap all peaks to closest maxima

Steps: - reorder the peaks by heights to give higher peaks priority to the snap - 1st iteration: search for nearest maxima and calculate delta positions (don’t set peak.position here yet) - use deltas to fit patterns of shifts and detect the most probable global shift - use the global shift to re-reference the spectrum - 2nd iteration: re-search for nearest maxima - set newly detected position to peak if found better fits - re-set the spectrum referencing to original (if not requested as argument)

Parameters
  • peaks – list of peaks to snap

  • maximumLimit – float to use as + left-right limits from peak position where to search new maxima

  • useAdjacientPeaksAsLimits – bool. use adj peak position as left-right limits. don’t search maxima after adjacent peaks

  • doNeg – snap also negative peaks

  • figOfMeritLimit – float. don’t snap peaks with FOM below limit threshold

  • spectrum – the spectum obj. optional if all peaks belong to the same spectrum

Returns

ccpn.core.lib.peakUtils.snap1DPeaksToExtrema(peaks, maximumLimit=0.1, figOfMeritLimit=1, doNeg=True)[source]
ccpn.core.lib.peakUtils.snapToExtremum(peak: Peak, halfBoxSearchWidth: int = 3, halfBoxFitWidth: int = 3, minDropFactor: float = 0.1, fitMethod: str = 'parabolic', searchBoxMode=False, searchBoxDoFit=False)[source]

Snap the position of the peak the nearest extremum. Assumes called with an existing peak, will fit within a box ±halfBoxSearchWidth about the current peak position.

ccpn.core.lib.peakUtils.updateHeight(peak)[source]