tools — biskit 3.0.0a1 documentation

# tools

general purpose utility methods.

Functions Overview

`Dump` |
`Load` |
`absbinary` | Absolute path of binary.
`absfile` | Get absolute file path:: - expand ~ to user home, change - expand ../../ to absolute path - resolve links - add working directory to unbound files (‘ab.txt’->’/home/raik/ab.txt’)
`backup` | Create backup of file if it already exists.
`binExists` | Check if binary with file name f exists.
`clipStr` | Shorten string from end and replace the last characters with suffix:: clipStr( str, length ) -> str, with len( str ) <= length
`cmdDict` | Convenience implementation of `get_cmdDict`.
`colorSpectrum` | Creates a list of ‘nColors’ colors for biggles starting at ‘firstColor’ ending at ‘lastColor’ Examples:: free spectrum red FF0000 to green 00FF00 bound spectrum cyan 00FFFF to magenta FF00FF
`dataRoot` | Root of Biskit data directory (formerly ‘biskit/Biskit/data’).
`dateSortString` |
return: | YYYY/MM/DD:hh:mm.ss.ms :rtype:
`dateString` |
return: | DD/MM/YYYY :rtype: str
`dictAdd` | Add value to dic, create list, if dic has already value in key.
`dump` | Dump this:: dump(this, filename, gzip = 0) Supports also ‘~’ or ‘~user’.
`ensure` | Check type of a variable
`errWrite` | print s to standard error.
`errWriteln` | print s to standard error with line feed.
`file2dic` | Construct dictionary from file with key - value pairs (one per line).
`fileLength` | Count number of lines in a file.
`flushPrint` | print s without line break and flush standard out.
`get_cmdDict` | Parse commandline options into dictionary of type C{ {<option> : <value>} } Options are recognised by a leading ‘-‘.
`getframeinfo` | Get information about a frame or traceback object.
`gzopen` | Open a normal or a gzipped file.
`hex2int` | Convert hex-code string into float number.
`hex2rgb` | convert 8 bit hex rgb color into rgb color :: ‘FF00FF’ -> [ 1.0, 0.0, 1.0, ]
`hexColors` | Creates a list of ‘nColors’ colors for PyMol starting at ‘firstColor’ ending at ‘lastColor’ Examples:: free spectrum red FF0000 to green 00FF00 bound spectrum cyan 00FFFF to magenta FF00FF
`homefile` | Relativize a file name to ~ or, if it is in another user’s home, to ~otheruser or, if it is in nobody’s home, to / .
`info` | :: info( item, short=1) -> Print useful information about item.
`isBinary` | Check if file is a binary.
`lastError` | Collect type and line of last exception.
`lastErrorTrace` |
`load` | Load dumped object from file.
`localtime` | tm_sec,tm_wday,tm_yday,tm_isdst)
`packageRoot` |
return: | absolute folder of the biskit python package.
`platformFolder` | Get a platform-specific subfolder of f for platform-dependent imports.
`profile` | Profile the given code fragment and report time-consuming method calls.
`projectRoot` | Root of biskit project.
`relpath` | Translate p2 into a path relative to p1.
`rgb2hex` | convert rgb color into 8 bit hex rgb color:: [ 1.0, 0.0, 1.0, ] -> ‘FF00FF’
`sortString` | Sort the letters of a string:: sortString( str ) -> str with sorted letters
`splithome` | Split path into home directory and remaining path.
`string2Fname` | Remove forbidden character from string so that it can be used as a filename.
`stripFilename` | Return filename without path and without ending.
`stripSuffix` | Return file name without ending.
`tempDir` | Get folder for temporary files - either from environment settings or ‘/tmp’
`testRoot` | Root of Biskit test directory.
`toInt` | Convert to intereg if possible:: toInt(o) -> int, int(o) or default if o is impossible to convert.
`toIntArray` | Convert single value or list of values to numpy array of int.
`toIntList` | Convert single value or list of values into list of integers.
`toList` | Make a list:: toList(o) -> [o], or o, if o is already a list
`toStr` | Make a string from a list or interger.
`tryImport` | Try to import a class from a module.
`tryImportModule` | Try to import a module.
`tryRemove` | Remove file or folder:: remove(f [,verbose=0, tree=0]), remove if possible, otherwise do nothing

Classes Overview

`PseudoClass` | Empty class that raises an ImportError upon creation.

Exceptions Defined in this Module

`PickleError` |
`ToolsError` |

## tools Module Details

exception `biskit.tools.` `ToolsError`

exception `biskit.tools.` `PickleError`

`biskit.tools.` `errWriteln`(s)

  print s to standard error with line feed.

  Parameters: | s (str) – string

