def main(): parser = ArgumentParser(description=__doc__) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--eps', action='store', dest='eps', default=1e-12, help=helps['eps']) parser.add_argument('-o', '--filename-out', action='store', dest='filename_out', default=None, help=helps['filename-out']) parser.add_argument('filename') options = parser.parse_args() filename = options.filename mesh = Mesh.from_file(filename) mesh_out = extract_edges(mesh, eps=float(options.eps)) mesh_out = merge_lines(mesh_out) filename_out = options.filename_out if filename_out is None: filename_out = edit_filename(filename, prefix='edge_', new_ext='.vtk') output('Outline mesh - vertices: %d, edges: %d, output filename: %s' % (mesh_out[0].shape[0], mesh_out[2][0].shape[0], filename_out)) # hack to write '3_2' elements - edges io = VTKMeshIO(None) aux_mesh = Struct() aux_mesh._get_io_data = lambda: mesh_out aux_mesh.n_el = mesh_out[2][0].shape[0] io.write(filename_out, aux_mesh)
def generate_gallery_html(output_filename, gallery_dir, rst_dir, thumbnails_dir, dir_map, link_prefix=''): """ Generate the gallery html file with thumbnail images and links to examples. Parameters ---------- output_filename : str The output html file name. gallery_dir : str The top level directory of gallery files. rst_dir : str The full path to rst files of examples within `gallery_dir`. thumbnails_dir : str The full path to thumbnail images within `gallery_dir`. dir_map : dict The directory mapping returned by `generate_rst_files()` link_prefix : str, optional The prefix to prepend to links to individual pages of examples. """ output('generating %s...' % output_filename) lines = [] for dirname, filenames in ordered_iteritems(dir_map): full_dirname = os.path.join(rst_dir, dirname) for ex_filename, rst_filename in filenames: full_rst_filename = os.path.join(full_dirname, rst_filename) ebase = full_rst_filename.replace(rst_dir, '')[1:] ebase = edit_filename(ebase, new_ext='.py') link_base = full_rst_filename.replace(gallery_dir, '')[1:] link = os.path.join(link_prefix, os.path.splitext(link_base)[0] + '.html') _get_fig_filenames(ebase, thumbnails_dir).next() for thumbnail_filename in _get_fig_filenames(ebase, thumbnails_dir): if not os.path.isfile(thumbnail_filename): # Skip examples with no image (= failed examples). continue thumbnail_name = thumbnail_filename.replace(gallery_dir, '')[1:] line = _link_template % (link, thumbnail_name, os.path.splitext(ebase)[0]) lines.append(line) fd = open(output_filename, 'w') fd.write(_gallery_template % (link_prefix, '\n'.join(lines))) fd.close() output('...done')
def main(): parser = ArgumentParser(description=__doc__) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--eps', action='store', dest='eps', default=1e-12, help=helps['eps']) parser.add_argument('-o', '--filename-out', action='store', dest='filename_out', default=None, help=helps['filename-out']) parser.add_argument('filename') options = parser.parse_args() filename = options.filename mesh = Mesh.from_file(filename) mesh_out = extract_edges(mesh, eps=float(options.eps)) mesh_out = merge_lines(mesh_out) filename_out = options.filename_out if filename_out is None: filename_out = edit_filename(filename, prefix='edge_', new_ext='.vtk') output('Outline mesh - vertices: %d, edges: %d, output filename: %s' % (mesh_out[0].shape[0], mesh_out[2][0].shape[0], filename_out)) # hack to write '3_2' elements - edges io = MeshioLibIO() aux_mesh = Struct() aux_mesh._get_io_data = lambda: mesh_out aux_mesh.n_el = mesh_out[2][0].shape[0] io.write(filename_out, aux_mesh)
def generate_images(images_dir, examples_dir): """ Generate images from results of running examples found in `examples_dir` directory. The generated images are stored to `images_dir`, """ from sfepy.applications import solve_pde from sfepy.postprocess.viewer import Viewer from sfepy.postprocess.utils import mlab prefix = output.prefix output_dir = tempfile.mkdtemp() trunk = os.path.join(output_dir, 'result') options = Struct(output_filename_trunk=trunk, output_format='vtk', save_ebc=False, save_ebc_nodes=False, save_regions=False, save_field_meshes=False, save_regions_as_groups=False, solve_not=False) default_views = {'' : {}} ensure_path(images_dir + os.path.sep) view = Viewer('', offscreen=False) for ex_filename in locate_files('*.py', examples_dir): if _omit(ex_filename): continue output.level = 0 output.prefix = prefix ebase = ex_filename.replace(examples_dir, '')[1:] output('trying "%s"...' % ebase) try: problem, state = solve_pde(ex_filename, options=options) except KeyboardInterrupt: raise except: problem = None output('***** failed! *****') if problem is not None: if ebase in custom: views = custom[ebase] else: views = default_views tsolver = problem.get_time_solver() if tsolver.ts is None: suffix = None else: suffix = tsolver.ts.suffix % (tsolver.ts.n_step - 1) filename = problem.get_output_name(suffix=suffix) for suffix, kwargs in views.iteritems(): fig_filename = _get_fig_filename(ebase, images_dir, suffix) fname = edit_filename(filename, suffix=suffix) output('displaying results from "%s"' % fname) disp_name = fig_filename.replace(sfepy.data_dir, '') output('to "%s"...' % disp_name.lstrip(os.path.sep)) view.filename = fname view(scene=view.scene, show=False, is_scalar_bar=True, **kwargs) view.save_image(fig_filename) mlab.clf() output('...done') remove_files(output_dir) output('...done')
def generate_gallery_html(examples_dir, output_filename, gallery_dir, rst_dir, thumbnails_dir, dir_map, link_prefix): """ Generate the gallery html file with thumbnail images and links to examples. Parameters ---------- output_filename : str The output html file name. gallery_dir : str The top level directory of gallery files. rst_dir : str The full path to rst files of examples within `gallery_dir`. thumbnails_dir : str The full path to thumbnail images within `gallery_dir`. dir_map : dict The directory mapping returned by `generate_rst_files()` link_prefix : str, optional The prefix to prepend to links to individual pages of examples. """ output('generating %s...' % output_filename) with open(_gallery_template_file, 'r') as fd: gallery_template = fd.read() div_lines=[] sidebar = [] for dirname, filenames in ordered_iteritems(dir_map): full_dirname = os.path.join(rst_dir, dirname) dirnamenew = dirname.replace("_"," ") sidebarline = _side_links % (dirname, dirnamenew.title()) lines = [] for ex_filename, rst_filename in filenames: full_rst_filename = os.path.join(full_dirname, rst_filename) ebase = full_rst_filename.replace(rst_dir, '')[1:] ebase = edit_filename(ebase, new_ext='.py') link_base = full_rst_filename.replace(gallery_dir, '')[1:] link = os.path.join(link_prefix, os.path.splitext(link_base)[0] + '.html') _get_fig_filenames(ebase, thumbnails_dir).next() for thumbnail_filename in _get_fig_filenames(ebase, thumbnails_dir): if not os.path.isfile(thumbnail_filename): # Skip examples with no image (= failed examples). continue thumbnail_name = thumbnail_filename.replace(gallery_dir, '')[1:] path_to_file = os.path.join(examples_dir,ebase) docstring = get_default(import_file(path_to_file).__doc__, 'missing description!') docstring = docstring.replace('e.g.', 'eg:') docstring = docstring.split('.') line = _link_template % (link,os.path.splitext(ebase)[0], thumbnail_name,link,docstring[0]+'.') lines.append(line) if(len(lines)!=0): div_lines.append(_div_line % (dirname, dirnamenew.title(), dirname, '\n'.join(lines))) sidebar.append(sidebarline) fd = open(output_filename, 'w') fd.write(gallery_template % ((link_prefix,) * 7 + ('\n'.join(sidebar), '\n'.join(div_lines)))) fd.close() output('...done')
def generate_images(images_dir, examples_dir): """ Generate images from results of running examples found in `examples_dir` directory. The generated images are stored to `images_dir`, """ from sfepy.applications import solve_pde from sfepy.postprocess import Viewer from sfepy.postprocess.utils import mlab prefix = output.prefix output_dir = tempfile.mkdtemp() trunk = os.path.join(output_dir, 'result') options = Struct(output_filename_trunk=trunk, output_format='vtk', save_ebc=False, save_ebc_nodes=False, save_regions=False, save_field_meshes=False, save_regions_as_groups=False, solve_not=False) default_views = {'' : {}} ensure_path(images_dir + os.path.sep) view = Viewer('', offscreen=False) for ex_filename in locate_files('*.py', examples_dir): if _omit(ex_filename): continue output.level = 0 output.prefix = prefix ebase = ex_filename.replace(examples_dir, '')[1:] output('trying "%s"...' % ebase) try: problem, state = solve_pde(ex_filename, options=options) except KeyboardInterrupt: raise except: problem = None output('***** failed! *****') if problem is not None: if ebase in custom: views = custom[ebase] else: views = default_views tsolver = problem.get_time_solver() if tsolver.ts is None: suffix = None else: suffix = tsolver.ts.suffix % (tsolver.ts.n_step - 1) filename = problem.get_output_name(suffix=suffix) for suffix, kwargs in views.iteritems(): fig_filename = _get_fig_filename(ebase, images_dir, suffix) fname = edit_filename(filename, suffix=suffix) output('displaying results from "%s"' % fname) disp_name = fig_filename.replace(sfepy.data_dir, '') output('to "%s"...' % disp_name.lstrip(os.path.sep)) view.filename = fname view(scene=view.scene, show=False, is_scalar_bar=True, fig_filename=fig_filename, **kwargs) mlab.clf() output('...done') remove_files(output_dir) output('...done')
def main(): parser = OptionParser(usage = usage, version = "%prog " + sfepy.__version__) parser.add_option( "-m", "--mesh", action = "store_true", dest = "save_mesh", default = True, help = "save surface mesh [default: %default]" ) parser.add_option( "-n", "--no-surface", action = "store_true", dest = "no_surface", default = False, help = "do not output surface [default: %default]" ) (options, args) = parser.parse_args() if (len( args ) == 2): filename_in = args[0]; filename_out = args[1]; else: parser.print_help(), return if (filename_in == '-'): file_in = sys.stdin else: file_in = open( filename_in, "r" ); mesh = Mesh.from_file( filename_in ) if (filename_in != '-'): file_in.close() domain = Domain('domain', mesh) domain.setup_groups() if domain.has_faces(): domain.fix_element_orientation() domain.setup_facets(create_edges=False) lst, surf_faces = domain.surface_faces() surf_mesh = Mesh.from_surface( surf_faces, mesh ) if options.save_mesh: aux = edit_filename(filename_in, prefix='surf_', new_ext='.mesh') surf_mesh.write(aux, io='auto') if options.no_surface: return gr_s = surface_graph( surf_faces, mesh.n_nod ) ## import sfepy.base.plotutils as plu ## plu.spy( gr_s ) ## plu.pylab.show() n_comp, comps = surface_components( gr_s, surf_faces ) # print 'components:', n_comp ccs, comps = comps, nm.zeros( (0,1), nm.int32 ) for cc in ccs: comps = nm.concatenate( (comps, cc[:,nm.newaxis]), 0 ) out = nm.concatenate( (lst, comps), 1 ) if (filename_out == '-'): file_out = sys.stdout else: file_out = open( filename_out, "w" ); for row in out: file_out.write( '%d %d %d %d\n' % (row[0], row[1], row[2], row[3]) ) if (filename_out != '-'): file_out.close()
def main(): parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument("--version", action="version", version="%(prog)s " + sfepy.__version__) parser.add_argument("-m", "--mesh", action="store_true", dest="save_mesh", default=False, help="save surface mesh") parser.add_argument("-n", "--no-surface", action="store_true", dest="no_surface", default=False, help="do not output surface [default: %(default)s]") parser.add_argument('filename_in', help="'-' is for stdin") parser.add_argument('filename_out', help="'-' is for stdout") options = parser.parse_args() filename_in = options.filename_in filename_out = options.filename_out if (filename_in == '-'): file_in = sys.stdin else: file_in = open(filename_in, "r") mesh = Mesh.from_file(filename_in) if (filename_in != '-'): file_in.close() domain = FEDomain('domain', mesh) if options.save_mesh: region = domain.create_region('surf', 'vertices of surface', 'facet') surf_mesh = Mesh.from_region(region, mesh, localize=True, is_surface=True) aux = edit_filename(filename_in, prefix='surf_', new_ext='.mesh') surf_mesh.write(aux, io='auto') if domain.has_faces(): domain.fix_element_orientation() lst, surf_faces = get_surface_faces(domain) if options.no_surface: return gr_s = surface_graph(surf_faces, mesh.n_nod) n_comp, comps = surface_components(gr_s, surf_faces) output('number of surface components:', n_comp) ccs, comps = comps, nm.zeros((0,1), nm.int32) for cc in ccs: comps = nm.concatenate((comps, cc[:,nm.newaxis]), 0) out = nm.concatenate((lst, comps), 1) if (filename_out == '-'): file_out = sys.stdout else: file_out = open(filename_out, "w") for row in out: file_out.write('%d %d %d\n' % (row[0], row[1], row[2])) if (filename_out != '-'): file_out.close()
def main(): parser = OptionParser(usage=usage, version='%prog') parser.add_option('-n', '--dry-run', action='store_true', dest='dry_run', default=False, help=help['dry_run']) options, args = parser.parse_args() if len(args) == 2: doc_dir, top_dir = [os.path.realpath(ii) for ii in args] else: parser.print_help(), return docs = set(ii for ii in locate_files('*.rst', root_dir=doc_dir)) sources = set(ii for ii in locate_files('*.py', root_dir=os.path.join(top_dir, 'sfepy')) if os.path.basename(ii) not in omits) sources.update(ii for ii in locate_files('*.pyx', root_dir=os.path.join(top_dir, 'sfepy')) if os.path.basename(ii) not in omits_pyx) scripts = set(ii for ii in locate_files('*.py', root_dir=os.path.join(top_dir, 'script')) if os.path.basename(ii) not in omits) top_scripts = set(os.path.realpath(ii) for ii in fnmatch.filter(os.listdir(top_dir), '*.py') if os.path.basename(ii) not in omits) all_sources = set() all_sources.update(sources, scripts, top_scripts) cwd = os.path.realpath(os.path.curdir) + os.path.sep output.prefix = 'smd:' output('removing unneeded rst files in "%s"...' % doc_dir) for doc in sorted(docs): aux = edit_filename(doc, new_ext='.py') src1 = os.path.normpath(aux.replace(doc_dir, top_dir)) aux = edit_filename(doc, new_ext='.pyx') src2 = os.path.normpath(aux.replace(doc_dir, top_dir)) if (src1 not in all_sources) and (src2 not in all_sources): output('remove: %s' % doc.replace(cwd, '')) if not options.dry_run: os.remove(doc) output('...done') output('creating missing rst files in "%s"...' % doc_dir) for src in sorted(all_sources): aux = edit_filename(src, new_ext='.rst') doc = os.path.normpath(aux.replace(top_dir, doc_dir)) if doc not in docs: output('create: %s' % doc.replace(cwd, '')) if not options.dry_run: mod_filename = src.replace(top_dir + os.path.sep, '') mod_name = mod_filename.replace(os.path.sep, '.') mod_name = edit_filename(mod_name, new_ext='') if mod_name.startswith('sfepy'): # Module. title = mod_name + ' module' else: # Script. title = mod_filename + ' script' mod_name = mod_name.split('.')[-1] underlines = '=' * len(title) contents = doc_template % (title, underlines, mod_name) ensure_path(doc) fd = open(doc, 'w') fd.write(contents) fd.close() output('...done')
def main(): parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('-n', '--dry-run', action='store_true', dest='dry_run', default=False, help=help['dry_run']) parser.add_argument('doc_dir') parser.add_argument('top_dir') options = parser.parse_args() doc_dir, top_dir = [ os.path.realpath(ii) for ii in [options.doc_dir, options.top_dir] ] docs = set(ii for ii in locate_files('*.rst', root_dir=doc_dir)) sources = set( ii for ii in locate_files('*.py', root_dir=os.path.join(top_dir, 'sfepy')) if os.path.basename(ii) not in omits) sources.update(ii for ii in locate_files( '*.pyx', root_dir=os.path.join(top_dir, 'sfepy')) if os.path.basename(ii) not in omits_pyx) scripts = set(ii for ii in locate_files( '*.py', root_dir=os.path.join(top_dir, 'script')) if os.path.basename(ii) not in omits) top_scripts = set( os.path.realpath(ii) for ii in fnmatch.filter(os.listdir(top_dir), '*.py') if os.path.basename(ii) not in omits) all_sources = set() all_sources.update(sources, scripts, top_scripts) cwd = os.path.realpath(os.path.curdir) + os.path.sep output.prefix = 'smd:' output('removing unneeded rst files in "%s"...' % doc_dir) for doc in sorted(docs): aux = edit_filename(doc, new_ext='.py') src1 = os.path.normpath(aux.replace(doc_dir, top_dir)) aux = edit_filename(doc, new_ext='.pyx') src2 = os.path.normpath(aux.replace(doc_dir, top_dir)) if (src1 not in all_sources) and (src2 not in all_sources): output('remove: %s' % doc.replace(cwd, '')) if not options.dry_run: os.remove(doc) output('...done') output('creating missing rst files in "%s"...' % doc_dir) for src in sorted(all_sources): aux = edit_filename(src, new_ext='.rst') doc = os.path.normpath(aux.replace(top_dir, doc_dir)) if doc not in docs: output('create: %s' % doc.replace(cwd, '')) if not options.dry_run: mod_filename = src.replace(top_dir + os.path.sep, '') mod_name = mod_filename.replace(os.path.sep, '.') mod_name = edit_filename(mod_name, new_ext='') if mod_name.startswith('sfepy'): # Module. title = mod_name + ' module' else: # Script. title = mod_filename + ' script' mod_name = mod_name.split('.')[-1] underlines = '=' * len(title) contents = doc_template % (title, underlines, mod_name) ensure_path(doc) fd = open(doc, 'w') fd.write(contents) fd.close() output('...done')
def main(): parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument("--version", action="version", version="%(prog)s " + sfepy.__version__) parser.add_argument("-m", "--mesh", action="store_true", dest="save_mesh", default=False, help="save surface mesh") parser.add_argument("-n", "--no-surface", action="store_true", dest="no_surface", default=False, help="do not output surface [default: %(default)s]") parser.add_argument('filename_in', help="'-' is for stdin") parser.add_argument('filename_out', help="'-' is for stdout") options = parser.parse_args() filename_in = options.filename_in filename_out = options.filename_out if (filename_in == '-'): file_in = sys.stdin else: file_in = open(filename_in, "r") mesh = Mesh.from_file(filename_in) if (filename_in != '-'): file_in.close() domain = FEDomain('domain', mesh) if options.save_mesh: region = domain.create_region('surf', 'vertices of surface', 'facet') surf_mesh = Mesh.from_region(region, mesh, localize=True, is_surface=True) aux = edit_filename(filename_in, prefix='surf_', new_ext='.mesh') surf_mesh.write(aux, io='auto') if domain.has_faces(): domain.fix_element_orientation() lst, surf_faces = get_surface_faces(domain) if options.no_surface: return gr_s = surface_graph(surf_faces, mesh.n_nod) n_comp, comps = surface_components(gr_s, surf_faces) output('number of surface components:', n_comp) ccs, comps = comps, nm.zeros((0, 1), nm.int32) for cc in ccs: comps = nm.concatenate((comps, cc[:, nm.newaxis]), 0) out = nm.concatenate((lst, comps), 1) if (filename_out == '-'): file_out = sys.stdout else: file_out = open(filename_out, "w") for row in out: file_out.write('%d %d %d\n' % (row[0], row[1], row[2])) if (filename_out != '-'): file_out.close()
def main(): parser = OptionParser(usage=usage, version="%prog " + sfepy.__version__) parser.add_option("-m", "--mesh", action="store_true", dest="save_mesh", default=False, help="save surface mesh") parser.add_option("-n", "--no-surface", action="store_true", dest="no_surface", default=False, help="do not output surface [default: %default]") (options, args) = parser.parse_args() if (len(args) == 2): filename_in = args[0]; filename_out = args[1]; else: parser.print_help(), return if (filename_in == '-'): file_in = sys.stdin else: file_in = open(filename_in, "r"); mesh = Mesh.from_file(filename_in) if (filename_in != '-'): file_in.close() domain = FEDomain('domain', mesh) if options.save_mesh: region = domain.create_region('surf', 'vertices of surface', 'facet') surf_mesh = Mesh.from_region(region, mesh, localize=True, is_surface=True) aux = edit_filename(filename_in, prefix='surf_', new_ext='.mesh') surf_mesh.write(aux, io='auto') if domain.has_faces(): domain.fix_element_orientation() lst, surf_faces = get_surface_faces(domain) if options.no_surface: return gr_s = surface_graph(surf_faces, mesh.n_nod) n_comp, comps = surface_components(gr_s, surf_faces) output('number of surface components:', n_comp) ccs, comps = comps, nm.zeros((0,1), nm.int32) for cc in ccs: comps = nm.concatenate((comps, cc[:,nm.newaxis]), 0) out = nm.concatenate((lst, comps), 1) if (filename_out == '-'): file_out = sys.stdout else: file_out = open(filename_out, "w"); for row in out: file_out.write('%d %d %d\n' % (row[0], row[1], row[2])) if (filename_out != '-'): file_out.close()
def save_state(self, filename, state=None, out=None, fill_value=None, post_process_hook=None, linearization=None, file_per_var=False, **kwargs): """ Parameters ---------- file_per_var : bool or None If True, data of each variable are stored in a separate file. If None, it is set to the application option value. linearization : Struct or None The linearization configuration for higher order approximations. If its kind is 'adaptive', `file_per_var` is assumed True. """ linearization = get_default(linearization, self.linearization) if linearization.kind != 'adaptive': file_per_var = get_default(file_per_var, self.file_per_var) else: file_per_var = True extend = not file_per_var if (out is None) and (state is not None): out = state.create_output_dict(fill_value=fill_value, extend=extend, linearization=linearization) if post_process_hook is not None: out = post_process_hook(out, self, state, extend=extend) if linearization.kind == 'adaptive': for key, val in out.iteritems(): mesh = val.get('mesh', self.domain.mesh) aux = io.edit_filename(filename, suffix='_' + val.var_name) mesh.write(aux, io='auto', out={key : val}, float_format=self.float_format, **kwargs) if hasattr(val, 'levels'): output('max. refinement per group:', val.levels) elif file_per_var: meshes = {} if self.equations is None: varnames = {} for key, val in out.iteritems(): varnames[val.var_name] = 1 varnames = varnames.keys() outvars = self.create_variables(varnames) itervars = outvars.__iter__ else: itervars = self.equations.variables.iter_state for var in itervars(): rname = var.field.region.name if meshes.has_key(rname): mesh = meshes[rname] else: mesh = Mesh.from_region(var.field.region, self.domain.mesh, localize=True, is_surface=var.is_surface) meshes[rname] = mesh vout = {} for key, val in out.iteritems(): try: if val.var_name == var.name: vout[key] = val except AttributeError: msg = 'missing var_name attribute in output!' raise ValueError(msg) aux = io.edit_filename(filename, suffix='_' + var.name) mesh.write(aux, io='auto', out=vout, float_format=self.float_format, **kwargs) else: mesh = out.pop('__mesh__', self.domain.mesh) mesh.write(filename, io='auto', out=out, float_format=self.float_format, **kwargs)
def main(): parser = OptionParser(usage=usage, version="%prog " + sfepy.__version__) parser.add_option("-m", "--mesh", action="store_true", dest="save_mesh", default=False, help="save surface mesh") parser.add_option("-n", "--no-surface", action="store_true", dest="no_surface", default=False, help="do not output surface [default: %default]") (options, args) = parser.parse_args() if (len(args) == 2): filename_in = args[0] filename_out = args[1] else: parser.print_help(), return if (filename_in == '-'): file_in = sys.stdin else: file_in = open(filename_in, "r") mesh = Mesh.from_file(filename_in) if (filename_in != '-'): file_in.close() domain = FEDomain('domain', mesh) if options.save_mesh: region = domain.create_region('surf', 'vertices of surface', 'facet') surf_mesh = Mesh.from_region(region, mesh, localize=True, is_surface=True) aux = edit_filename(filename_in, prefix='surf_', new_ext='.mesh') surf_mesh.write(aux, io='auto') if domain.has_faces(): domain.fix_element_orientation() lst, surf_faces = get_surface_faces(domain) if options.no_surface: return gr_s = surface_graph(surf_faces, mesh.n_nod) n_comp, comps = surface_components(gr_s, surf_faces) output('number of surface components:', n_comp) ccs, comps = comps, nm.zeros((0, 1), nm.int32) for cc in ccs: comps = nm.concatenate((comps, cc[:, nm.newaxis]), 0) out = nm.concatenate((lst, comps), 1) if (filename_out == '-'): file_out = sys.stdout else: file_out = open(filename_out, "w") for row in out: file_out.write('%d %d %d\n' % (row[0], row[1], row[2])) if (filename_out != '-'): file_out.close()
def generate_probes(filename_input, filename_results, options, conf=None, problem=None, probes=None, labels=None, probe_hooks=None): """ Generate probe figures and data files. """ if conf is None: required, other = get_standard_keywords() conf = ProblemConf.from_file(filename_input, required, other) opts = conf.options if options.auto_dir: output_dir = opts.get_('output_dir', '.') filename_results = os.path.join(output_dir, filename_results) output('results in: %s' % filename_results) io = MeshIO.any_from_filename(filename_results) step = options.step if options.step >= 0 else io.read_last_step() all_data = io.read_data(step) output('loaded:', all_data.keys()) output('from step:', step) if options.only_names is None: data = all_data else: data = {} for key, val in all_data.iteritems(): if key in options.only_names: data[key] = val if problem is None: problem = ProblemDefinition.from_conf(conf, init_equations=False, init_solvers=False) if probes is None: gen_probes = conf.get_function(conf.options.gen_probes) probes, labels = gen_probes(problem) if probe_hooks is None: probe_hooks = {None : conf.get_function(conf.options.probe_hook)} if options.output_filename_trunk is None: options.output_filename_trunk = problem.ofn_trunk filename_template = options.output_filename_trunk \ + ('_%%d.%s' % options.output_format) if options.same_dir: filename_template = os.path.join(os.path.dirname(filename_results), filename_template) output_dir = os.path.dirname(filename_results) for ip, probe in enumerate(probes): output(ip, probe.name) probe.set_options(close_limit=options.close_limit) for key, probe_hook in probe_hooks.iteritems(): out = probe_hook(data, probe, labels[ip], problem) if out is None: continue if isinstance(out, tuple): fig, results = out else: fig = out if key is not None: filename = filename_template % (key, ip) else: filename = filename_template % ip if fig is not None: if isinstance(fig, dict): for fig_name, fig_fig in fig.iteritems(): fig_filename = edit_filename(filename, suffix='_' + fig_name) fig_fig.savefig(fig_filename) output('figure ->', os.path.normpath(fig_filename)) else: fig.savefig(filename) output('figure ->', os.path.normpath(filename)) if results is not None: txt_filename = edit_filename(filename, new_ext='.txt') write_results(txt_filename, probe, results) output('data ->', os.path.normpath(txt_filename))
def generate_probes(filename_input, filename_results, options, conf=None, problem=None, probes=None, labels=None, probe_hooks=None): """ Generate probe figures and data files. """ if conf is None: required, other = get_standard_keywords() conf = ProblemConf.from_file(filename_input, required, other) opts = conf.options if options.auto_dir: output_dir = opts.get_('output_dir', '.') filename_results = os.path.join(output_dir, filename_results) output('results in: %s' % filename_results) io = MeshIO.any_from_filename(filename_results) step = options.step if options.step >= 0 else io.read_last_step() all_data = io.read_data(step) output('loaded:', list(all_data.keys())) output('from step:', step) if options.only_names is None: data = all_data else: data = {} for key, val in six.iteritems(all_data): if key in options.only_names: data[key] = val if problem is None: problem = Problem.from_conf(conf, init_equations=False, init_solvers=False) if probes is None: gen_probes = conf.get_function(conf.options.gen_probes) probes, labels = gen_probes(problem) if probe_hooks is None: probe_hooks = {None: conf.get_function(conf.options.probe_hook)} if options.output_filename_trunk is None: options.output_filename_trunk = problem.ofn_trunk filename_template = options.output_filename_trunk \ + ('_%%d.%s' % options.output_format) if options.same_dir: filename_template = os.path.join(os.path.dirname(filename_results), filename_template) output_dir = os.path.dirname(filename_results) for ip, probe in enumerate(probes): output(ip, probe.name) probe.set_options(close_limit=options.close_limit) for key, probe_hook in six.iteritems(probe_hooks): out = probe_hook(data, probe, labels[ip], problem) if out is None: continue if isinstance(out, tuple): fig, results = out else: fig = out if key is not None: filename = filename_template % (key, ip) else: filename = filename_template % ip if fig is not None: if isinstance(fig, dict): for fig_name, fig_fig in six.iteritems(fig): fig_filename = edit_filename(filename, suffix='_' + fig_name) fig_fig.savefig(fig_filename) output('figure ->', os.path.normpath(fig_filename)) else: fig.savefig(filename) output('figure ->', os.path.normpath(filename)) if results is not None: txt_filename = edit_filename(filename, new_ext='.txt') write_results(txt_filename, probe, results) output('data ->', os.path.normpath(txt_filename))
def main(): parser = OptionParser(usage=usage, version="%prog " + sfepy.__version__) parser.add_option("-m", "--mesh", action="store_true", dest="save_mesh", default=True, help="save surface mesh [default: %default]") parser.add_option("-n", "--no-surface", action="store_true", dest="no_surface", default=False, help="do not output surface [default: %default]") (options, args) = parser.parse_args() if (len(args) == 2): filename_in = args[0] filename_out = args[1] else: parser.print_help(), return if (filename_in == '-'): file_in = sys.stdin else: file_in = open(filename_in, "r") mesh = Mesh.from_file(filename_in) if (filename_in != '-'): file_in.close() domain = Domain('domain', mesh) domain.setup_groups() if domain.has_faces(): domain.fix_element_orientation() domain.setup_facets(create_edges=False) lst, surf_faces = domain.surface_faces() surf_mesh = Mesh.from_surface(surf_faces, mesh) if options.save_mesh: aux = edit_filename(filename_in, prefix='surf_', new_ext='.mesh') surf_mesh.write(aux, io='auto') if options.no_surface: return gr_s = surface_graph(surf_faces, mesh.n_nod) ## import sfepy.base.plotutils as plu ## plu.spy( gr_s ) ## plu.pylab.show() n_comp, comps = surface_components(gr_s, surf_faces) # print 'components:', n_comp ccs, comps = comps, nm.zeros((0, 1), nm.int32) for cc in ccs: comps = nm.concatenate((comps, cc[:, nm.newaxis]), 0) out = nm.concatenate((lst, comps), 1) if (filename_out == '-'): file_out = sys.stdout else: file_out = open(filename_out, "w") for row in out: file_out.write('%d %d %d %d\n' % (row[0], row[1], row[2], row[3])) if (filename_out != '-'): file_out.close()
def save_state(self, filename, state=None, out=None, fill_value=None, post_process_hook=None, linearization=None, file_per_var=False, **kwargs): """ Parameters ---------- file_per_var : bool or None If True, data of each variable are stored in a separate file. If None, it is set to the application option value. linearization : Struct or None The linearization configuration for higher order approximations. If its kind is 'adaptive', `file_per_var` is assumed True. """ linearization = get_default(linearization, self.linearization) if linearization.kind != 'adaptive': file_per_var = get_default(file_per_var, self.file_per_var) else: file_per_var = True extend = not file_per_var if (out is None) and (state is not None): out = state.create_output_dict(fill_value=fill_value, extend=extend, linearization=linearization) if post_process_hook is not None: out = post_process_hook(out, self, state, extend=extend) if linearization.kind == 'adaptive': for key, val in out.iteritems(): mesh = val.get('mesh', self.domain.mesh) aux = io.edit_filename(filename, suffix='_' + val.var_name) mesh.write(aux, io='auto', out={key : val}, float_format=self.float_format, **kwargs) if hasattr(val, 'levels'): output('max. refinement per group:', val.levels) elif file_per_var: meshes = {} if self.equations is None: varnames = {} for key, val in out.iteritems(): varnames[val.var_name] = 1 varnames = varnames.keys() outvars = self.create_variables(varnames) itervars = outvars.__iter__ else: itervars = self.equations.variables.iter_state for var in itervars(): rname = var.field.region.name if meshes.has_key( rname ): mesh = meshes[rname] else: mesh = Mesh.from_region(var.field.region, self.domain.mesh, localize=True, is_surface=var.is_surface) meshes[rname] = mesh vout = {} for key, val in out.iteritems(): try: if val.var_name == var.name: vout[key] = val except AttributeError: msg = 'missing var_name attribute in output!' raise ValueError(msg) aux = io.edit_filename(filename, suffix='_' + var.name) mesh.write(aux, io='auto', out=vout, float_format=self.float_format, **kwargs) else: self.domain.mesh.write(filename, io='auto', out=out, float_format=self.float_format, **kwargs)
def generate_probes(filename_input, filename_results, options, conf=None, problem=None, probes=None, labels=None, probe_hooks=None): """ Generate probe figures and data files. """ if conf is None: required, other = get_standard_keywords() conf = ProblemConf.from_file(filename_input, required, other) opts = conf.options if options.auto_dir: output_dir = get_default_attr(opts, 'output_dir', '.') filename_results = os.path.join(output_dir, filename_results) output('results in: %s' % filename_results) io = MeshIO.any_from_filename(filename_results) all_data = io.read_data(options.step) output('loaded:', all_data.keys()) if options.only_names is None: data = all_data else: data = {} for key, val in all_data.iteritems(): if key in options.only_names: data[key] = val if problem is None: problem = ProblemDefinition.from_conf(conf, init_equations=False, init_solvers=False) if probes is None: gen_probes = conf.get_function(conf.options.gen_probes) probes, labels = gen_probes(problem) if probe_hooks is None: probe_hooks = {None: conf.get_function(conf.options.probe_hook)} if options.output_filename_trunk is None: options.output_filename_trunk = problem.ofn_trunk filename_template = options.output_filename_trunk \ + ('_%%d.%s' % options.output_format) if options.same_dir: filename_template = os.path.join(os.path.dirname(filename_results), filename_template) output_dir = os.path.dirname(filename_results) for ip, probe in enumerate(probes): output(ip, probe.name) probe.set_options(close_limit=options.close_limit) for key, probe_hook in probe_hooks.iteritems(): out = probe_hook(data, probe, labels[ip], problem) if out is None: continue if isinstance(out, tuple): fig, results = out else: fig = out if key is not None: filename = filename_template % (key, ip) else: filename = filename_template % ip if fig is not None: if isinstance(fig, dict): for fig_name, fig_fig in fig.iteritems(): fig_filename = edit_filename(filename, suffix='_' + fig_name) fig_fig.savefig(fig_filename) output('figure ->', os.path.normpath(fig_filename)) else: fig.savefig(filename) output('figure ->', os.path.normpath(filename)) if results is not None: txt_filename = edit_filename(filename, new_ext='.txt') fd = open(txt_filename, 'w') fd.write('\n'.join(probe.report()) + '\n') for key, res in results.iteritems(): pars, vals = res fd.write('\n# %s\n' % key) if vals.ndim == 1: aux = nm.hstack((pars[:, None], vals[:, None])) else: aux = nm.hstack((pars[:, None], vals)) nm.savetxt(fd, aux) fd.close() output('data ->', os.path.normpath(txt_filename))