Пример #1
0
def create_function_from_metadata(pp, fieldname, metadata, saveformat):
    "Create a function from metadata"
    assert metadata['type'] == 'Function'

    # Load mesh
    if saveformat == 'hdf5':
        mesh = Mesh()
        hdf5file = HDF5File(mpi_comm_world(), os.path.join(pp.get_savedir(fieldname), fieldname+'.hdf5'), 'r')
        hdf5file.read(mesh, "Mesh", False)
        del hdf5file
    elif saveformat == 'xml' or saveformat == 'xml.gz':
        mesh = Mesh()
        hdf5file = HDF5File(mpi_comm_world(), os.path.join(pp.get_savedir(fieldname), "mesh.hdf5"), 'r')
        hdf5file.read(mesh, "Mesh", False)
        del hdf5file

    # Replace loaded mesh if same mesh is loaded previously
    mesh = MeshPool(mesh, tolerance=0.0)

    shape = eval(metadata["element_value_shape"])
    degree = eval(metadata["element_degree"])
    family = eval(metadata["element_family"])

    # Get space from existing function spaces if mesh is the same
    spaces = SpacePool(mesh)
    space = spaces.get_custom_space(family, degree, shape)

    return Function(space, name=fieldname)
Пример #2
0
def convert(msh_file, h5_file):
    '''Temporary version of convert from msh to h5'''
    root, _ = os.path.splitext(msh_file)
    assert os.path.splitext(msh_file)[1] == '.msh'
    assert os.path.splitext(h5_file)[1] == '.h5'

    # Get the xml mesh
    xml_file = '.'.join([root, 'xml'])
    subprocess.call(['dolfin-convert %s %s' % (msh_file, xml_file)], shell=True)
    # Success?
    assert os.path.exists(xml_file)

    mesh = Mesh(xml_file)
    out = HDF5File(mesh.mpi_comm(), h5_file, 'w')
    out.write(mesh, 'mesh')

    info('Mesh has %d cells' % mesh.num_cells())
    info('Mesh size %g %g' % (mesh.hmin(), mesh.hmax()))

    outputs = [mesh]
    # Save ALL data as facet_functions
    names = ('surfaces', 'volumes')
    for name, region in zip(names, ('facet_region.xml', 'physical_region.xml')):
        r_xml_file = '_'.join([root, region])

        f = MeshFunction('size_t', mesh, r_xml_file)
        out.write(f, name)
        
        outputs.append(f)
        
    return outputs
Пример #3
0
def convert(msh_file, h5_file):
    '''Convert msh file to h5_file'''
    root, _ = os.path.splitext(msh_file)
    assert os.path.splitext(msh_file)[1] == '.msh'
    assert os.path.splitext(h5_file)[1] == '.h5'

    # Get the xml mesh
    xml_file = '.'.join([root, 'xml'])
    subprocess.call(['dolfin-convert %s %s' % (msh_file, xml_file)],
                    shell=True)
    # Success?
    assert os.path.exists(xml_file)

    mesh = Mesh(xml_file)
    out = HDF5File(mesh.mpi_comm(), h5_file, 'w')
    out.write(mesh, 'mesh')

    for region in ('facet_region.xml', ):
        name, _ = region.split('_')
        r_xml_file = '_'.join([root, region])

        f = MeshFunction('size_t', mesh, r_xml_file)
        out.write(f, name)

    # Sucess?
    assert os.path.exists(h5_file)

    return mesh
Пример #4
0
def convert(msh_file):
    '''Temporary version of convertin from msh to h5'''
    root, _ = os.path.splitext(msh_file)
    assert os.path.splitext(msh_file)[1] == '.msh'

    # Get the xml mesh
    xml_file = '.'.join([root, 'xml'])

    # Convert to XML
    convert2xml(msh_file, xml_file)

    # Success?
    assert os.path.exists(xml_file)

    mesh = Mesh(xml_file)
    h5_file = '.'.join([root, 'h5'])
    out = HDF5File(mesh.mpi_comm(), h5_file, 'w')
    out.write(mesh, 'mesh')

    # Save ALL data as facet_functions
    data_sets = ('curves', 'surfaces', 'volumes')
    regions = ('curve_region.xml', 'facet_region.xml', 'volume_region.xml')

    for data_set, region in zip(data_sets, regions):
        r_xml_file = '_'.join([root, region])

        if os.path.exists(r_xml_file):
            f = MeshFunction('size_t', mesh, r_xml_file)
            out.write(f, data_set)
            # And clean
            os.remove(r_xml_file)
    # and clean
    os.remove(xml_file)

    return h5_file
