Exemplo n.º 1
0
    def getFilterFiles(self, directory):

        isDir = os.path.isdir

        filterFiles = set()
        for filtr in self.fileType.filters:
            # have to use fullfilter rather than filter because cwd is not directory in general
            fullfilter = joinPath(directory, filtr)
            filterFiles.update(glob.glob(fullfilter))

        # remove directory from file names

        n = len(directory)
        if directory[-1] != dirsep:
            n = n + 1

        filterFiles = list(set([x[n:] for x in filterFiles if not isDir(x)]))
        filterFiles.sort()

        # add in subdirectories
        subDirs = [
            x for x in os.listdir(directory) if isDir(joinPath(directory, x))
        ]
        subDirs.sort()

        return subDirs + filterFiles
Exemplo n.º 2
0
  def singleCallback(self, entry, row, col):

    file = joinPath(self.directory, entry)
    if os.path.isdir(file):
      if not self.show_file:
        self.directory_entry.setEntry(joinPath(self.directory, entry))
    else:
      if self.show_file:
        self.file_entry.setEntry(entry)
      if self.single_callback:
        self.single_callback(file)
Exemplo n.º 3
0
    def showAminoPlot(self):

        matrix = self.matrix
        binWidth = self.binWidth
        canvas = self.canvas
        itemconf = canvas.itemconfigure
        scaleColorQuick = self.scaleColorQuick

        if self.aminoAcid:
            colors = self.canvasDict.get(self.aminoAcid)

            if not colors:
                # fileName is the name of a PGM file in P2 format
                fileName = joinPath(self.bitmapDir,
                                    'log_%s.pgm' % self.aminoAcid.upper())
                colors = self.readPGM(fileName)
                self.canvasDict[self.aminoAcid] = colors

            if not colors:
                showWarning(
                    'Warning',
                    'Ramachandran plot data for %s does not exist! Using default'
                    % self.aminoAcid)
                fileName = joinPath(self.bitmapDir, 'log_ALL.pgm')
                colors = self.readPGM(fileName)
                self.canvasDict[self.aminoAcid] = colors

        else:
            colors = self.canvasDict.get('ALL')

            if not colors:
                fileName = joinPath(self.bitmapDir, 'log_ALL.pgm')
                colors = self.readPGM(fileName)
                self.canvasDict['ALL'] = colors

        for i in range(len(colors)):
            for j in range(len(colors[0])):
                item = matrix[i][j]
                color = colors[i][j]
                itemconf(item, fill=color)
                if binWidth < 7:
                    itemconf(item, outline=color)
                elif binWidth < 12:
                    itemconf(item, outline=scaleColorQuick(color, 0.9))
                else:
                    itemconf(item, outline=scaleColorQuick(color, 0.8))

        itemconf(self.title, text=self.aminoAcid or 'All Residue Types')
Exemplo n.º 4
0
    def determineDir(self, directory):

        directory = normalisePath(directory)

        assert os.path.isdir(directory), '"%s" is not a directory' % directory

        self.prev_directory = self.directory

        if not os.path.isabs(directory):
            if self.directory is None:  # first time around
                directory = joinPath(normalisePath(os.getcwd()), directory)
            else:
                directory = joinPath(self.directory, directory)

        self.directory = directory
        self.dirs = self.directory.split(dirsep)
Exemplo n.º 5
0
  def __init__(self, parent, selectionList, title = 'Select', text = 'Select', topText = None, dismissText = None, selected = None, selectionDict = None, urlFile = None, dismissButton = True, modal = False):
  
    self.selectionList = selectionList
    self.selectionDict = selectionDict
    
    self.text = text
    
    self.dismissButton = dismissButton
    
    if dismissButton:
      if dismissText:
        self.dismissText = dismissText
      else:
        self.dismissText = 'dismiss'
      
    self.topText = topText
    self.isSelected = None

    if not selected:
      self.selectedIndex = 0
    else:
      self.selectedIndex = self.selectionList.index(selected)
      
    if urlFile:
      self.help_url = joinPath(getHelpUrlDir(),urlFile + '.html')
    else:
      self.help_url = None
          
    TemporaryBasePopup.__init__(self,parent = parent, title = title, modal = modal, transient=True)
