root/trunk/src/__init__.py

Revision 365, 6.9 kB (checked in by mschmucker, 2 weeks ago)

Added draft implementation for an parameter search/optimization
framework. Currently, only grid search is implemented. See also Ticket #47 for
more info.

Line 
1 """
2 NeuroTools
3 ==========
4
5 NeuroTools is not a neural simulator, but a collection of tools
6 to support all tasks associated with a neural simulation project which
7 are not handled by the simulation engine.
8
9 For more information see:
10 http://neuralensemble.org/NeuroTools
11
12
13 Available subpackages
14 ---------------------
15
16 NeuroTools functionality is modularized as follows:
17
18 signals    - provides core classes for manipulation of spike trains and analog signals.
19 spike2     - offers an easy way for reading data from CED's Spike2 Son files.
20 parameters - contains classes for managing large, hierarchical parameter sets.
21 analysis   - cross-correlation, tuning curves, frequency spectrum, etc.
22 stgen      - various stochastic process generators relevant for Neuroscience
23              (OU, poisson, inhomogenous gamma, ...).
24 utilities  - miscellaneous stuff, like SRB access.
25 io         - NeuroTools support for reading and writing of files in various formats.
26 plotting   - routines for plotting and visualization.
27 datastore  - a consistent interface for persistent data storage (e.g. for caching intermediate results).
28 random     - a set of classes representing statistical distributions
29
30 Sub-package specific documentation is available by importing the
31 sub-package, and requesting help on it:
32
33 >>> import NeuroTools.signals
34 >>> help(NeuroTools.signals)
35 """
36
37 __all__ = ['analysis', 'parameters', 'plotting', 'signals', 'stgen', 'io', 'datastore', 'utilities', 'spike2', 'random', 'optimize']
38 __version__ = "0.1.0 (Asynchronous Astrocyte)"
39
40 #########################################################
41 ## ALL DEPENDENCIES SHOULD BE GATHERED HERE FOR CLARITY
42 #########################################################
43
44 # The nice thing would be to gather every non standard
45 # dependency here, in order to centralize the warning
46 # messages and the check
47 dependencies = {'pylab' : {'website' : 'http://matplotlib.sourceforge.net/', 'is_present' : False, 'check':False},
48                 'matplotlib': {'website' : 'http://matplotlib.sourceforge.net/', 'is_present' : False, 'check':False},
49                 'tables': {'website' : 'http://www.pytables.org/moin' , 'is_present' : False, 'check':False},
50                 'psyco' : {'website' : 'http://psyco.sourceforge.net/', 'is_present' : False, 'check':False},
51                 'pygsl' : {'website' : 'http://pygsl.sourceforge.net/', 'is_present' : False, 'check':False},
52                 'PIL'   : {'website' : 'http://www.pythonware.com/products/pil/', 'is_present':False, 'check':False},
53                 'scipy' : {'website' : 'http://numpy.scipy.org/' , 'is_present' : False, 'check':False},
54                 'NeuroTools.facets.hdf5' : {'website' : None, 'is_present' : False, 'check':False},
55                 'srblib' : {'website' : 'http://www.sdsc.edu/srb/index.php/Python', 'is_present' : False, 'check':False},
56                 'rpy' : {'website' : 'http://rpy.sourceforge.net/', 'is_present' : False, 'check':False},
57
58                 ## Add here your extensions ###
59                }
60
61
62 #########################################################
63 ## Function to display error messages on the dependencies
64 #########################################################
65
66 def get_import_warning(name):
67     return ''' ----------------- Dependency Warning ---------------------
68 ** %s ** package is not installed.
69 To have functions using %s please install the package.
70 website : %s
71 ''' %(name, name, dependencies[name]['website'])
72
73 def get_runtime_warning(name, errmsg):
74     return ''' ----------------- Dependency Warning ---------------------
75 ** %s ** package is installed but cannot be imported. The error message is: %s
76 ''' %(name, errmsg)
77
78 def check_numpy_version():
79     import numpy
80     numpy_version = numpy.__version__.split(".")[0:2]
81     numpy_version = float(".".join(numpy_version))
82     if numpy_version >= 1.2:
83         return True
84     else:
85         return False
86
87 def check_pytables_version():
88    #v = [int(s) for s in __version__.split('.')]
89    if tables.__version__<= 2: #1.4: #v[0] < 1 or (v[0] == 1 and v[1] < 4):
90        raise Exception('PyTables version must be >= 1.4, installed version is %s' % __version__)
91
92 def check_dependency(name):
93     if dependencies[name]['check']:
94         return dependencies[name]['is_present']
95     else:
96         try:
97             exec("import %s" %name)
98             dependencies[name]['is_present'] = True
99         except ImportError:
100             print get_import_warning(name)
101         except RuntimeError, errmsg:
102             print get_runtime_warning(name, errmsg)
103         dependencies[name]['check'] = True
104         return dependencies[name]['is_present']
105
106
107
108 # Setup fancy logging
109
110 red     = 0010; green  = 0020; yellow = 0030; blue = 0040;
111 magenta = 0050; cyan   = 0060; bright = 0100
112 try:
113     import ll.ansistyle
114     def colour(col,text):
115         return str(ll.ansistyle.Text(col,str(text)))
116 except ImportError:
117     def colour(col,text):
118             return text
119        
120 import logging
121
122 # Add a header() level to logging
123 logging.HEADER = 60
124 logging.addLevelName(logging.HEADER, 'HEADER')
125
126 root = logging.getLogger()
127
128 def root_header(msg, *args, **kwargs):
129     if len(root.handlers) == 0:
130         basicConfig()
131     apply(root.header, (msg,)+args, kwargs)
132
133 def logger_header(self, msg, *args, **kwargs):
134     if self.manager.disable >= logging.HEADER:
135         return
136     if logging.HEADER >= self.getEffectiveLevel():
137         apply(self._log, (logging.HEADER, msg, args), kwargs)
138
139 logging.Logger.header = logger_header
140 logging.header = root_header
141
142 class FancyFormatter(logging.Formatter):
143     """
144     A log formatter that colours and indents the log message depending on the level.
145     """
146    
147     DEFAULT_COLOURS = {
148         'CRITICAL': bright+red,
149         'ERROR': red,
150         'WARNING': magenta,
151         'HEADER': bright+yellow,
152         'INFO': cyan,
153         'DEBUG': green
154     }
155    
156     DEFAULT_INDENTS = {
157         'CRITICAL': "",
158         'ERROR': "",
159         'WARNING': "",
160         'HEADER': "",
161         'INFO': "  ",
162         'DEBUG': "    ",
163     }
164    
165     def __init__(self, fmt=None, datefmt=None, colours=DEFAULT_COLOURS):
166         logging.Formatter.__init__(self, fmt, datefmt)
167         self._colours = colours
168         self._indents = FancyFormatter.DEFAULT_INDENTS
169    
170     def format(self, record):
171         s = logging.Formatter.format(self, record)
172         if record.levelname == "HEADER":
173             s = "=== %s ===" % s
174         if self._colours:
175             s = colour(self._colours[record.levelname], s)
176         return self._indents[record.levelname] + s
177
178
179 def init_logging(filename, file_level=logging.INFO, console_level=logging.WARNING):
180     logging.basicConfig(level=file_level,
181                         format='%(asctime)s %(levelname)s %(message)s', # %(pathname)s %(module)s %(funcName)s',
182                         filename=filename,
183                         filemode='w')
184     console = logging.StreamHandler()
185     console.setLevel(console_level)
186     console.setFormatter(FancyFormatter('%(message)s'))
187     logging.getLogger('').addHandler(console)
Note: See TracBrowser for help on using the browser.