Пример #5
0
def read_fenics_solution(filepath):
    from dolfin import (Mesh, XDMFFile, MeshValueCollection, cpp,
                        FunctionSpace, Function, HDF5File, MPI)
    mesh = Mesh()
    with XDMFFile("%s_triangle.xdmf" % filepath.split('.')[0]) as infile:
        infile.read(mesh)  # read the complete mesh

    #mvc_subdo = MeshValueCollection("size_t", mesh, mesh.geometric_dimension() - 1)
    #with XDMFFile("%s_triangle.xdmf" % filepath.split('.')[0]) as infile:
    #    infile.read(mvc_subdo, "subdomains")  # read the diferent subdomians
    #subdomains = cpp.mesh.MeshFunctionSizet(mesh, mvc_subdo)

    #mvc = MeshValueCollection("size_t", mesh, mesh.geometric_dimension() - 2)
    #with XDMFFile("%s_line.xdmf" % filepath.split('.')[0]) as infile:
    #    infile.read(mvc, "boundary_conditions")  # read the boundary conditions
    #boundary = cpp.mesh.MeshFunctionSizet(mesh, mvc)

    # Define function space and basis functions
    V = FunctionSpace(mesh, "CG", 1)
    U = Function(V)
    input_file = HDF5File(MPI.comm_world,
                          filepath.split('.')[0] + "_solution_field.h5", "r")
    input_file.read(U, "solution")
    input_file.close()

    dofs = V.tabulate_dof_coordinates().reshape(
        V.dim(),
        mesh.geometry().dim())  # coordinates of nodes
    U.set_allow_extrapolation(True)
    return U, mesh, dofs.shape[0]
Пример #6
0
def load_mesh(filename):
    """ Loads in the mesh specified by the argument filename. """
    info_cyan("Loading mesh: " + filename)
    mesh = Mesh()
    h5file = HDF5File(mesh.mpi_comm(), filename, "r")
    h5file.read(mesh, "mesh", False)
    h5file.close()
    return mesh
Пример #7
0
def load_mesh(filename, subdir="mesh", use_partition_from_file=False):
    """ Loads the mesh specified by the argument filename. """
    info_cyan("Loading mesh: " + filename)
    mesh = Mesh()
    h5file = HDF5File(mesh.mpi_comm(), filename, "r")
    h5file.read(mesh, subdir, use_partition_from_file)
    h5file.close()
    return mesh
Пример #8
0
def load_checkpoint(checkpointfolder, w_, w_1):
    if checkpointfolder:
        h5filename = os.path.join(checkpointfolder, "fields.h5")
        h5file = HDF5File(mpi_comm(), h5filename, "r")
        for field in w_:
            info_red("Loading subproblem: {}".format(field))
            h5file.read(w_[field], "{}/current".format(field))
            h5file.read(w_1[field], "{}/previous".format(field))
        h5file.close()
Пример #9
0
def load_checkpoint(checkpointfolder, w_, w_1):
    if checkpointfolder:
        h5filename = os.path.join(checkpointfolder, "fields.h5")
        h5file = HDF5File(mpi_comm_world(), h5filename, "r")
        for field in w_:
            info_red("Loading subproblem: " + field)
            h5file.read(w_[field], field + "/current")
            h5file.read(w_1[field], field + "/previous")
        h5file.close()
Пример #10
0
def read_h5(h5Path):
    mesh = Mesh()
    hdf = HDF5File(mesh.mpi_comm(), h5Path, 'r')
    hdf.read(mesh, '/mesh', False)
    subdomains = MeshFunction('size_t', mesh, 3)
    boundaries = MeshFunction('size_t', mesh, 2)

    hdf.read(subdomains, '/subdomains')
    hdf.read(boundaries, '/boundaries')

    return mesh, subdomains, boundaries
Пример #11
0
 def store_mesh(self, mesh, cell_domains=None, facet_domains=None):
     "Store mesh in casedir to mesh.hdf5 (dataset Mesh) in casedir."
     casedir = self.get_casedir()
     meshfile = HDF5File(mpi_comm_world(),
                         os.path.join(casedir, "mesh.hdf5"), 'w')
     meshfile.write(mesh, "Mesh")
     if cell_domains is not None:
         meshfile.write(cell_domains, "CellDomains")
     if facet_domains is not None:
         meshfile.write(facet_domains, "FacetDomains")
     del meshfile
