Beispiel #1
0
  def importNmrStar31(self):

    if not self.project:
      showWarning('Failure','Please create a new CCPN project.', parent=self)
      return

    fileTypes = [ FileType('STAR', ['*.str']),
                  FileType('All', ['*'])]

    fileSelectPopup = FileSelectPopup(self, file_types=fileTypes,
                        title='Import NMR-STAR 3.1 file', dismiss_text='Cancel',
                        selected_file_must_exist=True, multiSelect=False,)

    fileName = fileSelectPopup.getFile()

    if not os.path.exists(fileName):
      showWarning('Failure','No such file.', parent=self)
      return

    if fileName:
      nmrStarObj = NmrStarFormat(self.project, self, verbose=True)
      nmrStarObj.readProject(fileName, minimalPrompts=True, version='3.1')

      self.eciFrame.updateAll()

      return nmrStarObj
Beispiel #2
0
def importFullStarProjects(starFileName, projectName, inputDir='.', outputDir='.', guiRoot=None, allowPopups=0,minimalPrompts=1,verbose=1):
    '''Returns a full CCPN project rooted in inputDir/projectName that will be created and saved.
    Input will be from inputDir/starFileName

    Returns False for error.
    '''

    if not os.path.exists(inputDir):
        nTerror("Failed to find inputDir: %s" % inputDir)
        return False
    starFileNameFull = os.path.join(inputDir, starFileName)
    if not os.path.exists(starFileNameFull):
        nTerror("Failed to find starFileNameFull: %s" % starFileNameFull)
        return False
    if not os.path.exists(outputDir):
        os.mkdir(outputDir)
    os.chdir(outputDir)

    ccpnProjectPath = os.path.join(outputDir, projectName)
    if os.path.exists(ccpnProjectPath):
        shutil.rmtree(ccpnProjectPath)

    ccpnProject = Implementation.MemopsRoot(name=projectName)

#    'linkAtoms':                (True,False,'If set to False (off), unrecognized coordinate atoms will not be linked.'),
    keywds = {'minimalPrompts': minimalPrompts, 'allowPopups': allowPopups, 'linkAtoms':0}
    formatNmrStarFormat = NmrStarFormat(ccpnProject, guiRoot, verbose=verbose, **keywds)
    formatNmrStarFormat.version = '3.1'
    entryTitle = 'Project from NMR-STAR for %s' % projectName
    entryDetails = "Created by Wim Vranken's FormatConverter embedded in CING"
    formatNmrStarFormat.getFullProject( starFileNameFull, title = entryTitle, details = entryDetails, **keywds)
#    nmrConstraintStore = shiftList.nmrConstraintStore
#    structureGeneration = nmrConstraintStore.findFirstStructureGeneration()
#    formatNmrStarFormat.linkResonances(
#                  forceDefaultChainMapping=1, # may be overwritten by using forceChainMappings.
#                  globalStereoAssign=1,
#                  setSingleProchiral=1,
#                  setSinglePossEquiv=1,
##                  strucGen=structureGeneration,
#                  allowPopups=allowPopups, minimalPrompts=minimalPrompts, verbose=verbose, **keywds)
    # Catch entries like mentioned in issue

    try:
        ccpnProject.checkAllValid()
    except ApiError:
        nTtracebackError()
        nTerror("Failed ccpnProject.checkAllValid")
        nTerror("See issue: %s%d" % (issueListUrl, 266))
        return False

    ccpnProject.saveModified()

    if not os.path.exists(ccpnProjectPath):
        nTerror("Failed to find new CCPN project directory: %s" % ccpnProjectPath)
        return False
    tgzFileName = projectName + ".tgz"
    cmd = "tar -czf %s %s" % (tgzFileName, projectName)
    do_cmd(cmd)

    return ccpnProject
Beispiel #3
0
def importStarChemicalShifts(ccpnProject, inputDir, guiRoot, allowPopups=1, minimalPrompts=0, verbose=1, **presets):
    print "JFD: now in importStarChemicalShifts"