`biskit.tools.` `errWrite`(s)

  print s to standard error.

  Parameters: | s (str) – string

`biskit.tools.` `flushPrint`(s)

  print s without line break and flush standard out.

  Parameters: | s (str) – string

`biskit.tools.` `lastError`()

  Collect type and line of last exception.

  Returns: | ‘<ExceptionType> in line <lineNumber>:<Exception arguments>’
  Return type: | String

`biskit.tools.` `dictAdd`(dic, key, value, forceList=False)

  Add value to dic, create list, if dic has already value in key.

  Parameters: | key (str) – dictionary key value (any) – value

`biskit.tools.` `absfile`(filename, resolveLinks=1)
  Get absolute file path::
    - expand ~ to user home, change
    - expand ../../ to absolute path
    - resolve links
    - add working directory to unbound files (‘ab.txt’->’/home/raik/ab.txt’)

  Parameters: | filename (str) – name of file resolveLinks (1|0) – eliminate any symbolic links (default: 1)
  Returns: | absolute path or filename
  Return type: | string
  Raises: | ToolsError – if a ~user part does not translate to an existing path

`biskit.tools.` `homefile`(filename, otherUser=1, ownCopy=1)

  Relativize a file name to ~ or, if it is in another user’s home, to ~otheruser or, if it is in nobody’s home, to / .

  `splithome()` is used to also guess home directories of other users.

  Parameters: | filename (str) – name of file otherUser (1|0) – look also in other user’s home directories (default 1) ownCopy (1|0) – replace alien path by path into own home directory if possible, e.g. ~other/data/x is replaced by ~/data/x if there is such a file. (default 1) Careful!
  Returns: | path or filename
  Return type: | str

`biskit.tools.` `splithome`(filename)

  Split path into home directory and remaining path. Valid home directories are folders belonging to the same folder as the current user’s home. I.e. the method tries also to guess home directories of other users.

  Parameters: | filename (str) – name of file
  Returns: | home folder of some user, remaining path relative to home
  Return type: | (str, str)

`biskit.tools.` `relpath`(p1, p2)

  Translate p2 into a path relative to p1.

  Parameters: | p1 (str) – base path p2 (str) – target path
  Returns: | relative path p1 -> p2
  Return type: | str

`biskit.tools.` `stripSuffix`(filename)

  Return file name without ending.

  Parameters: | filename (str) – name of file
  Returns: | filename or path without suffix
  Return type: | str

`biskit.tools.` `stripFilename`(filename)

  Return filename without path and without ending.

  Parameters: | filename (str) – name of file
  Returns: | base filename
  Return type: | str

`biskit.tools.` `fileLength`(filename)

  Count number of lines in a file.

  Parameters: | filename (str) – name of file
  Returns: | number of lines
  Return type: | int

`biskit.tools.` `tempDir`()

  Get folder for temporary files - either from environment settings or ‘/tmp’

  Returns: | directort for temporary files
  Return type: | str

`biskit.tools.` `file2dic`(filename)

  Construct dictionary from file with key - value pairs (one per line).

  Parameters: | filename (str) – name of file
  Raises: | ToolsError – if file can’t be parsed into dictionary IOError – if file can’t be opened

`biskit.tools.` `get_cmdDict`(lst_cmd, dic_default)

  Parse commandline options into dictionary of type C{ {<option> : <value>} } Options are recognised by a leading ‘-‘. Error handling should be improved.

  Option C{ -x |file_name| } is interpreted as file with additional options. The key value pairs in lst_cmd replace key value pairs in the -x file and in dic_default.

  Parameters: | lst_cmd ([str]) – list with the command line options:: e.g. [‘-pdb’, ‘in1.pdb’, ‘in2.pdb’, ‘-o’, ‘out.dat’] dic_default ({str : str}) – dictionary with default options:: e.g. {‘psf’:’in.psf’}
  Returns: | command dictionary:: ala {‘pdb’:[‘in1.pdb’, ‘in2.pdb’], ‘psf’:’in.psf’, ‘o’:’out.dat’}
  Return type: | {<option> : <value>}

`biskit.tools.` `cmdDict`(defaultDic={})

  Convenience implementation of `get_cmdDict`. Take command line options from sys.argv[1:] and convert them into dictionary. Example:

      '-o out.dat -in 1.pdb 2.pdb 3.pdb -d' will be converted to
      {'o':'out.dat', 'in': ['1.pdb', '2.pdb', '3.pdb'], 'd':'' }

  Option C{ -x |file_name| } is interpreted as file with additional options.

  Parameters: | defaultDic (dic) – dic with default values.
  Returns: | command dictionary
  Return type: | dic