Пример #12
0
    def _update_xml_gz_file(self, field_name, saveformat, data, timestep, t):
        "Create new xml.gz file for current timestep with new data."
        assert saveformat == "xml.gz"
        fullname, metadata = self._get_datafile_name(field_name, saveformat,
                                                     timestep)
        meshfile = os.path.join(self.get_savedir(field_name), "mesh.hdf5")
        if not os.path.isfile(meshfile):
            hdf5file = HDF5File(mpi_comm_world(), meshfile, 'w')
            hdf5file.write(data.function_space().mesh(), "Mesh")
            del hdf5file
        datafile = File(fullname)
        datafile << data

        return metadata
def save_output(eigenvectors, phi, e_density, potential):

    #writing to HDF file
    f = HDF5File("out.h5", "w")

    f.write(phi, 'phi')
    f.write(e_density, 'n(x)')
    f.write(potential, 'V(x)')

    i = 0
    while (i < len(eigenvectors)):
        name = 'eigenvector' + str(i)
        print eigenvectors[i]
        print phi
        print e_density
Пример #14
0
def init_from_restart(restart_folder, sys_comp, uc_comp, u_components, 
                      q_, q_1, q_2, **NS_namespace):
    """Initialize solution from checkpoint files """
    if restart_folder:
        for ui in sys_comp:
            filename = path.join(restart_folder, ui + '.h5')
            hdf5_file = HDF5File(mpi_comm_world(), filename, "r")
            hdf5_file.read(q_[ui].vector(), "/current", False)      
            q_[ui].vector().apply('insert')
            # Check for the solution at a previous timestep as well
            if ui in uc_comp:
                q_1[ui].vector().zero()
                q_1[ui].vector().axpy(1., q_[ui].vector())
                q_1[ui].vector().apply('insert')
                if ui in u_components:
                    hdf5_file.read(q_2[ui].vector(), "/previous", False)
                    q_2[ui].vector().apply('insert')
Пример #15
0
def load_h5_mesh(h5_file, scale_factor=None):
    '''Unpack to mesh, volumes and surfaces'''
    mesh = Mesh()
    h5 = HDF5File(mesh.mpi_comm(), h5_file, 'r')
    h5.read(mesh, 'mesh', False)
    # Convert units
    if scale_factor is not None:
        assert scale_factor > 0, "Scale factor must be a positive real number!"
        mesh.coordinates()[:] *= scale_factor

    surfaces = MeshFunction('size_t', mesh, mesh.topology().dim() - 1)
    h5.read(surfaces, 'surfaces')

    volumes = MeshFunction('size_t', mesh, mesh.topology().dim())
    h5.read(volumes, 'volumes')

    return mesh, volumes, surfaces
Пример #16
0
def as_pvd(h5_file):
    '''Store facet and cell function for pvd'''
    root, ext = os.path.splitext(h5_file)

    mesh = Mesh()
    hdf = HDF5File(mesh.mpi_comm(), h5_file, 'r')
    hdf.read(mesh, '/mesh', False)

    facet_markers = FacetFunction('size_t', mesh)
    hdf.read(facet_markers, '/facet_markers')

    cell_markers = CellFunction('size_t', mesh)
    hdf.read(cell_markers, '/cell_markers')

    File(root + 'facets' + '.pvd') << facet_markers
    File(root + 'volumes' + '.pvd') << cell_markers

    return True
Пример #17
0
def test_hdf5_save(mesh, casedir):
    spacepool = SpacePool(mesh)
    Q = spacepool.get_space(1, 0)
    V = spacepool.get_space(1, 1)

    mff = MockFunctionField(Q, dict(save=True, save_as="hdf5"))
    mvff = MockVectorFunctionField(V, dict(save=True, save_as="hdf5"))

    pp = PostProcessor(dict(casedir=casedir))
    pp.add_fields([mff, mvff])

    pp.update_all({}, 0.0, 0)
    pp.update_all({}, 0.1, 1)
    pp.update_all({}, 0.2, 2)
    pp.finalize_all()

    for mf, FS in [(mff, Q), (mvff, V)]:
        assert os.path.isdir(pp.get_savedir(mf.name))
        assert os.path.isfile(
            os.path.join(pp.get_savedir(mf.name), "metadata.db"))
        assert os.path.isfile(
            os.path.join(pp.get_savedir(mf.name), mf.name + ".hdf5"))

        md = shelve.open(os.path.join(pp.get_savedir(mf.name), "metadata.db"),
                         'r')
        assert 'hdf5' in md["0"]
        assert 'hdf5' in md["1"]
        assert 'hdf5' in md["2"]
        assert 'hdf5' in md['saveformats']

        assert md['saveformats'] == ['hdf5']
        md.close()

        assert len(os.listdir(pp.get_savedir(mf.name))) == 2

        # Read back
        hdf5file = HDF5File(
            mpi_comm_world(),
            os.path.join(pp.get_savedir(mf.name), mf.name + ".hdf5"), 'r')
        f = Function(FS)
        for i in ["0", "1", "2"]:
            hdf5file.read(f, mf.name + i)

        assert norm(f) == norm(pp.get(mf.name))