#    formatCns = CnsFormat(ccpnProject, guiRoot, verbose=verbose, minimalPrompts=minimalPrompts, allowPopups=allowPopups, **presets)
    formatNmrStarFormat = NmrStarFormat(ccpnProject, guiRoot, verbose=verbose, minimalPrompts=minimalPrompts, 
                                        allowPopups=allowPopups, **presets)
    ccpnShiftListOfList = []

    # Actually just one but this is less time to code;-)
    globPattern = inputDir + '/*_21.str'
    fileList = glob(globPattern)
    nTdebug("From %s will read files: %s" % (globPattern, fileList))

    for fn in fileList:
        fnBaseName = os.path.basename(fn).split('.')[0]
        shiftList = formatNmrStarFormat.readShifts(fn, minimalPrompts=minimalPrompts, verbose=verbose)
        if not shiftList:
            nTerror("Failed to read")
            return True
        shiftList.setName(fnBaseName)
        ccpnShiftListOfList.append(shiftList)
        # Find and print this shiftList in the CCPN data model. Just to check lookup.
        shiftList = ccpnProject.currentNmrProject.findFirstMeasurementList(className = 'ShiftList')
        print 'ShiftList: [%s]' % shiftList


    keywds = getDeepByKeysOrDefault(presets, {}, READ_SHIFTS, KEYWORDS)
    if keywds:
        nTmessage("In importStarChemicalShifts using keywds...")
        nTdebug(str(keywds))

    shiftList = getDeepByKeys(ccpnShiftListOfList, 0) # no need to repeat
    nTdebug("First shiftList: %s" % shiftList)
    if shiftList == None:
        nTerror("Failed to get shiftList again.")
        return True

#    nmrConstraintStore = shiftList.nmrConstraintStore
#    structureGeneration = nmrConstraintStore.findFirstStructureGeneration()
    formatNmrStarFormat.linkResonances(
                  forceDefaultChainMapping=1, # may be overwritten by using forceChainMappings.
                  globalStereoAssign=1,
                  setSingleProchiral=1,
                  setSinglePossEquiv=1,
#                  strucGen=structureGeneration,
                  allowPopups=allowPopups, minimalPrompts=minimalPrompts, verbose=verbose, **keywds)