`biskit.tools.` `dump`(this, filename, gzip=0, mode='wb')
  Dump this::
    dump(this, filename, gzip = 0) Supports also ‘~’ or ‘~user’.

  Note: Peter Schmidtke : gzip fixed, works now

  Written by Wolfgang Rieping.

  Parameters: | this (any) – object to dump filename (str) – name of file gzip (1|0) – gzip dumped object (default 0) mode (str) – file handle mode (default w)

`biskit.tools.` `load`(filename, gzip=0, encoding='ASCII')

  Load dumped object from file.

  Note: Peter Schmidtke : gzip fixed, works now

  Written by Wolfgang Rieping.

  Parameters: | filename (str) – name of file gzip (1|0) – unzip dumped object (default 0) encoding (str) – optional encoding for pickle.load [‘ASCII’]
  Returns: | loaded object
  Return type: | any

  :raise cPickle.UnpicklingError, if the pickle format is not recognized

`biskit.tools.` `packageRoot`()

  Returns: | absolute folder of the biskit python package.
  Return type: | str

`biskit.tools.` `projectRoot`()

  Root of biskit project. That’s the folder containing the biskit python package (the parent folder of `packageRoot`).

  Returns: | absolute path of the root (parent) folder of current project:: i.e. ‘/home/raik/py/biskitproject’
  Return type: | string

`biskit.tools.` `dataRoot`()

  Root of Biskit data directory (formerly ‘biskit/Biskit/data’). :return: absolute path :rtype: string

`biskit.tools.` `testRoot`(subfolder='')

  Root of Biskit test directory.

  Parameters: | subfolder – str, optional sub-folder of test data folder
  Returns: | absolute path
  Return type: | string

`biskit.tools.` `isBinary`(f)

  Check if file is a binary.

  Parameters: | f (str) – path to existing file
  Returns: | condition
  Return type: | 1|0
  Raises: | OSError – if file doesn’t exist

`biskit.tools.` `binExists`(f)

  Check if binary with file name f exists.

  Parameters: | f (str) – binary file name
  Returns: | True if binary file f is found in PATH and is executable
  Return type: | 1|0

`biskit.tools.` `absbinary`(f)

  Absolute path of binary.

  Parameters: | f (str) – binary file name
  Returns: | full path to existing binary
  Return type: | str
  Raises: | IOError – if an executable binary is not found in PATH

`biskit.tools.` `platformFolder`(f)

  Get a platform-specific subfolder of f for platform-dependent imports.

  Parameters: | f (str) – parent folder
  Returns: | path
  Return type: | str

`biskit.tools.` `sortString`(s)
  Sort the letters of a string::
    sortString( str ) -> str with sorted letters

  Parameters: | s (str) – string to be sorted
  Returns: | sorted string
  Return type: | str

`biskit.tools.` `string2Fname`(s)

  Remove forbidden character from string so that it can be used as a filename.

  Parameters: | s (str) – string
  Returns: | cleaned string
  Return type: | str

`biskit.tools.` `toIntList`(o)

  Convert single value or list of values into list of integers.

  Parameters: | o (int or [int]) – value or list
  Returns: | list of integer
  Return type: | [int]

`biskit.tools.` `toIntArray`(o)

  Convert single value or list of values to numpy array of int.

  Parameters: | o (int or [int]) – value or list
  Returns: | array of integer
  Return type: | N0.array(‘i’)

`biskit.tools.` `toList`(o)
  Make a list::
    toList(o) -> [o], or o, if o is already a list

  Parameters: | o (any or [any]) – value(s)
  Returns: | list
  Return type: | [any]

`biskit.tools.` `toStr`(o)

  Make a string from a list or interger. Stripping of any flanking witespaces.

  Parameters: | o (any or [any]) – value(s)
  Returns: | list
  Return type: | [any]

`biskit.tools.` `toInt`(o, default=None)
  Convert to intereg if possible::
    toInt(o) -> int, int(o) or default if o is impossible to convert.

  Parameters: | o (any) – value default (any) – value to return if conversion is impossible (default: None)
  Returns: | integer OR None
  Return type: | int OR None

`biskit.tools.` `hex2int`(shex)

  Convert hex-code string into float number. :param s: hex-code, e.g. ‘FF0B99’ :type s: str :return: float :rtype: float

`biskit.tools.` `colorSpectrum`(nColors, firstColor='FF0000', lastColor='FF00FF')

  Creates a list of ‘nColors’ colors for biggles starting at ‘firstColor’ ending at ‘lastColor’ Examples:

      free spectrum red FF0000 to green 00FF00
      bound spectrum cyan 00FFFF to magenta FF00FF

  Parameters: | nColors (int) – number of colors to create firstColor (str) – first color in hex format (default: FF0000) lastColor (str) – last color in hex format (default: FF00FF)
  Returns: | list of colors
  Return type: | [int]

