Commits

James Taylor  committed 58c08d7

Forgot the cookbook package. Fixed bitset.pyx (still in progress) so that it builds.

  • Participants
  • Parent commits 320555a

Comments (0)

Files changed (7)

File bx/bitset.pyx

     cdef int find_next_clear( self, int start ):
         return bitFindClear( self.bits, start, self.bitCount )
 
-    cdef and( self, BitSet other ):
+    cdef iand( self, BitSet other ):
         bitAnd( self.bits, other.bits, self.bitCount )
         
-    cdef or( self, BitSet other ): 
+    cdef ior( self, BitSet other ): 
         bitOr( self.bits, other.bits, self.bitCount )
 
     cdef bitXor( self, BitSet other ): 
         bitXor( self.bits, other.bits, self.bitCount )
 
-    cdef not( self ):
+    cdef invert( self ):
         bitNot( self.bits, self.bitCount)
 
     ## ---- Python "Operator Overloading" ----
         return self.get( index )
 
     cdef __iand__( self, BitSet other ):
-        self.and( other )
+        self.iand( other )
 
     cdef __ior__( self, BitSet other ):
-        self.or( other )
+        self.ior( other )
 
     cdef __invert__( self ):
-        self.bitNot
+        self.invert()
         
         
 

File cookbook/__init__.py

+seq_types = type( () ), type( [] )
+
+def flatten( *args ):
+    for arg in args:
+        if type( arg ) in seq_types:
+            for elem in arg:
+                for f in flatten( elem ): 
+                    yield f
+        else:
+            yield arg
+
+def cross_lists(*sets):
+    """Return the cross product of the arguments"""
+    wheels = map(iter, sets) 
+    digits = [it.next() for it in wheels]
+    while True:
+        yield digits[:]
+        for i in range(len(digits)-1, -1, -1):
+            try:
+                digits[i] = wheels[i].next()
+                break
+            except StopIteration:
+                wheels[i] = iter(sets[i])
+                digits[i] = wheels[i].next()
+        else:
+            break
+
+# Cached / memoized methods
+
+import types
+
+def cachedmethod(function):
+    return types.MethodType(Memoize(function), None)
+
+
+class Memoize:
+    def __init__(self,function):
+        self._cache = {}
+        self._callable = function
+            
+    def __call__(self, *args, **kwds):
+        cache = self._cache
+        key = self._getKey(*args,**kwds)
+        try: return cache[key]
+        except KeyError:
+            cachedValue = cache[key] = self._callable(*args,**kwds)
+            return cachedValue
+    
+    def _getKey(self,*args,**kwds):
+        return kwds and (args, ImmutableDict(kwds)) or args    
+
+
+class ImmutableDict(dict):
+    '''A hashable dict.'''
+
+    def __init__(self,*args,**kwds):
+        dict.__init__(self,*args,**kwds)
+    def __setitem__(self,key,value):
+        raise NotImplementedError, "dict is immutable"
+    def __delitem__(self,key):
+        raise NotImplementedError, "dict is immutable"
+    def clear(self):
+        raise NotImplementedError, "dict is immutable"
+    def setdefault(self,k,default=None):
+        raise NotImplementedError, "dict is immutable"
+    def popitem(self):
+        raise NotImplementedError, "dict is immutable"
+    def update(self,other):
+        raise NotImplementedError, "dict is immutable"
+    def __hash__(self):
+        return hash(tuple(self.iteritems()))

File cookbook/attribute.py