Beispiel #4
0
def writeBmrbChemShiftDeposition(guiParent, chain, chemShiftList, outFile):

    proj = chain.root

    format = NmrStarFormat(proj, guiParent, verbose=1)

    fout = open(outFile, 'w')

    resSeq = newline

    for residue in chain.sortedResidues():

        resSeq += residue.molResidue.chemComp.getCode1Letter()

        chopOff = len(resSeq) / 41.0

        if chopOff == int(chopOff):
            resSeq += newline

    fout.write("_Mol_residue_sequence" + newline)
    fout.write(";")
    fout.write(resSeq + newline)
    fout.write(";" + (newline * 2))

    fout.write("""
loop_
        _Residue_seq_code
        _Residue_author_seq_code
        _Residue_label""")

    fout.write(newline * 2)

    count = 0

    for residue in chain.sortedResidues():

        count += 1

        fout.write("%-3d %-3d %3s" %
                   (residue.seqId, residue.seqCode, residue.ccpCode))

        if count / 5.0 == int(count / 5.0):
            fout.write(newline)
        else:
            fout.write("     ")

    fout.write("stop_")
    fout.write(newline)

    fout.write("""
###################################################################
#      Chemical Shift Ambiguity Code Definitions                  #
#                                                                 #
#    Codes            Definition                                  #
#                                                                 #
#      1             Unique                                       #
#      2             Ambiguity of geminal atoms or geminal methyl #
#                         proton groups                           #
#      3             Aromatic atoms on opposite sides of the ring #
#                        (e.g. Tyr HE1 and HE2 protons)           #
#      4             Intraresidue ambiguities (e.g. Lys HG and    #
#                         HD protons)                             #
#      5             Interresidue ambiguities (Lys 12 vs. Lys 27) #
#      9             Ambiguous, specific ambiguity not defined    #
#                                                                 #
###################################################################


# INSTRUCTIONS
# 1) Replace the @-signs with appropriate values.
# 2) Text comments concerning the assignments can be
#    supplied in the full deposition.
# 3) Feel free to add or delete rows to the table as needed.
#    The row numbers (_Atom_shift_assign_ID values) will be
#    re-assigned to sequential values by BMRB


# The atom table chosen for this sequence is:

loop_
     _Atom_shift_assign_ID
     _Residue_seq_code
     _Residue_label
     _Atom_name
     _Atom_type
     _Chem_shift_value
     _Chem_shift_value_error
     _Chem_shift_ambiguity_code

#
#Atom   Residue
#shift  Seq     Residue Atom    Atom    Shift/  Error/  Ambiguity
#assign code    Label   Name    Type    ppm     ppm     Code
#---------------------------------------------------------------
#""")

    fout.write(newline * 2)

    # Using code originally written for XEasy output

    format.getFormatNamingSystemName = getFormatNamingSystemName
    format.writeShifts(outFile,
                       measurementList=chemShiftList,
                       chains=[chain],
                       noWrite=True,
                       compressResonances=False)

    counter = 1
    for chemShift in format.measurementFile.chemShifts:

        if chemShift.atomName[-1] == '*':
            atomName = chemShift.atomName[:-1]
        else:
            atomName = chemShift.atomName

        fout.write("%-6d   %-5d  %-4s    %-5s   %-5s   %-7.3f %-7.3f %d" %
                   (counter, chemShift.seqCode, chemShift.resLabel, atomName,
                    chemShift.atomType, chemShift.value, chemShift.valueError,
                    chemShift.ambCode))

        counter += 1

        fout.write(newline)

    fout.write(newline)
    fout.write("stop_")
    fout.write(newline * 2)

    fout.close()

    return True