Пример #18
0
def save_checkpoint_solution_h5(tstep, q_, q_1, newfolder, u_components,
                                NS_parameters):
    """Overwrite solution in Checkpoint folder.

    For safety reasons, in case the solver is interrupted, take backup of
    solution first.

    Must be restarted using the same mesh-partitioning. This will be fixed
    soon. (MM)

    """
    checkpointfolder = path.join(newfolder, "Checkpoint")
    NS_parameters["num_processes"] = MPI.size(MPI.comm_world)
    if MPI.rank(MPI.comm_world) == 0:
        if path.exists(path.join(checkpointfolder, "params.dat")):
            system('cp {0} {1}'.format(
                path.join(checkpointfolder, "params.dat"),
                path.join(checkpointfolder, "params_old.dat")))
        f = open(path.join(checkpointfolder, "params.dat"), 'wb')
        pickle.dump(NS_parameters, f)

    MPI.barrier(MPI.comm_world)
    for ui in q_:
        h5file = path.join(checkpointfolder, ui + '.h5')
        oldfile = path.join(checkpointfolder, ui + '_old.h5')
        # For safety reasons...
        if path.exists(h5file):
            if MPI.rank(MPI.comm_world) == 0:
                system('cp {0} {1}'.format(h5file, oldfile))
        MPI.barrier(MPI.comm_world)
        ###
        newfile = HDF5File(MPI.comm_world, h5file, 'w')
        newfile.flush()
        newfile.write(q_[ui].vector(), '/current')
        if ui in u_components:
            newfile.write(q_1[ui].vector(), '/previous')
        if path.exists(oldfile):
            if MPI.rank(MPI.comm_world) == 0:
                system('rm {0}'.format(oldfile))
        MPI.barrier(MPI.comm_world)
    if MPI.rank(MPI.comm_world) == 0 and path.exists(
            path.join(checkpointfolder, "params_old.dat")):
        system('rm {0}'.format(path.join(checkpointfolder, "params_old.dat")))
Пример #19
0
def test_store_mesh(casedir):
    pp = PostProcessor(dict(casedir=casedir))

    from dolfin import (UnitSquareMesh, CellFunction, FacetFunction,
                        AutoSubDomain, Mesh, HDF5File, assemble, Expression,
                        ds, dx)

    # Store mesh
    mesh = UnitSquareMesh(6, 6)
    celldomains = CellFunction("size_t", mesh)
    celldomains.set_all(0)
    AutoSubDomain(lambda x: x[0] < 0.5).mark(celldomains, 1)

    facetdomains = FacetFunction("size_t", mesh)
    AutoSubDomain(lambda x, on_boundary: x[0] < 0.5 and on_boundary).mark(
        facetdomains, 1)

    pp.store_mesh(mesh, celldomains, facetdomains)

    # Read mesh back
    mesh2 = Mesh()
    f = HDF5File(mpi_comm_world(), os.path.join(pp.get_casedir(), "mesh.hdf5"),
                 'r')
    f.read(mesh2, "Mesh", False)

    celldomains2 = CellFunction("size_t", mesh2)
    f.read(celldomains2, "CellDomains")
    facetdomains2 = FacetFunction("size_t", mesh2)
    f.read(facetdomains2, "FacetDomains")

    e = Expression("1+x[1]", degree=1)

    dx1 = dx(1, domain=mesh, subdomain_data=celldomains)
    dx2 = dx(1, domain=mesh2, subdomain_data=celldomains2)
    C1 = assemble(e * dx1)
    C2 = assemble(e * dx2)
    assert abs(C1 - C2) < 1e-10

    ds1 = ds(1, domain=mesh, subdomain_data=facetdomains)
    ds2 = ds(1, domain=mesh2, subdomain_data=facetdomains2)
    F1 = assemble(e * ds1)
    F2 = assemble(e * ds2)
    assert abs(F1 - F2) < 1e-10
