Package Biskit :: Module tools
[hide private]
[frames] | no frames]

Module tools

source code

simply - everyday tools

Classes [hide private]
  ToolsError
  PickleError
  PseudoClass
Empty class that raises an ImportError upon creation.
  Test
Test class

Functions [hide private]
  errWriteln(s)
print s to standard error with line feed.
  errWrite(s)
print s to standard error.
  flushPrint(s)
print s without line break and flush standard out.
String lastError()
Collect type and line of last exception.
  lastErrorTrace(limit=None)
  dictAdd(dic, key, value)
Add value to dic, create list, if dic has already value in key.
string absfile(filename, resolveLinks=1)
Get absolute file path:
str 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 / .
(str, str) splithome(filename)
Split path into home directory and remaining path.
str stripSuffix(filename)
Return file name without ending.
str stripFilename(filename)
Return filename without path and without ending.
int fileLength(filename)
Count number of lines in a file.
str tempDir()
Get folder for temporary files - either from environment settings or '/tmp'
  file2dic(filename)
Construct dictionary from file with key - value pairs (one per line).
{<option> : <value>} get_cmdDict(lst_cmd, dic_default)
Parse commandline options into dictionary of type {<option> : <value>} Options are recognised by a leading '-'.
dic cmdDict(defaultDic={})
Convenience implementation of get_cmdDict.
  Dump(this, filename, gzip=0, mode='w')
Dump this:

any

@raise cPickle.UnpicklingError, if the pickle format is not recognized
Load(filename, gzip=0)
Load dumped object from file.
(str, function) getOnDemand(attr, dumpIt=1)
Return attr either unpickled, freshly calculated or unchanged.
string projectRoot()
Root of biskit project.
string testRoot()
Root of Biskit test directory.
1|0 isBinary(f)
Check if file is a binary.
1|0 binExists(f)
Check if binary with file name f exists.
str absbinary(f)
Absolute path of binary.
str platformFolder(f)
Get a platform-specific subfolder of f for platform-dependent imports.
str sortString(s)
Sort the letters of a string:
str string2Fname(s)
Remove forbidden character from string so that it can be used as a filename.
[int] toIntList(o)
Convert single value or list of values into list of integers.
Numeric.array('i') toIntArray(o)
Convert single value or list of values to Numeric array of int.
[any] toList(o)
Make a list:
[any] toStr(o)
Make a string from a list or interger.
int OR None toInt(o, default=None)
Convert to intereg if possible:
[int] colorSpectrum(nColors, firstColor='FF0000', lastColor='FF00FF')
Creates a list of 'nColors' colors for biggles starting at 'firstColor' ending at 'lastColor' Examples:
[ str ] hexColors(nColors, firstColor='FF0000', lastColor='FF00FF')
Creates a list of 'nColors' colors for PyMol starting at 'firstColor' ending at 'lastColor' Examples:
str rgb2hex(rgbColor)
convert rgb color into 8 bit hex rgb color:
[float] hex2rgb(hexColor, str=0)
convert 8 bit hex rgb color into rgb color :
str dateString()
Returns DD/MM/YYYY
  dateSortString()
Returns YYYY/MM/DD:hh:mm.ss.ms
1|0 tryRemove(f, verbose=0, tree=0, wildcard=0)
Remove file or folder:
bool backup(fname, suffix='~')
Create backup of file if it already exists.
  ensure(v, t, allowed=[], forbidden=[])
Check type of a variable
str clipStr(s, length, suffix='..', expandtabs=1)
Shorten string from end and replace the last characters with suffix:
  info(item, short=1)
:
bool tryImport(module, cls, as=None, namespace=None)
Try to import a class from a module.
bool tryImportModule(module, as=None, namespace=None)
Try to import a class from a module.

Variables [hide private]
  test = Test()

Function Details [hide private]

errWriteln(s)

source code 

print s to standard error with line feed.
Parameters:
  • s (str) - string

errWrite(s)

source code 

print s to standard error.
Parameters:
  • s (str) - string

flushPrint(s)

source code 

print s without line break and flush standard out.
Parameters:
  • s (str) - string

lastError()

source code 

Collect type and line of last exception.
Returns: String
'<ExceptionType> in line <lineNumber>:<Exception arguments>'

lastErrorTrace(limit=None)

source code 

dictAdd(dic, key, value)

source code 

Add value to dic, create list, if dic has already value in key.
Parameters:
  • key (str) - dictionary key
  • value (any) - value

absfile(filename, resolveLinks=1)

source code 

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: string
absolute path or filename
Raises:
  • ToolsError - if a ~user part does not translate to an existing path

homefile(filename, otherUser=1, ownCopy=1)

source code 

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: str
path or filename

splithome(filename)

source code 

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: (str, str)
home folder of some user, remaining path relative to home

stripSuffix(filename)

source code 

Return file name without ending.
Parameters:
  • filename (str) - name of file
Returns: str
filename or path without suffix

stripFilename(filename)

source code 

Return filename without path and without ending.
Parameters:
  • filename (str) - name of file
Returns: str
base filename

fileLength(filename)

source code 

Count number of lines in a file.
Parameters:
  • filename (str) - name of file
Returns: int
number of lines

tempDir()

source code 

Get folder for temporary files - either from environment settings or '/tmp'
Returns: str
directort for temporary files

file2dic(filename)

source code 

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

get_cmdDict(lst_cmd, dic_default)

source code 

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