Beispiel #5
0
def makeChemShiftSelections(guiParent, chains, chemShiftList, verbose=0):

    #
    # TODO: only NON-EXCHANGABLE hydrogens for sidechain!!! Mark them in ref data?
    #

    #
    # Get the info from the chemical shift list and the relevant chains
    #

    if not chains or not chemShiftList:
        print "  ERROR need chains or chemShiftList!"
        return False

    #
    # Set up for all chains...
    #

    results = {}

    for chain in chains:

        if chain.molecule.molType not in chemShiftClasses.keys():
            continue

        chemShiftClassMolType = chemShiftClasses[chain.molecule.molType]

        for residue in chain.sortedResidues():

            atomSetsDone = []

            for atom in residue.sortedAtoms():

                atomType = atom.chemAtom.elementSymbol

                if atomType not in chemShiftClassMolType.keys():
                    continue

                atomChemShiftClasses = chemShiftClassMolType[atomType]

                atomName = atom.name
                atomRecognized = 0

                for chemShiftClass in atomChemShiftClasses.keys():

                    (findAtomNames,
                     ignoreAtomNames) = atomChemShiftClasses[chemShiftClass]

                    atomFound = 0

                    if atomName in findAtomNames:

                        atomFound = 1

                    elif not findAtomNames:

                        if atomName not in ignoreAtomNames:

                            chemAtom = atom.chemAtom
                            chemAtomSet = chemAtom.chemAtomSet

                            if chemAtomSet and (chemAtomSet.isEquivalent
                                                or chemAtomSet.isEquivalent
                                                == None):

                                if chemAtomSet.name not in atomSetsDone:
                                    atomSetsDone.append(chemAtomSet.name)
                                    atomFound = 1

                                atomRecognized = 1

                            else:
                                atomFound = 1

                    if atomFound:

                        atomRecognized = 1

                        if not results.has_key(chemShiftClass):
                            results[chemShiftClass] = [0, 0]

                        results[chemShiftClass][0] += 1

                if not atomRecognized:
                    print " Chain atom name %s not found" % atomName

    #
    # Do per chain... but keep track of all.
    #

    format = NmrStarFormat(chains[0].root, guiParent, verbose=0)
    format.getFormatNamingSystemName = getFormatNamingSystemName

    for chain in chains:

        if chain.molecule.molType not in chemShiftClasses.keys():
            continue

        chemShiftClassMolType = chemShiftClasses[chain.molecule.molType]

        format.writeShifts('voidFileNotWritten',
                           measurementList=chemShiftList,
                           chains=[chain],
                           noWrite=True,
                           verbose=False,
                           individualAtoms=False)

        for chemShift in format.measurementFile.chemShifts:

            atomType = chemShift.atomType

            if atomType not in chemShiftClassMolType.keys():
                continue

            atomChemShiftClasses = chemShiftClassMolType[atomType]
            atomRecognized = 0

            for chemShiftClass in atomChemShiftClasses.keys():

                (findAtomNames,
                 ignoreAtomNames) = atomChemShiftClasses[chemShiftClass]

                atomFound = 0

                if chemShift.atomName in findAtomNames:

                    atomFound = 1

                elif not findAtomNames:

                    if chemShift.atomName not in ignoreAtomNames:
                        atomFound = 1

                if atomFound:
                    atomRecognized = 1
                    results[chemShiftClass][1] += 1

            if not atomRecognized:
                print " Chemical shift atom name %s not found" % atomName

        del format.measurementFile

    #
    # Print results
    #

    if verbose:

        chemShiftResultClasses = results.keys()
        chemShiftResultClasses.sort()

        for chemShiftClass in chemShiftResultClasses:
            percentage = results[chemShiftClass][1] * 100.0 / results[
                chemShiftClass][0]
            print "  %-20s: %6.2f found (%d/%d total)" % (
                chemShiftClass, percentage, results[chemShiftClass][1],
                results[chemShiftClass][0])

    return results
Beispiel #6
0
def importFullStarProjects(starFileName,
                           projectName,
                           inputDir='.',
                           outputDir='.',
                           guiRoot=None,
                           allowPopups=0,
                           minimalPrompts=1,
                           verbose=1):
    '''Returns a full CCPN project rooted in inputDir/projectName that will be created and saved.
    Input will be from inputDir/starFileName

    Returns False for error.
    '''

    if not os.path.exists(inputDir):
        nTerror("Failed to find inputDir: %s" % inputDir)
        return False
    starFileNameFull = os.path.join(inputDir, starFileName)
    if not os.path.exists(starFileNameFull):
        nTerror("Failed to find starFileNameFull: %s" % starFileNameFull)
        return False
    if not os.path.exists(outputDir):
        os.mkdir(outputDir)
    os.chdir(outputDir)

    ccpnProjectPath = os.path.join(outputDir, projectName)
    if os.path.exists(ccpnProjectPath):
        shutil.rmtree(ccpnProjectPath)

    ccpnProject = Implementation.MemopsRoot(name=projectName)

    #    'linkAtoms':                (True,False,'If set to False (off), unrecognized coordinate atoms will not be linked.'),
    keywds = {
        'minimalPrompts': minimalPrompts,
        'allowPopups': allowPopups,
        'linkAtoms': 0
    }
    formatNmrStarFormat = NmrStarFormat(ccpnProject,
                                        guiRoot,
                                        verbose=verbose,
                                        **keywds)
    formatNmrStarFormat.version = '3.1'
    entryTitle = 'Project from NMR-STAR for %s' % projectName
    entryDetails = "Created by Wim Vranken's FormatConverter embedded in CING"
    formatNmrStarFormat.getFullProject(starFileNameFull,
                                       title=entryTitle,
                                       details=entryDetails,
                                       **keywds)
    #    nmrConstraintStore = shiftList.nmrConstraintStore
    #    structureGeneration = nmrConstraintStore.findFirstStructureGeneration()
    #    formatNmrStarFormat.linkResonances(
    #                  forceDefaultChainMapping=1, # may be overwritten by using forceChainMappings.
    #                  globalStereoAssign=1,
    #                  setSingleProchiral=1,
    #                  setSinglePossEquiv=1,
    ##                  strucGen=structureGeneration,
    #                  allowPopups=allowPopups, minimalPrompts=minimalPrompts, verbose=verbose, **keywds)
    # Catch entries like mentioned in issue

    try:
        ccpnProject.checkAllValid()
    except ApiError:
        nTtracebackError()
        nTerror("Failed ccpnProject.checkAllValid")
        nTerror("See issue: %s%d" % (issueListUrl, 266))
        return False

    ccpnProject.saveModified()

    if not os.path.exists(ccpnProjectPath):
        nTerror("Failed to find new CCPN project directory: %s" %
                ccpnProjectPath)
        return False
    tgzFileName = projectName + ".tgz"
    cmd = "tar -czf %s %s" % (tgzFileName, projectName)
    do_cmd(cmd)

    return ccpnProject