Exemplo n.º 6
0
    def updateInfo(self, *extra):

        projName = self.proj_name_entry.get()
        directory = self.proj_dir_select.getDirectory()
        directory = joinPath(directory, projName)

        self.proj_dir_label.set(directory)
Exemplo n.º 7
0
    def save(self):

        projName = self.proj_name_entry.get()
        directory = self.proj_dir_select.getDirectory()
        directory = joinPath(directory, projName)
        if self.isProjectDirectory(directory):
            if not showOkCancel('Overwrite directory',
                                'Overwrite existing project directory?',
                                parent=self):
                return

        self.updateInfo()

        self.did_save = False
        changeDataLocations = self.dataCheckButton.isSelected()
        done = False
        try:
            done = Io.saveProject(self.project,
                                  newPath=directory,
                                  newProjectName=projName,
                                  createFallback=True,
                                  showYesNo=showYesNo,
                                  changeDataLocations=changeDataLocations,
                                  showWarning=showWarning)

            if done:
                showInfo('Project saved', 'Project saved successfully')
                self.did_save = True
                if self.callback:
                    self.callback(self.project)
            elif self.modal:
                return  # give another chance
        except Implementation.ApiError, e:
            showError('Save project', e.error_msg)
Exemplo n.º 8
0
    def __init__(self,
                 parent,
                 message,
                 nmrRes,
                 optionList,
                 title,
                 urlFile=None):

        # Constructor doesn't do much except call body
        # The parent is self.parent (parent of the popup)

        self.singleResonanceStatus = None

        self.message = message
        self.optionList = optionList
        self.nmrRes = nmrRes

        if urlFile:
            self.help_url = joinPath(getHelpUrlDir(), urlFile + '.html')

        else:
            self.help_url = None

        # modal = true means that it won't continue unless this one returns value
        BasePopup.__init__(self,
                           parent=parent,
                           title=title,
                           modal=True,
                           transient=True)
Exemplo n.º 9
0
 def callback(key, values, comment):
     if key == 'control':
         if project.foundControl:
             raise AnsigParseException('control found twice')
         project.foundControl = True
         controlKeywordDict = {
             'help_dir': (False, 1, (None, )),
             'html_viewer': (False, 1, (None, )),
             'dictionary': (False, 1, (None, )),
             'gr_translate': (False, 1, (None, )),
             'sequence': (False, 1, (None, )),
             'spectra': (False, 1, (None, )),
             'crosspeaks': (False, 1, (None, )),
             'backup': (False, 1, (None, )),
             'initialize': (False, 1, (None, )),
             'exit': (False, 1, (None, )),
             'binaryformat': (False, 1, (None, )),
             'font': (False, 1, (None, )),
         }
         return controlKeywordDict
     elif key in ('sequence', 'spectra', 'crosspeaks', 'binaryformat'):
         value = values[0]
         if key != 'binaryformat':
             key = key + 'File'
             if not os.path.isabs(value):
                 base = os.path.dirname(project.projectFile)
                 value = joinPath(base, value)
         setattr(project, key, value)
Exemplo n.º 10
0
  def __init__(self, parent, matchName, chemAtomList, chemAtomDict, propagateList, ccpCode, shifts, matchType = 'Resonance', matchInfoPopup = None, selectedIndex = 4, title = 'Select resonance atom match', helpUrl = 'AtomSelect.html', headerLines = None, modal = False):

    self.help_url = joinPath(getHelpUrlDir(),helpUrl)

    # Constructor doesn't do much except call body
    # The parent is self.parent (parent of the popup)
   
    self.chemAtomOrSets = None
    self.propagate = None
    
    self.matchName = matchName
    self.matchType = matchType
    self.matchInfoPopup = matchInfoPopup
    self.chemAtomList = chemAtomList
    self.chemAtomDict = chemAtomDict
    self.propagateList = propagateList
    self.ccpCode = ccpCode
    self.shifts = shifts
    self.guiParent = parent
    self.headerLines = headerLines
    
    self.selectedIndex = selectedIndex

    # modal = true means that it won't continue unless this one returns value
    TemporaryBasePopup.__init__(self, parent=parent, title=title, modal=modal, transient=True)