+""" attribute.py
+Provides functions for creating simple properties.
+
+If, inside a class definition, you write:
+
+    attribute(foo=1, bar=2)
+    
+simple properties named 'foo' and 'bar' are created for this class.
+Also, private instance variables '__foo' and '__bar' will be added 
+to instances of this class.
+
+USEAGE:
+
+# assumes attribute.py is on path 
+from attribute import *
+
+class MyClass(object):
+    readable(foo=1, bar=2) # or, attribute('r', foo=1, bar=2)
+    writable(fro=3, boz=4) # or, attribute('w', fro=3, boz=4)
+    attribute(baz=5)
+
+This is equivalent to the following:
+
+class MyClass(object):
+    def __init__(self): 
+        self.__foo = 1
+        self.__bar = 2
+        self.__fro = 3
+        self.__boz = 4
+        self.__baz = 5
+
+    def get_foo(self): 
+        return self.__foo
+    def get_bar(self): 
+        return self.__bar
+    def set_fro(self, value): 
+        self.__fro = value
+    def set_boz(self, value): 
+        self.__boz = value
+    def get_baz(self):
+        return self.__baz
+    def set_baz(self, value):
+        self.__baz = value
+    def del_baz(self):
+        del self.__baz
+
+    foo = property(fget=get_foo, doc="foo")
+    bar = property(fget=get_bar, doc="bar")
+    fro = property(fset=set_fro, doc="fro")
+    boz = property(fset=set_boz, doc="boz")
+    baz = property(fget=get_baz, fset=set_baz, fdel=del_baz, doc="baz")
+"""
+
+__all__ = ['attribute', 'readable', 'writable']
+__version__ = '3.0'
+__author__ = 'Sean Ross'
+__credits__ = ['Guido van Rossum', 'Garth Kidd']
+__created__ = '10/21/02'
+
+import sys
+
+def mangle(classname, attrname):
+    """mangles name according to python name-mangling 
+       conventions for private variables"""
+    return "_%s__%s" % (classname, attrname)
+
+def class_space(classlevel=3):
+    "returns the calling class' name and dictionary"
+    frame = sys._getframe(classlevel)
+    classname = frame.f_code.co_name
+    classdict = frame.f_locals
+    return classname, classdict
+
+# convenience function
+def readable(**kwds):
+    "returns one read-only property for each (key,value) pair in kwds"
+    return _attribute(permission='r', **kwds)
+
+# convenience function
+def writable(**kwds):
+    "returns one write-only property for each (key,value) pair in kwds"
+    return _attribute(permission='w', **kwds) 
+
+# needed because of the way class_space is resolved in _attribute
+def attribute(permission='rwd', **kwds):
+    """returns one property for each (key,value) pair in kwds;
+       each property provides the specified level of access(permission):
+           'r': readable, 'w':writable, 'd':deletable
+    """
+    return _attribute(permission, **kwds)
+
+# based on code by Guido van Rossum, comp.lang.python 2001-07-31        
+def _attribute(permission='rwd', **kwds):
+    """returns one property for each (key,value) pair in kwds;
+       each property provides the specified level of access(permission):
+           'r': readable, 'w':writable, 'd':deletable
+    """
+    classname, classdict = class_space()
+    def _property(attrname, default):
+        propname, attrname = attrname, mangle(classname, attrname)
+        fget, fset, fdel, doc = None, None, None, propname
+        if 'r' in permission:
+            def fget(self):
+                value = default
+                try: value = getattr(self, attrname)
+                except AttributeError: setattr(self, attrname, default)
+                return value
+        if 'w' in permission:
+            def fset(self, value):
+                setattr(self, attrname, value)
+        if 'd' in permission:
+            def fdel(self): 
+                try: delattr(self, attrname)
+                except AttributeError: pass
+                # calling fget can restore this attribute, so remove property 
+                delattr(self.__class__, propname)
+        return property(fget=fget, fset=fset, fdel=fdel, doc=doc)
+        
+    for attrname, default in kwds.items():
+        classdict[attrname] = _property(attrname, default)
+

File cookbook/doc_optparse.py

+"""
+:Author: M. Simionato
+:Date: April 2004
+:Title: A much simplified interface to optparse.
+
+You should use optionparse in your scripts as follows.
+First, write a module level docstring containing something like this
+(this is just an example):
+
+'''usage: %prog files [options]
+   -d, --delete: delete all files
+   -e, --erase = ERASE: erase the given file'''
+   
+Then write a main program of this kind:
+
+# sketch of a script to delete files
+if __name__=='__main__':
+    import optionparse
+    option,args=optionparse.parse(__doc__)
+    if not args and not option: optionparse.exit()
+    elif option.delete: print "Delete all files"
+    elif option.erase: print "Delete the given file"
+
+Notice that ``optionparse`` parses the docstring by looking at the
+characters ",", ":", "=", "\\n", so be careful in using them. If
+the docstring is not correctly formatted you will get a SyntaxError
+or worse, the script will not work as expected.
+"""
+
+import optparse, re, sys
+
+USAGE = re.compile(r'(?s)\s*usage: (.*?)(\n[ \t]*\n|$)')
+
+def nonzero(self): # will become the nonzero method of optparse.Values       
+    "True if options were given"
+    for v in self.__dict__.itervalues():
+        if v is not None: return True
+    return False
+
+optparse.Values.__nonzero__ = nonzero # dynamically fix optparse.Values
+
+class ParsingError(Exception): pass
+
+optionstring=""
+
+def exit(msg=""):
+    raise SystemExit(msg or optionstring.replace("%prog",sys.argv[0]))
+
+def parse(docstring, arglist=None):
+    global optionstring
+    optionstring = docstring
+    match = USAGE.search(optionstring)
+    if not match: raise ParsingError("Cannot find the option string")
+    optlines = match.group(1).splitlines()
+    try:
+        p = optparse.OptionParser(optlines[0])
+        for line in optlines[1:]:
+            opt, help=line.split(':')[:2]
+            short,long=opt.split(',')[:2]
+            if '=' in opt:
+                action='store'
+                long=long.split('=')[0]
+            else:
+                action='store_true'
+            p.add_option(short.strip(),long.strip(),
+                         action = action, help = help.strip())
+    except (IndexError,ValueError):
+        raise ParsingError("Cannot parse the option string correctly")
+    return p.parse_args(arglist)
+