Пример #20
0
def convert(msh_file, h5_file, save_mvc=False):
    '''Temporary version of convertin from msh to h5'''
    root, _ = os.path.splitext(msh_file)
    assert os.path.splitext(msh_file)[1] == '.msh'
    assert os.path.splitext(h5_file)[1] == '.h5'

    # Get the xml mesh
    xml_file = '.'.join([root, 'xml'])
    subprocess.call(['dolfin-convert %s %s' % (msh_file, xml_file)], shell=True)
    # Success?
    assert os.path.exists(xml_file)

    mesh = Mesh(xml_file)
    out = HDF5File(mesh.mpi_comm(), h5_file, 'w')
    out.write(mesh, 'mesh')

    print('Mesh has %d cells' % mesh.num_cells())
    print('Mesh size %g %g' % (mesh.hmin(), mesh.hmax()))
    
    # Save ALL data as facet_functions
    names = ('surfaces', 'volumes')
    if not save_mvc:
        for name, region in zip(names, ('facet_region.xml', 'physical_region.xml')):
            r_xml_file = '_'.join([root, region])

            f = MeshFunction('size_t', mesh, r_xml_file)
            print('%d %s with 1' % (sum(1 for _ in SubsetIterator(f, 1)), name))
            out.write(f, name)

        return True

    for name, region in zip(names, ('facet_region.xml', 'physical_region.xml')):
        r_xml_file = '_'.join([root, region])

        f = MeshFunction('size_t', mesh, r_xml_file)
        # With mesh value collection we only store nonzero tags
        mvc = MeshValueCollection('size_t', mesh, f.dim())
        # Fill
        fill_mvc_from_mf(f, mvc)
        # And save
        out.write(mvc, name)
                    
    return True
Пример #21
0
    def __call__(self):
        """Load file"""
        #t0 = time()
        cbc_log(20, "Loading: "+self.filename+", Timestep: "+str(self.timestep))

        if self.saveformat == 'hdf5':
            hdf5file = HDF5File(mpi_comm_world(), self.filename, 'r')
            hdf5file.read(self.function, self.fieldname+str(self.timestep))
            del hdf5file
            data = self.function
        elif self.saveformat in ["xml", "xml.gz"]:
            V = self.function.function_space()
            self.function.assign(Function(V, self.filename))
            data = self.function
        elif self.saveformat == "shelve":
            shelvefile = shelve.open(self.filename, 'r')
            data = shelvefile[str(self.timestep)]
            shelvefile.close()
        cbc_log(20, "Loaded: "+self.filename+", Timestep: "+str(self.timestep))
        return data
Пример #22
0
def save_checkpoint(tstep, t, mesh, w_, w_1, newfolder, parameters):
    """ Save checkpoint files.

    A part of this is taken from the Oasis code."""
    checkpointfolder = os.path.join(newfolder, "Checkpoint")
    parameters["num_processes"] = MPI_size
    parameters["t_0"] = t
    parameters["tstep"] = tstep
    parametersfile = os.path.join(checkpointfolder, "parameters.dat")
    parametersfile_old = parametersfile + ".old"
    if mpi_is_root():
        # In case of failure, keep old file.
        if os.path.exists(parametersfile):
            os.system("mv {0} {1}".format(parametersfile,
                                          parametersfile_old))
        dump_parameters(parameters, parametersfile)

    mpi_barrier()
    h5filename = os.path.join(checkpointfolder, "fields.h5")
    h5filename_old = h5filename + ".old"
    # In case of failure, keep old file.
    if mpi_is_root() and os.path.exists(h5filename):
        os.system("mv {0} {1}".format(h5filename, h5filename_old))
    h5file = HDF5File(mpi_comm(), h5filename, "w")
    h5file.flush()
    info_red("Storing mesh")
    h5file.write(mesh, "mesh")
    for field in w_:
        info_red("Storing subproblem: " + field)
        mpi_barrier()
        h5file.write(w_[field], "{}/current".format(field))
        if field in w_1:
            h5file.write(w_1[field], "{}/previous".format(field))
        mpi_barrier()
    h5file.close()
    # Since program is still running, delete the old files.
    remove_safe(h5filename_old)
    mpi_barrier()
    remove_safe(parametersfile_old)
Пример #23
0
 def __init__(self, mpi_comm, mesh_dim, filename, rw_mode):
     self.h5_file = HDF5File(mpi_comm, filename + "_checkpoint.h5", rw_mode)
     self.xdmf_file = XDMFFile(mpi_comm, filename + ".xdmf")