Exemplo n.º 11
0
    def fcImportAllData(self):

        # These files have to be correct, no preparsing necessary.
        self.fcImportFile('sequence', 'dyana',
                          joinPath(self.importDir, "1bc6.seq"))
        self.fcImportFile('distanceConstraints', 'dyana',
                          joinPath(self.importDir, "1bc6.restr"))
        self.fcImportFile('coordinates',
                          'pdb',
                          joinPath(self.importDir, "1bc6.pdb"),
                          addKeywords={'forceDefaultChainMapping': True})

        self.formatConversion.linkResonances(setSingleProchiral=True)

        # This should be modifiable...
        self.ccpnProject.saveModified()
Exemplo n.º 12
0
    def getEntryInfo(self, entry):

        file = joinPath(self.directory, entry)

        if os.path.islink(file):
            # plain arrow: u' \u2192 '
            entry = entry + u' \u21D2 ' + unicode(os.readlink(file), 'utf-8')
            size = None
            color = '#E0D0C0'

        elif os.path.isdir(file):
            if not self.isRootDirectory(entry):
                entry = entry + dirsep
            size = None
            color = '#C0D0C0'

        else:
            color = '#C0C0D0'

            if self.show_file:
                try:
                    size = str(os.path.getsize(file))
                except:
                    size = None
            else:
                size = None

        try:
            fileTime = self.fileTime(file)
        except:
            fileTime = ''

        return (entry, size, fileTime, color)
Exemplo n.º 13
0
def getAquaAtomInfo(chemCompCodes = {}):

  aquaRefDir = getDataPath('ccp', 'aqua')
  files = os.listdir(aquaRefDir)

  for file in files:
    if file[0:8] == 'AtomLIB-':
      format = file[8:]
      
      readAquaFormats(joinPath(aquaRefDir,file),format,chemCompCodes)
  
  for file in files:
    if file[-8:] == 'LIB-aqua':
      info = file[0:-8]
      readAquaDefs(joinPath(aquaRefDir,file),info,chemCompCodes)
  
  return chemCompCodes
Exemplo n.º 14
0
  def doubleCallback(self, entry, row, col):

    # TODO: need to worry about symbolic links leading you astray on path
    file = joinPath(self.directory, entry)
    if (self.show_file or not self.double_callback) and os.path.isdir(file):
      self.changeDir(file)
    elif self.double_callback:
      self.double_callback(file)
Exemplo n.º 15
0
class ImportFormatComponentPopup(GenericFormatPopup):
 
  help_url = joinPath(getHelpUrlDir(),'ImportFormatComponent.html')

  def setImportExportFlag(self):
  
    self.importExportFlag = 'import'
    self.titleText = "Project '%s': " % self.project.name + '%s %s %s' % (self.format,self.component,self.importExportFlag)
Exemplo n.º 16
0
    def getIntensityValue(self, phi, psi):

        intensities = self.intensityDict.get(self.aminoAcid)
        if not intensities:
            if self.aminoAcid:
                fileName = joinPath(self.bitmapDir,
                                    'log_%s.pgm' % self.aminoAcid.upper())
            else:
                fileName = joinPath(self.bitmapDir, 'log_ALL.pgm')

            self.readPGM(fileName)
            intensities = self.intensityDict[self.aminoAcid]

        i = int((phi + 180) / self.binSize)
        j = int((psi - 180) / -self.binSize)

        return intensities[i][j]