File cookbook/progress_bar.py

+import sys
+
+"""
+Class for building a text progress bar, see __main__ for command line use (\r is the key)
+
+http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/168639
+"""
+
+class ProgressBar:
+    def __init__(self, minValue = 0, maxValue = 10, totalWidth=12):
+        self.progBar = "[]"   # This holds the progress bar string
+        self.min = minValue
+        self.max = maxValue
+        self.span = maxValue - minValue
+        self.width = totalWidth
+        self.amount = 0       # When amount == max, we are 100% done 
+        self.update(0)  # Build progress bar string
+
+    def update(self, newAmount = 0):
+        if newAmount < self.min: newAmount = self.min
+        if newAmount > self.max: newAmount = self.max
+        self.amount = newAmount
+
+        # Figure out the new percent done, round to an integer
+        diffFromMin = float(self.amount - self.min)
+        percentDone = (diffFromMin / float(self.span)) * 100.0
+        percentDone = round(percentDone)
+        percentDone = int(percentDone)
+
+        # Figure out how many hash bars the percentage should be
+        allFull = self.width - 2
+        numHashes = (percentDone / 100.0) * allFull
+        numHashes = int(round(numHashes))
+
+        # build a progress bar with hashes and spaces
+        if allFull == numHashes:
+            self.progBar = "[" + '='*(numHashes) + "]"
+        else:
+            self.progBar = "[" + '='*(numHashes-1) + '>' + ' '*(allFull-numHashes) + "]"
+
+        # figure out where to put the percentage, roughly centered
+        percentPlace = (len(self.progBar) / 2) - len(str(percentDone)) 
+        percentString = str(percentDone) + "%"
+
+        # slice the percentage into the bar
+        self.progBar = self.progBar[0:percentPlace] + percentString + self.progBar[percentPlace+len(percentString):]
+
+    def update_and_print( self, newAmount = 0, f = sys.stdout ):
+        self.update( newAmount )
+        print >> f, "\r", self,
+        f.flush()
+
+
+    def __str__(self):
+        return str(self.progBar)
+
+if __name__ == "__main__":
+    import time
+
+    bar = ProgressBar( 0, 1000, 80 )
+
+    for i in range(1000):
+        bar.update( i )
+        print "\r", bar,
+        sys.stdout.flush()
+        
+
+    print

File scripts.list

 maf_to_fasta.py
 maf_to_int_seqs.py
 maf_truncate.py
-merge_ranges.py
 nib_intervals_to_fasta.py
 nib_length.py
 one_field_per_line.py
 pretty_table.py
-prefix_lines
-ranges.py
 scores_to_h5.py
 tfloc_summary.py
 ucsc_gene_table_to_intervals.py
 scripts = open( "scripts.list" ).read().split()
 all_packages = open( "packages.list" ).read().split()
 py_packages = [ p[:-3] for p in all_packages if p.endswith( ".py" ) ]
-print py_packages
 packages = [ p for p in all_packages if not p.endswith( ".py" ) ]
 
 
         py_modules = py_packages,
         packages = packages,
         scripts = open( "scripts.list" ).read().split(),
-        ext_modules=[ Extension( "bitset", [ "bitset.pyx" ] + [ JK_LIB + f for f in bitset_deps ], include_dirs=[JK_INC] ) ],
+        ext_modules=[ Extension( "bx.bitset", [ "bx/bitset.pyx" ] + [ JK_LIB + f for f in bitset_deps ], include_dirs=[JK_INC] ) ],
         cmdclass = {'build_ext': build_ext}
      )