Option -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: {<option> : <value>}
command dictionary:
        ala {'pdb':['in1.pdb', 'in2.pdb'], 'psf':'in.psf', 'o':'out.dat'}

cmdDict(defaultDic={})

source code 

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 -x |file_name| is interpreted as file with additional options.
Parameters:
  • defaultDic (dic) - dic with default values.
Returns: dic
command dictionary

Dump(this, filename, gzip=0, mode='w')

source code 

Dump this:
 Dump(this, filename, gzip = 0)
 Supports also '~' or '~user'.
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)

Author: Wolfgang Rieping @note gzip currently doesn't work.

Load(filename, gzip=0)

source code 

Load dumped object from file.
Parameters:
  • filename (str) - name of file
  • gzip (1|0) - unzip dumped object (default 0)
Returns:

any

@raise cPickle.UnpicklingError, if the pickle format is not recognized
loaded object

Author: Wolfgang Rieping

getOnDemand(attr, dumpIt=1)

source code 

Return attr either unpickled, freshly calculated or unchanged. If attr is no tuple or anything else goes wrong it is returned unchanged
Parameters:
  • attr ((str, function)) - tuple of string and function:
                attr[0] - name of existing or non-existing file or ''
                attr[1] - function to get result if it can't be unpickled
    
  • dumpIt (0|1) - try pickling return value to attr[0](if valid file) (default 1)
Returns: (str, function)
attr (unchanged or object unpickeled from file)

projectRoot()

source code 

Root of biskit project.
Returns: string
absolute path of the root of current project:
        i.e. '/home/Bis/raik/biskit'

testRoot()

source code 

Root of Biskit test directory.
Returns: string
absolute path

isBinary(f)

source code 

Check if file is a binary.
Parameters:
  • f (str) - path to existing file
Returns: 1|0
condition
Raises:
  • OSError - if file doesn't exist

binExists(f)

source code 

Check if binary with file name f exists.
Parameters:
  • f (str) - binary file name
Returns: 1|0
True if binary file f is found in PATH and is executable

absbinary(f)

source code 

Absolute path of binary.
Parameters:
  • f (str) - binary file name
Returns: str
full path to existing binary
Raises:
  • IOError - if an executable binary is not found in PATH

platformFolder(f)

source code 

Get a platform-specific subfolder of f for platform-dependent imports.
Parameters:
  • f (str) - parent folder
Returns: str
path

sortString(s)

source code 

Sort the letters of a string:
 sortString( str ) -> str with sorted letters
Parameters:
  • s (str) - string to be sorted
Returns: str
sorted string

string2Fname(s)

source code 

Remove forbidden character from string so that it can be used as a filename.
Parameters:
  • s (str) - string
Returns: str
cleaned string

toIntList(o)

source code 

Convert single value or list of values into list of integers.
Parameters:
  • o (int or [int]) - value or list
Returns: [int]
list of integer

toIntArray(o)

source code 

Convert single value or list of values to Numeric array of int.
Parameters:
  • o (int or [int]) - value or list
Returns: Numeric.array('i')
array of integer

toList(o)

source code 

Make a list:
 toList(o) -> [o], or o,  if o is already a list
Parameters:
  • o (any or [any]) - value(s)
Returns: [any]
list

toStr(o)

source code 

Make a string from a list or interger. Stripping of any flanking witespaces.
Parameters:
  • o (any or [any]) - value(s)
Returns: [any]
list

toInt(o, default=None)

source code 

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: int OR None
integer OR None

colorSpectrum(nColors, firstColor='FF0000', lastColor='FF00FF')

source code 

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: [int]
list of colors

hexColors(nColors, firstColor='FF0000', lastColor='FF00FF')

source code 

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: [ str ]
list of hex colors

rgb2hex(rgbColor)

source code 

convert rgb color into 8 bit hex rgb color:
 [ 1.0, 0.0, 1.0, ] -> 'FF00FF'
Parameters:
  • rgbColor ([float]) - RGB-color e.g. [ 1.0, 0.0, 1.0, ]
Returns: str
hex colors

hex2rgb(hexColor, str=0)

source code 

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: [float]
rgb colors

dateString()

source code 
Returns: str
DD/MM/YYYY

dateSortString()

source code 
Returns:
YYYY/MM/DD:hh:mm.ss.ms

tryRemove(f, verbose=0, tree=0, wildcard=0)

source code 

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|0
1 if file was removed

backup(fname, suffix='~')

source code 

Create backup of file if it already exists.
Parameters:
  • fname (str) - file name
  • suffix (str) - suffix to add to backup file name ['~']
Returns: bool
True if backup was created, False otherwise

ensure(v, t, allowed=[], forbidden=[])

source code 

Check type of a variable
Parameters:
  • v (variable) - variable to test
  • t (str) - required type
  • allowed ([str]) - {default: []}
Raises:
  • TypeError - if invalid

clipStr(s, length, suffix='..', expandtabs=1)

source code 

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: str
shortend string

info(item, short=1)

source code 

:
 info( item, short=1) -> Print useful information about item.
Parameters:
  • item (item) - query item
  • short (1|0) - short version (default: 1)

tryImport(module, cls, as=None, namespace=None)

source code 

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
  • cls (str) - name of the class
  • namespace (dict) - namespace for the import [default: globals() ]
Returns: bool
True if import succeeded, False otherwise

tryImportModule(module, as=None, namespace=None)

source code 

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
  • namespace (dict) - namespace for the import [default: globals() ]
Returns: bool
True if import succeeded, False otherwise

Variables Details [hide private]

test

Value:
Test()