`biskit.tools.` `hexColors`(nColors, firstColor='FF0000', lastColor='FF00FF')

  Creates a list of ‘nColors’ colors for PyMol starting at ‘firstColor’ ending at ‘lastColor’ Examples:

      free spectrum red FF0000 to green 00FF00
      bound spectrum cyan 00FFFF to magenta FF00FF

  Parameters: | nColors (int) – number of colors to create firstColor (str) – first color in hex format (default: FF0000) lastColor (str) – last color in hex format (default: FF00FF)
  Returns: | list of hex colors
  Return type: | [ str ]

`biskit.tools.` `rgb2hex`(rgbColor)
  convert rgb color into 8 bit hex rgb color::
    [ 1.0, 0.0, 1.0, ] -> ‘FF00FF’

  Parameters: | rgbColor – RGB-color e.g. [ 1.0, 0.0, 1.0, ]

  :type rgbColor : [float]

  Returns: | hex colors
  Return type: | str

`biskit.tools.` `hex2rgb`(hexColor, str=0)
  convert 8 bit hex rgb color into rgb color ::
    ‘FF00FF’ -> [ 1.0, 0.0, 1.0, ]

  Parameters: | hexColor (str) – HEX-color e.g. ‘FF00FF’ str (1|0) – return rgb colors as a tring (i.e for PyMol)
  Returns: | rgb colors
  Return type: | [float]

`biskit.tools.` `dateString`()

  Returns: | DD/MM/YYYY
  Return type: | str

`biskit.tools.` `dateSortString`()

  Returns: | YYYY/MM/DD:hh:mm.ss.ms
  Return type: |

`biskit.tools.` `tryRemove`(f, verbose=0, tree=0, wildcard=0)
  Remove file or folder::
    remove(f [,verbose=0, tree=0]), remove if possible, otherwise do nothing

  Parameters: | f (str) – file path verbose (0|1) – report failure (default 0) tree (0|1) – remove whole folder (default 0) wildcard (0|1) – filename contains wildcards (default 0)
  Returns: | 1 if file was removed
  Return type: | 1|0

`biskit.tools.` `backup`(fname, suffix='~')

  Create backup of file if it already exists. :param fname: file name :type fname: str :param suffix: suffix to add to backup file name [‘~’] :type suffix: str

  Returns: | True if backup was created, False otherwise
  Return type: | bool

`biskit.tools.` `ensure`(v, t, allowed=[], forbidden=[])

  Check type of a variable

  Parameters: | v (variable) – variable to test t (str) – required type allowed ([str]) – list of additional values allowed for v {default: []}
  Raises: | TypeError – if invalid

`biskit.tools.` `clipStr`(s, length, suffix='..', expandtabs=1)
  Shorten string from end and replace the last characters with suffix::
    clipStr( str, length ) -> str, with len( str ) <= length

  Parameters: | s (str) – original string length (int) – desired length suffix (str) – suffix (default: ..)
  Returns: | shortend string
  Return type: | str

`biskit.tools.` `info`(item, short=1)
  ::
    info( item, short=1) -> Print useful information about item.

  Parameters: | item (item) – query item short (1|0) – short version (default: 1)

class `biskit.tools.` `PseudoClass`

  Empty class that raises an ImportError upon creation.

`biskit.tools.` `tryImport`(module, cls, old_as=None, namespace=None)

  Try to import a class from a module. If that fails, ‘import’ a default class of the same name that raises an exception when used.

  Parameters: | module (str) – name of the module

  :param cls : name of the class :type cls : str :param namespace: namespace for the import [default: globals() ] :type namespace: dict

  Returns: | True if import succeeded, False otherwise
  Return type: | bool

`biskit.tools.` `tryImportModule`(module, old_as=None, namespace=None)

  Try to import a module. If that fails, ‘import’ a dummy module of the same name.

  NOTE: as of python 3, the namespace returned by globals() cannot reach out of the tools module – this method thus always needs to be called like this:

      >>> tryImportModule( 'numpy', namespace=globals() )

  Parameters: | module (str) – name of the module namespace (dict) – namespace for the import [default: globals() ]
  Returns: | True if import succeeded, False otherwise
  Return type: | bool

`biskit.tools.` `gzopen`(fname, mode='rt')

  Open a normal or a gzipped file. :param fname: file name (can contain ~, .. etc.) :type fname: str :param mode: read/write mode [‘r’] :type mode: str

  Returns: | file handle
  Return type: | file or GZipFile

`biskit.tools.` `profile`(s)

  Profile the given code fragment and report time-consuming method calls. :param s: python code fragment, example: ‘m = PDBModel(“3tgi”)’ :type s: str