Package solvcon :: Module helper
[hide private]
[frames] | no frames]

Source Code for Module solvcon.helper

  1  # -*- coding: UTF-8 -*- 
  2  # 
  3  # Copyright (C) 2008-2011 Yung-Yu Chen <yyc@solvcon.net>. 
  4  # 
  5  # This program is free software; you can redistribute it and/or modify 
  6  # it under the terms of the GNU General Public License as published by 
  7  # the Free Software Foundation; either version 2 of the License, or 
  8  # (at your option) any later version. 
  9  # 
 10  # This program is distributed in the hope that it will be useful, 
 11  # but WITHOUT ANY WARRANTY; without even the implied warranty of 
 12  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 13  # GNU General Public License for more details. 
 14  # 
 15  # You should have received a copy of the GNU General Public License along 
 16  # with this program; if not, write to the Free Software Foundation, Inc., 
 17  # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 
 18   
 19  """ 
 20  Helping functionalities. 
 21  """ 
22 23 -class Printer(object):
24 """ 25 Print message to a stream. 26 27 @ivar _streams: list of (stream, filename) tuples to be used.. 28 @itype _streams: list 29 """ 30
31 - def __init__(self, streams, **kw):
32 import sys, os 33 import warnings 34 self.prefix = kw.pop('prefix', '') 35 self.postfix = kw.pop('postfix', '') 36 self.override = kw.pop('override', False) 37 self.force_flush = kw.pop('force_flush', True) 38 # build (stream, filename) tuples. 39 if not isinstance(streams, list) and not isinstance(streams, tuple): 40 streams = [streams] 41 self._streams = [] 42 for stream in streams: 43 if isinstance(stream, str): 44 if stream == 'sys.stdout': 45 self._streams.append((sys.stdout, None)) 46 else: 47 if not self.override and os.path.exists(stream): 48 warnings.warn('file %s overriden.' % stream, 49 UserWarning) 50 self._streams.append((open(stream, 'w'), stream)) 51 else: 52 self._streams.append((stream, None))
53 54 @property
55 - def streams(self):
56 return (s[0] for s in self._streams)
57
58 - def __call__(self, msg):
59 msg = ''.join([self.prefix, msg, self.postfix]) 60 for stream in self.streams: 61 stream.write(msg) 62 if self.force_flush: 63 stream.flush()
64
65 -class Information(object):
66 - def __init__(self, **kw):
67 self.prefix = kw.pop('prefix', '*') 68 self.nchar = kw.pop('nchar', 4) 69 self.width = kw.pop('width', 80) 70 self.level = kw.pop('level', 0) 71 self.muted = kw.pop('muted', False)
72 @property
73 - def streams(self):
74 import sys 75 from .conf import env 76 if self.muted: return [] 77 streams = [sys.stdout] 78 if env.logfile != None: streams.append(env.logfile) 79 return streams
80 - def __call__(self, data, travel=0, level=None, has_gap=True):
81 self.level += travel 82 if level == None: 83 level = self.level 84 width = self.nchar*level 85 lines = data.split('\n') 86 prefix = self.prefix*(self.nchar-1) 87 if width > 0: 88 if has_gap: 89 prefix += ' ' 90 else: 91 prefix += '*' 92 prefix = '\n' + prefix*self.level 93 data = prefix.join(lines) 94 for stream in self.streams: 95 stream.write(data) 96 stream.flush()
97 info = Information()
98 99 -def generate_apidoc(outputdir='doc/api'):
100 """ 101 Use epydoc to generate API doc. 102 """ 103 import os 104 from epydoc.docbuilder import build_doc_index 105 from epydoc.docwriter.html import HTMLWriter 106 docindex = build_doc_index(['solvcon'], introspect=True, parse=True, 107 add_submodules=True) 108 html_writer = HTMLWriter(docindex) 109 # write. 110 outputdir = os.path.join(*outputdir.split('/')) 111 if not os.path.exists(outputdir): 112 os.makedirs(outputdir) 113 html_writer.write(outputdir)
114
115 -def iswin():
116 """ 117 @return: flag under windows or not. 118 @rtype: bool 119 """ 120 import sys 121 if sys.platform.startswith('win'): 122 return True 123 else: 124 return False
125
126 -def get_username():
127 import os 128 try: 129 username = os.getlogin() 130 except: 131 username = None 132 if not username: 133 username = os.environ['LOGNAME'] 134 return username
135
136 -def search_in_parents(loc, name):
137 """ 138 Search for something in the file system all the way up from the specified 139 location to the root. 140 141 @param loc: the location to start searching. 142 @type loc: str 143 @param name: the searching target. 144 @type name: str 145 @return: the absolute path to the FS item. 146 @rtype: str 147 """ 148 import os 149 item = '' 150 loc = os.path.abspath(loc) 151 while True: 152 if os.path.exists(os.path.join(loc, name)): 153 item = os.path.join(loc, name) 154 break 155 parent = os.path.dirname(loc) 156 if loc == parent: 157 break 158 else: 159 loc = parent 160 return os.path.abspath(item) if item else item
161
162 -class Cubit(object):
163 """ 164 Delegate Cubit command through journaling file and load the generated mesh. 165 166 @ivar cmds: commands to be sent to Cubit. 167 @itype cmds: list 168 @ivar ndim: number of dimensions. 169 @itype ndim: int 170 @ivar large: use large file of Genesis/ExodusII or not. 171 @itype large: bool 172 """
173 - def __init__(self, cmds, ndim, large=False):
174 self.cmds = cmds 175 self.ndim = ndim 176 self.large = large 177 self.stdout = None
178 - def __call__(self):
179 """ 180 Launch Cubit for generating mesh and then load the generated 181 Genesis/ExodusII file. 182 183 @return: the loaded Genesis object. 184 @rtype: solvcon.io.genesis.Genesis 185 """ 186 from tempfile import mkdtemp 187 import os, shutil 188 from subprocess import Popen, PIPE, STDOUT 189 from .io.genesis import Genesis 190 # prepare working directory. 191 wdir = mkdtemp() 192 joup = os.path.join(wdir, 'jou.jou') 193 gnp = os.path.join(wdir, 'gn.g') 194 # prepare journaling file. 195 cmds = self.cmds[:] 196 cmds.insert(0, 'cd "%s"' % wdir) 197 cmds.append('set large exodus file %s' % 'on' if self.large else 'off') 198 cmds.append('export genesis "%s" dimension %d overwrite' % ( 199 gnp, self.ndim)) 200 jouf = open(joup, 'w') 201 jouf.write('\n'.join(cmds)) 202 jouf.close() 203 # call Cubit and get the data. 204 cli = 'cubit -nographics -batch -nojournal -input %s' % joup 205 try: 206 pobj = Popen(cli, shell=True, stdout=PIPE, stderr=STDOUT) 207 self.stdout = pobj.stdout.read() 208 gn = Genesis(gnp) 209 gn.load() 210 gn.close_file() 211 except: 212 gn = None 213 finally: 214 shutil.rmtree(wdir) 215 return gn
216