Beispiel #7
0
def importStarChemicalShifts(ccpnProject,
                             inputDir,
                             guiRoot,
                             allowPopups=1,
                             minimalPrompts=0,
                             verbose=1,
                             **presets):
    print "JFD: now in importStarChemicalShifts"

    #    formatCns = CnsFormat(ccpnProject, guiRoot, verbose=verbose, minimalPrompts=minimalPrompts, allowPopups=allowPopups, **presets)
    formatNmrStarFormat = NmrStarFormat(ccpnProject,
                                        guiRoot,
                                        verbose=verbose,
                                        minimalPrompts=minimalPrompts,
                                        allowPopups=allowPopups,
                                        **presets)
    ccpnShiftListOfList = []

    # Actually just one but this is less time to code;-)
    globPattern = inputDir + '/*_21.str'
    fileList = glob(globPattern)
    nTdebug("From %s will read files: %s" % (globPattern, fileList))

    for fn in fileList:
        fnBaseName = os.path.basename(fn).split('.')[0]
        shiftList = formatNmrStarFormat.readShifts(
            fn, minimalPrompts=minimalPrompts, verbose=verbose)
        if not shiftList:
            nTerror("Failed to read")
            return True
        shiftList.setName(fnBaseName)
        ccpnShiftListOfList.append(shiftList)
        # Find and print this shiftList in the CCPN data model. Just to check lookup.
        shiftList = ccpnProject.currentNmrProject.findFirstMeasurementList(
            className='ShiftList')
        print 'ShiftList: [%s]' % shiftList

    keywds = getDeepByKeysOrDefault(presets, {}, READ_SHIFTS, KEYWORDS)
    if keywds:
        nTmessage("In importStarChemicalShifts using keywds...")
        nTdebug(str(keywds))

    shiftList = getDeepByKeys(ccpnShiftListOfList, 0)  # no need to repeat
    nTdebug("First shiftList: %s" % shiftList)
    if shiftList == None:
        nTerror("Failed to get shiftList again.")
        return True


#    nmrConstraintStore = shiftList.nmrConstraintStore
#    structureGeneration = nmrConstraintStore.findFirstStructureGeneration()
    formatNmrStarFormat.linkResonances(
        forceDefaultChainMapping=
        1,  # may be overwritten by using forceChainMappings.
        globalStereoAssign=1,
        setSingleProchiral=1,
        setSinglePossEquiv=1,
        #                  strucGen=structureGeneration,
        allowPopups=allowPopups,
        minimalPrompts=minimalPrompts,
        verbose=verbose,
        **keywds)