Exemplo n.º 17
0
    def setFileUpdates(self, fileUpdates=None, refresh=False, passwd=None):

        # Synchronise the server - This is the admin upload part

        if not fileUpdates:
            fileUpdates = self.fileUpdates

        if passwd is None:
            if self.parent.isGraphical:
                passwd = askPassword(
                    'Password Request',
                    'Enter password for %s@%s' % (self.uid, self.location))
            else:
                self.parent.warningMessage(
                    'Warning',
                    'Password must be specified when setting updates in non graphical mode'
                )

        if not passwd:
            return False

        # Clean server files
        self.deleteFile(passwd, '__temp_*')

        added = 0
        if self.fileUpdates:
            fileName = joinPath(self.parent.tempDir, self.dataFile)
            file = open(fileName, 'w')
            file.write('%s\n' % self.parent.version)
            for x in self.fileUpdates:
                if (not x.isNew) and refresh and (x in fileUpdates):
                    if not x.getIsUpToDate():
                        x.timestamp()
                        x.isNew = True

                data = fieldSep.join([
                    x.fileName, x.filePath, x.storedAs, x.language, x.date,
                    x.details,
                    str(x.priority)
                ])
                file.write('%s\n' % data)

                if x.isNew:
                    copyfile(x.installedFile, x.tempFile)
                    self.uploadFile(passwd, x.tempFile, x.storedAs)
                    added += 1

            file.close()

            self.uploadFile(passwd, fileName, self.dataFile)

        else:
            self.deleteFile(passwd, self.dataFile)

        self.parent.warningMessage('Notice',
                                   'Server Update of %d files' % added)

        return True
Exemplo n.º 18
0
class NamingSystemPopup(TemporaryBasePopup):

    help_url = joinPath(getHelpUrlDir(), 'NamingSystem.html')

    def __init__(self, parent, namingSysList=None, namingSysDict=None):

        # Constructor doesn't do much except call body
        # The parent is self.parent (parent of the popup)

        self.namingSys = None

        self.namingSysList = namingSysList
        self.namingSysDict = namingSysDict

        # modal = true means that it won't continue unless this one returns value
        TemporaryBasePopup.__init__(self,
                                    parent=parent,
                                    title='Choose namingSys',
                                    modal=False,
                                    transient=True)

    def body(self, master):

        #
        # Popup gui
        #

        # First row
        row = 0
        label = Label(master, text="Choose a naming system:")
        label.grid(row=row, column=0, sticky=Tkinter.W)

        row = row + 1
        label = Label(master, text="(% matches in brackets)")
        label.grid(row=row, column=0, sticky=Tkinter.W)

        row = row + 1
        self.menu = PulldownMenu(master, entries=self.namingSysList)
        self.menu.grid(row=row, column=0, sticky=Tkinter.EW)

        row = row + 1
        texts = ['OK']
        commands = [
            self.ok
        ]  # This calls 'ok' in BasePopup, this then calls 'apply' in here
        buttons = createDismissHelpButtonList(master,
                                              texts=texts,
                                              commands=commands,
                                              dismiss_text='Exit',
                                              help_url=self.help_url)
        buttons.grid(row=row, column=0)

    def apply(self):

        self.namingSysName = self.namingSysDict[self.menu.getSelected()]

        return True
Exemplo n.º 19
0
  def __init__(self, procpar_file, data_file=None, **kw):

    if not data_file:
      data_file = joinPath(os.path.dirname(procpar_file), 'datdir', 'phasefile')

    self.procpar_file = procpar_file
    self.data_file = data_file

    ExternalParams.__init__(self, **kw)
Exemplo n.º 20
0
    def topDir(self):

        if self.directory:
            isRoot = self.isRootDirectory
            dirName = self.directory
            while not isRoot(dirName):
                dirName = joinPath(dirName, os.pardir)

            self.changeDir(dirName)
Exemplo n.º 21
0
    def getFile(self, full_path=True):

        if self.show_file:
            file = self.file_entry.getEntry()
            if file and full_path:
                file = joinPath(self.directory, file)
        else:  # ignore full_path
            file = self.directory_entry.getEntry()

        return file