Пример #24
0
    def _update_hdf5_file(self, field_name, saveformat, data, timestep, t):
        """Update hdf5 file with new data.

        This creates a hashed dataset within the dataset to save FunctionSpace
        information only once, and for all subsequent savings only the vector
        is saved and links are created to the FunctionSpace information.

        This ensures that the saving is fully compatible with restart and
        replay on an arbitrary number of processes.
        """
        assert saveformat == "hdf5"
        fullname, metadata = self._get_datafile_name(field_name, saveformat,
                                                     timestep)

        # Create "good enough" hash. This is done to avoid data corruption when restarted from
        # different number of processes, different distribution or different function space
        local_hash = sha1()
        local_hash.update(
            str(data.function_space().mesh().num_cells()).encode())
        local_hash.update(str(data.function_space().ufl_element()).encode())
        local_hash.update(str(data.function_space().dim()).encode())
        local_hash.update(str(MPI.size(mpi_comm_world())).encode())

        # Global hash (same on all processes), 10 digits long
        global_hash = MPI.sum(mpi_comm_world(), int(local_hash.hexdigest(),
                                                    16))
        global_hash = str(int(global_hash % 1e10)).zfill(10)

        #key = (field_name, saveformat)
        #datafile = self._datafile_cache.get(key)
        #if datafile is None:
        #    datafile = HDF5File(mpi_comm_world(), fullname, 'w')
        #    self._datafile_cache[key] = datafile

        # Open HDF5File
        if not os.path.isfile(fullname):
            datafile = HDF5File(mpi_comm_world(), fullname, 'w')
        else:
            datafile = HDF5File(mpi_comm_world(), fullname, 'a')

        # Write to hash-dataset if not yet done
        if not datafile.has_dataset(global_hash) or not datafile.has_dataset(
                global_hash + "/" + field_name):
            datafile.write(data, str(global_hash) + "/" + field_name)

        if not datafile.has_dataset("Mesh"):
            datafile.write(data.function_space().mesh(), "Mesh")

        # Write vector to file
        # TODO: Link vector when function has been written to hash
        datafile.write(data.vector(), field_name + str(timestep) + "/vector")

        # HDF5File.close is broken in 1.4
        if dolfin_version() == "1.4.0+":
            datafile.close()
        del datafile
        # Link information about function space from hash-dataset
        hdf5_link(fullname,
                  str(global_hash) + "/" + field_name + "/x_cell_dofs",
                  field_name + str(timestep) + "/x_cell_dofs")
        hdf5_link(fullname,
                  str(global_hash) + "/" + field_name + "/cell_dofs",
                  field_name + str(timestep) + "/cell_dofs")
        hdf5_link(fullname,
                  str(global_hash) + "/" + field_name + "/cells",
                  field_name + str(timestep) + "/cells")

        return metadata
Пример #25
0
    shift_origin_parser.add_argument('--no_shift_origin',
                                     dest='shift_origin',
                                     action='store_false')
    parser.set_defaults(shift_origin=True)

    args = parser.parse_args()

    # Some sanity
    root, ext = os.path.splitext(args.tile)
    assert args.m > 0 and args.n > 0
    assert ext == '.h5'

    shape = (args.m, args.n)

    # Load the tile mesh
    h5 = HDF5File(get_comm_world(), args.tile, 'r')
    tile = Mesh()
    h5.read(tile, 'mesh', False)

    # Shift and so
    x = tile.coordinates()
    xmin = x.min(axis=0)
    dx = x.max(axis=0) - xmin

    if args.shift_origin: x[:] -= xmin

    x[:] *= args.scale_x

    # Did it work?
    print(dx, 'vs', x.max(axis=0) - x.min(axis=0), xmin, x.min(axis=0))
