Package meshpy :: Module gmsh
[hide private]
[frames] | no frames]

Source Code for Module meshpy.gmsh

1 -class GmshError(RuntimeError):
2 pass
3 4 5 6 # tools -----------------------------------------------------------------------
7 -def _erase_dir(dir):
8 from os import listdir, unlink, rmdir 9 from os.path import join 10 for name in listdir(dir): 11 unlink(join(dir, name)) 12 rmdir(dir)
13 14 15
16 -class _TempDirManager(object):
17 - def __init__(self):
18 from tempfile import mkdtemp 19 self.path = mkdtemp()
20
21 - def sub(self, n):
22 from os.path import join 23 return join(self.path, n)
24
25 - def clean_up(self):
26 _erase_dir(self.path)
27
28 - def error_clean_up(self):
29 _erase_dir(self.path)
30 31 32 33
34 -class GmshRunner(object):
35 - def __init__(self, source, dimensions, order=None, 36 incomplete_elements=None, other_options=[], 37 extension="geo", gmsh_executable="gmsh"):
38 self.source = source 39 self.dimensions = dimensions 40 self.order = order 41 self.incomplete_elements = incomplete_elements 42 self.other_options = other_options 43 self.extension = extension 44 self.gmsh_executable = gmsh_executable 45 46 if dimensions not in [1, 2, 3]: 47 raise RuntimeError("dimensions must be one of 1,2,3")
48
49 - def __enter__(self):
50 self.temp_dir_mgr = None 51 temp_dir_mgr = _TempDirManager() 52 try: 53 working_dir = temp_dir_mgr.path 54 from os.path import join 55 source_file_name = join(working_dir, "temp."+self.extension) 56 source_file = open(source_file_name, "w") 57 try: 58 source_file.write(self.source) 59 finally: 60 source_file.close() 61 62 output_file_name = join(working_dir, "output.msh") 63 cmdline = [ 64 self.gmsh_executable, 65 "-%d" % self.dimensions, 66 "-o", output_file_name, 67 "-nopopup"] 68 69 if self.order is not None: 70 cmdline.extend(["-order", str(self.order)]) 71 72 if self.incomplete_elements is not None: 73 cmdline.extend(["-string", 74 "Mesh.SecondOrderIncomplete = %d;" % int(self.incomplete_elements)]) 75 76 cmdline.extend(self.other_options) 77 cmdline.append(source_file_name) 78 79 from pytools.prefork import call_capture_output 80 retcode, stdout, stderr = call_capture_output( 81 cmdline, working_dir) 82 83 if stderr and "error" in stderr.lower(): 84 msg = "gmsh execution failed with message:\n\n" 85 if stdout: 86 msg += stdout+"\n" 87 msg += stderr+"\n" 88 raise GmshError(msg) 89 90 if stderr: 91 from warnings import warn 92 93 msg = "gmsh issued the following messages:\n\n" 94 if stdout: 95 msg += stdout+"\n" 96 msg += stderr+"\n" 97 warn(msg) 98 99 self.output_file = open(output_file_name, "r") 100 101 self.temp_dir_mgr = temp_dir_mgr 102 return self.output_file 103 except: 104 temp_dir_mgr.clean_up() 105 raise
106
107 - def __exit__(self, type, value, traceback):
108 self.output_file.close() 109 if self.temp_dir_mgr is not None: 110 self.temp_dir_mgr.clean_up()
111