Exemplo n.º 22
0
    def cingProjectDownload(self, outputDir):

        #
        # Put in CCPN project as default. Always usea time-stamped directory name.
        #

        if not outputDir:
            outputDir = self.ccpnProject.findFirstRepository(
                name='userData').url.path
            outputDir = os.path.join(outputDir, 'cing',
                                     self.getFileTimeString())

        #
        # Make sure output dir exists
        #

        if not os.path.exists(outputDir):
            os.makedirs(outputDir)

        #
        # Get the CING project name - safer in case changed on server side
        #

        projectPage = self.cingRequest("ProjectName")

        pyDict = eval(projectPage)
        projectName = pyDict['Result']

        #
        # Now download the file - first wait a bit just in case
        #

        time.sleep(20)

        cingZipFile = "%s_CING_report.zip" % projectName
        cingZipFileHttp = os.path.join(self.cingDownload, self.userId,
                                       self.accessKey, cingZipFile)

        # Try to re-download if not found.
        outputData = None

        while (not outputData or outputData.count("Not Found")):

            time.sleep(20)
            outputData = getDataFromHttp(cingZipFileHttp)

        #
        # And write it out...
        #

        self.cingZipFileOut = joinPath(outputDir, cingZipFile)

        fout = open(self.cingZipFileOut, 'w')
        fout.write(outputData)
        fout.close()
Exemplo n.º 23
0
    def callHttpScript(self, passwd, script, data):

        auth = base64.encodestring(self.uid + ":" + passwd)[:-1]
        authheader = 'Basic %s' % auth
        uri = 'http://' + joinPath(self.location, 'cgi-bin', self.httpDir,
                                   script)
        req = urllib2.Request(uri)
        req.add_header("Authorization", authheader)
        req.add_data(data)
        uu = urllib2.urlopen(req)
        print uu.read()
Exemplo n.º 24
0
  def getFilterFiles(self, directory):

    filterFiles = set()
    for filter in self.fileType.filters:
      # have to use fullfilter rather than filter because cwd is not directory in general
      fullfilter = joinPath(directory, filter)
      filterFiles.update(glob.glob(fullfilter))

    # remove directory from file names

    n = len(directory)
    if directory[-1] != dirsep:
      n = n + 1

    filterFiles = set([x[n:] for x in filterFiles])

    # add in subdirectories
    filterFiles.update([x for x in os.listdir(directory) if os.path.isdir(joinPath(directory, x))])

    return list(filterFiles)
Exemplo n.º 25
0
    def uploadFile(self, passwd, localFile, serverFile):

        cc = open(localFile).read()
        ss = joinPath(self.basedir, serverFile)
        data = urllib.urlencode({'content': cc, 'file': ss})
        try:
            # 18 Aug 08: TEMP: TBD: remove Temp when Jenny password protects directory
            self.callHttpScript(passwd, 'uploadFileTemp', data)
        except Exception, e:
            self.parent.warningMessage('Server',
                                       'Server exception: %s' % str(e))
Exemplo n.º 26
0
  def decomposeMultipleFileText(self,text):

    files = []
    
    if text:
      textItems = text.split("\n")
      if len(textItems) == 2:
        (path,fileNameText) = textItems
        for fileName in fileNameText.split(', '):
          files.append(joinPath(path,fileName))  
    
    return files
Exemplo n.º 27
0
class TextOutputPopup(BasePopup):

    help_url = joinPath(getHelpUrlDir(), 'TextOutput.html')

    def __init__(self, parent, title='Text output'):

        BasePopup.__init__(self,
                           parent=parent,
                           title=title,
                           modal=False,
                           transient=False)

    def body(self, master):

        self.text = ScrolledText(master)
        self.text.pack(side=Tkinter.TOP, expand=Tkinter.YES, fill=Tkinter.BOTH)

        texts = ['Save text']
        commands = [self.saveText]
        buttons = createHelpButtonList(master,
                                       texts=texts,
                                       commands=commands,
                                       help_url=self.help_url)

        buttons.pack()

    def saveText(self):

        fileSelectPopup = FileSelectPopup(
            self,
            file_types=[
                FileType('Text', ['*.txt', '*.out', '*.text']),
                FileType('All', ['*'])
            ],
            title='Select text output save file')

        fileName = fileSelectPopup.getFile()

        if fileName:
            writeFile = 1
            if os.path.exists(fileName):
                if not showYesNo('Overwrite file',
                                 'Overwrite existing file %s?' % fileName):
                    writeFile = 0

            if writeFile:
                fout = open(fileName, 'w')
                fout.write(self.text.text_area.getText())
                fout.close()

    def apply(self):

        return True