Пример #26
0
def save_geometry_to_h5(mesh,
                        h5name,
                        h5group="",
                        markers=None,
                        markerfunctions={},
                        microstructure={},
                        local_basis={},
                        comm=mpi_comm_world,
                        other_functions={},
                        other_attributes={},
                        overwrite_file=False,
                        overwrite_group=True):
    """
    Save geometry and other geometrical functions to a HDF file.

    Parameters
    ----------
    mesh : :class:`dolfin.mesh`
        The mesh
    h5name : str
        Path to the file
    h5group : str
        Folder within the file. Default is "" which means in
        the top folder.
    markers : dict
        A dictionary with markers. See `get_markers`.
    fields : list
        A list of functions for the microstructure
    local_basis : list
        A list of functions for the crl basis
    meshfunctions : dict
        A dictionary with keys being the dimensions the the values
        beeing the meshfunctions.
    comm : :class:`dolfin.MPI`
        MPI communicator
    other_functions : dict
        Dictionary with other functions you want to save
    other_attributes: dict
        Dictionary with other attributes you want to save
    overwrite_file : bool
        If true, and the file exists, the file will be overwritten (default: False)
    overwrite_group : bool
        If true and h5group exist, the group will be overwritten.

    """
    h5name = os.path.splitext(h5name)[0] + ".h5"

    assert isinstance(mesh, Mesh)

    file_mode = "a" if os.path.isfile(h5name) and not overwrite_file else "w"

    # IF we should append the file but overwrite the group we need to
    # check that the group does not exist. If so we need to open it in
    # h5py and delete it.
    if file_mode == "a" and overwrite_group and h5group != "":
        check_h5group(h5name, h5group, delete=True, comm=comm)

    with HDF5File(comm, h5name, file_mode) as h5file:

        # Save mesh
        ggroup = "{}/geometry".format(h5group)
        mgroup = "{}/mesh".format(ggroup)
        h5file.write(mesh, mgroup)

        # Save markerfunctions
        df.begin(LogLevel.PROGRESS, "Saving marker functions.")
        for dim, key in enumerate(markerfunctions.keys()):
            mf = markerfunctions[key]
            if mf is not None:
                dgroup = "{}/mesh/meshfunction_{}".format(ggroup, dim)
                h5file.write(mf, dgroup)
        df.end()

        # Save markers
        df.begin(LogLevel.PROGRESS, "Saving markers.")
        for name, (marker, dim) in markers.items():
            for key_str in ["domain", "meshfunction"]:
                dgroup = "{}/mesh/{}_{}".format(ggroup, key_str, dim)

                if h5file.has_dataset(dgroup):
                    aname = "marker_name_{}".format(name)
                    h5file.attributes(dgroup)[aname] = marker
        df.end()

        # Save microstructure
        df.begin(LogLevel.PROGRESS, "Saving microstructure.")
        for key in microstructure.keys():
            ms = microstructure[key]
            if ms is not None:
                fgroup = "{}/microstructure".format(h5group)
                fsubgroup = "{}/{}".format(fgroup, key)
                h5file.write(microstructure[key], fsubgroup)
                h5file.attributes(fsubgroup)["name"] = key
                elm = ms.function_space().ufl_element()

        try:
            family, degree = elm.family(), elm.degree()
            fspace = "{}_{}".format(family, degree)
            h5file.attributes(fgroup)["space"] = fspace
            h5file.attributes(fgroup)["names"] = ":".join(
                microstructure.keys())
        except:
            pass
        df.end()

        # Save local basis
        df.begin(LogLevel.PROGRESS, "Saving local basis.")
        for key in local_basis.keys():
            ml = local_basis[key]
            if ml is not None:
                lgroup = "{}/local basis functions".format(h5group)
                h5file.write(ml, lgroup + "/{}".format(key))
                elm = ml.function_space().ufl_element()

        try:
            family, degree = elm.family(), elm.degree()
            lspace = "{}_{}".format(family, degree)
            h5file.attributes(lgroup)["space"] = lspace
            h5file.attributes(lgroup)["names"] = ":".join(local_basis.keys())
        except:
            pass
        df.end()

        # Save other functions
        df.begin(LogLevel.PROGRESS, "Saving other functions")
        for key in other_functions.keys():
            mo = other_functions[key]
            if mo is not None:
                fungroup = "/".join([h5group, key])
                h5file.write(mo, fungroup)
                elm = mo.function_space().ufl_element()

        try:
            family, degree, vsize = elm.family(), elm.degree(), elm.value_size(
            )
            fspace = "{}_{}".format(family, degree)
            h5file.attributes(fungroup)["space"] = fspace
            h5file.attributes(fungroup)["value_size"] = vsize
        except:
            pass
        df.end()

        # Save other attributes
        df.begin(LogLevel.PROGRESS, "Saving other attributes")
        for key in other_attributes:
            if isinstance(other_attributes[key], str) and isinstance(key, str):
                h5file.attributes(h5group)[key] = other_attributes[key]
            else:
                begin(
                    df.LogLevel.WARNING,
                    "Invalid attribute {} = {}".format(key,
                                                       other_attributes[key]))
                end()
        df.end()

    df.begin(df.LogLevel.INFO, "Geometry saved to {}".format(h5name))
    df.end()