Exemplo n.º 28
0
class ChemCompSelectionPopup(TemporaryBasePopup):

    help_url = joinPath(getHelpUrlDir(), 'ChemCompSelection.html')

    def __init__(self, parent, project, **keywds):

        self.project = project
        self.keywds = keywds

        origCode = self.keywds['origCode']
        del self.keywds['origCode']

        TemporaryBasePopup.__init__(
            self,
            parent=parent,
            title="Project '%s': " % project.name +
            "ChemComp selection for code '%s'" % origCode,
            modal=False,
            transient=False,
            width=200)

    def body(self, master):

        self.frame = ChemCompFrame(master, self.project, **self.keywds)
        self.frame.pack(side=Tkinter.TOP,
                        expand=Tkinter.YES,
                        fill=Tkinter.BOTH)

        texts = ['OK']
        commands = [self.ok]
        buttons = createDismissHelpButtonList(master,
                                              texts=texts,
                                              commands=commands,
                                              dismiss_text='Cancel',
                                              help_url=self.help_url)

        buttons.pack()

    def apply(self):

        if self.frame.getSelectedChemComp():

            return True

        else:

            showInfo(
                'No selection',
                'Please select a chemCompVar from the bottom half of the window, or press Cancel to quit.'
            )

            return False
Exemplo n.º 29
0
def newProject(projectName, path=None, removeExisting=False, showYesNo=None):
    """
  Create, and return, a new project using a specified path (directory).
  If path is not specified it takes the current working directory.
  The path can be either absolute or relative.
  The 'userData' repository is pointed to the path.
  The 'backup' repository is pointed to the path + '_backup'.
  If either of these paths already exist (either as files or as directories):
    If removeExisting:
      Delete the path
    Else if showYesNo:
      Ask the user if it is ok to delete the path
      If yes, delete.  If no return None.
    Else:
      Raise an IOError
  """

    # relies on knowing that repositories to move have these names, and these values for path suffix
    repositoryNameMap = {'userData': '', 'backup': '_backup'}

    if not path:
        path = os.getcwd()

    for name in repositoryNameMap.keys():
        fullPath = joinPath(path, projectName) + repositoryNameMap[name]
        answer = checkRemoveIfExists(fullPath, removeExisting, showYesNo)
        if answer is None:
            return None

    project = Implementation.MemopsRoot(name=projectName)

    for name in repositoryNameMap.keys():
        fullPath = normalisePath(joinPath(path, projectName) +
                                 repositoryNameMap[name],
                                 makeAbsolute=True)
        repository = project.findFirstRepository(name=name)
        repository.url = Implementation.Url(path=fullPath)

    return project
Exemplo n.º 30
0
    def unpackRelease(self):

        os.chdir('%s/%s' % (self.baseDir, self.releaseDir))

        gzippedTarFile = self.releaseFile

        cmds = []
        if gzippedTarFile.endswith('.tar.gz'):
            tarFile = gzippedTarFile[:-3]
            sourceEnvFile = joinPath(self.baseDir, self.installDir, 'c',
                                     environmentFile)
            destEnvFile = joinPath(self.baseDir, self.releaseDir,
                                   self.ccpnmrTopDir, self.ccpnmrCodeDir, 'c',
                                   environmentFile)
            cmds.append('gunzip %s' % gzippedTarFile)
            cmds.append('tar xvf %s' % tarFile)
            cmds.append('gzip %s' % tarFile)
            cmds.append('cp %s %s' % (sourceEnvFile, destEnvFile))
        else:
            cmds.append('tar xvfz %s' % gzippedTarFile)

        self.runCmds(cmds)