Пример #27
0
    save_parser = parser.add_mutually_exclusive_group(required=False)
    save_parser.add_argument('--save', dest='save', action='store_true')
    save_parser.add_argument('--no-save', dest='save', action='store_false')

    parser.set_defaults(save=True)
    # Remove Xml and stuff
    parser.add_argument('--cleanup',
                        type=str,
                        nargs='+',
                        help='extensions to delete',
                        default=())
    args = parser.parse_args()

    # Protecting self
    assert not (set(('geo', '.geo')) & set(args.cleanup))

    if not args.output:
        args.output = '.'.join([os.path.splitext(args.input)[0], 'h5'])
    mesh = convert(args.input, args.output)

    if args.save:
        h5 = HDF5File(mpi_comm_world(), args.output, 'r')

        surfaces = MeshFunction('size_t', mesh, mesh.topology().dim() - 1, 0)
        h5.read(surfaces, 'facet')

        File('results/%s_surf.pvd' %
             os.path.splitext(args.input)[0]) << surfaces

    cleanup(exts=args.cleanup)
Пример #28
0
 def store(self, filename, function):
     with HDF5File(MPI.comm_self, filename, 'w') as fh:
         fh.write(function, self.function_name)
Пример #29
0
        def load(self, filename):
            function = self.function()
            with HDF5File(MPI.comm_self, filename, 'r') as fh:
                fh.read(function, self.function_name)

            return function
Пример #30
0
def load_geometry_from_h5(
    h5name,
    h5group="",
    fendo=None,
    fepi=None,
    include_sheets=True,
    comm=mpi_comm_world,
):
    """Load geometry and other mesh data from
    a h5file to an object.
    If the file contains muliple fiber fields
    you can spefify the angles, and if the file
    contais sheets and cross-sheets this can also
    be included

    :param str h5name: Name of the h5file
    :param str h5group: The group within the file
    :param int fendo: Helix fiber angle (endocardium) (if available)
    :param int fepi: Helix fiber angle (epicardium) (if available)
    :param bool include_sheets: Include sheets and cross-sheets
    :returns: An object with geometry data
    :rtype: object

    """
    # Set default groups
    ggroup = "{}/geometry".format(h5group)
    mgroup = "{}/mesh".format(ggroup)
    lgroup = "{}/local basis functions".format(h5group)
    fgroup = "{}/microstructure".format(h5group)

    if not os.path.isfile(h5name):
        raise IOError("File {} does not exist".format(h5name))

    # Check that the given file contains
    # the geometry in the given h5group
    if not check_h5group(h5name, mgroup, delete=False, comm=comm):
        msg = ("Error!\nGroup: '{}' does not exist in file:"
               "\n{}").format(mgroup, h5name)

        with h5py.File(h5name) as h:
            keys = h.keys()
        msg += "\nPossible values for the h5group are {}".format(keys)
        raise IOError(msg)

    # Dummy class to store attributes in
    class Geometry(object):
        pass

    geo = Geometry()

    with HDF5File(comm, h5name, "r") as h5file:

        # Load mesh
        mesh = Mesh(comm)
        h5file.read(mesh, mgroup, False)
        geo.mesh = mesh

        # Get mesh functions
        meshfunctions = ["vfun", "efun", "ffun", "cfun"]\
            if mesh.topology().dim() == 3 else ["vfun", "ffun", "cfun"]

        for dim, attr in enumerate(meshfunctions):
            dgroup = "{}/mesh/meshfunction_{}".format(ggroup, dim)
            mf = MeshFunction("size_t", mesh, dim, mesh.domains())

            if h5file.has_dataset(dgroup):
                h5file.read(mf, dgroup)
                setattr(geo, attr, mf)

        load_local_basis(h5file, lgroup, mesh, geo)
        load_microstructure(h5file, fgroup, mesh, geo, include_sheets)

        # Load the boundary markers
        markers = load_markers(h5file, mesh, ggroup, dgroup)
        geo.markers = markers

        origmeshgroup = "{}/original_geometry".format(h5group)
        if h5file.has_dataset(origmeshgroup):
            original_mesh = Mesh(comm)
            h5file.read(original_mesh, origmeshgroup, True)
            setattr(geo, "original_geometry", original_mesh)

    for attr in meshfunctions:
        if not hasattr(geo, attr):
            setattr(geo, attr, None)

    for attr in (["f0", "s0", "n0", "r0", "c0", "l0"]):
        if not hasattr(geo, attr):
            setattr(geo, attr, None)

    return geo