Пример #1
0
    def __call__(self, volume, problem=None, data=None):
        problem = get_default(problem, self.problem)

        dim, sym = problem.get_dim(get_sym=True)

        filename = self.set_variables(None, 0, 0, 'filename', **data)
        ts = TimeStepper(*HDF5MeshIO(filename).read_time_stepper())

        coef = nm.zeros((ts.n_step, sym), dtype=self.dtype)

        term_mode = self.term_mode
        equations, variables = problem.create_evaluable(self.expression,
                                                        term_mode=term_mode)

        self.set_variables(variables, None, None, 'col', **data)

        for ii, (ir, ic) in enumerate(iter_sym(dim)):
            filename = self.set_variables(None, ir, ic, 'filename', **data)
            io = HDF5MeshIO(filename)
            for step, time in ts:
                self.set_variables(variables, io, step, 'row', **data)

                val = eval_equations(equations, variables,
                                     term_mode=term_mode)

                coef[step,ii] = val

        coef /= self._get_volume(volume)

        return coef
Пример #2
0
    def __call__(self, volume, problem=None, data=None):
        problem = get_default(problem, self.problem)

        filename = self.set_variables(None, None, None, 'filename', **data)
        io = HDF5MeshIO(filename)
        ts = TimeStepper(*io.read_time_stepper())

        coef = nm.zeros((ts.n_step, 1), dtype=self.dtype)

        term_mode = self.term_mode
        equations, variables = problem.create_evaluable(self.expression,
                                                        term_mode=term_mode)

        self.set_variables(variables, None, None, 'col', **data)

        for step, time in ts:
            self.set_variables(variables, io, step, 'row', **data)

            val = eval_equations(equations, variables,
                                 term_mode=term_mode)

            coef[step] = val

        coef /= self._get_volume(volume)

        return coef
Пример #3
0
    def __call__(self, volume, problem=None, data=None):
        expression, region_name, aux_eq = self.expression

        problem = get_default(problem, self.problem)
        problem.select_variables(self.variables)

        aux = self.get_filename(data)
        io = HDF5MeshIO(self.get_filename(data))
        ts = TimeStepper(*io.read_time_stepper())

        coef = nm.zeros((ts.n_step, 1), dtype=nm.float64)

        for step, time in ts:
            step_data = io.read_data(step)

            var_name = self.variables[0]
            c_name = problem.variables[var_name].primary_var_name
            omega = step_data[c_name].data
            problem.variables[var_name].set_data(omega)

            val1 = eval_term_op(None, expression, problem, call_mode='d_eval')

            pc = step_data[self.variables[3]].data
            val2 = eval_boundary_diff_vel_grad(problem, omega, pc, aux_eq,
                                               region_name)
            coef[step] = val1 + val2

        coef /= volume

        return coef
Пример #4
0
def get_correctors_from_file_hdf5(coefs_filename='coefs.h5', dump_names=None):

    if dump_names == None:
        coefs = Coefficients.from_file_hdf5(coefs_filename)
        if hasattr(coefs, 'save_names'):
            dump_names = coefs.save_names
        else:
            raise ValueError(' "filenames" coefficient must be used!')

    out = {}

    for key, val in six.iteritems(dump_names):
        if type(val) in [tuple, list]:
            h5name, corr_name = val
        else:
            h5name, corr_name = val, op.split(val)[-1]

        io = HDF5MeshIO(h5name + '.h5')
        data = io.read_data(0)
        dkeys = list(data.keys())
        corr = {}
        for dk in dkeys:
            corr[dk] = data[dk].data.reshape(data[dk].shape)

        out[corr_name] = corr

    return out
Пример #5
0
    def from_file_hdf5(filename, var_names):
        """TODO: do not read entire file, provide data on demand."""
        io = HDF5MeshIO(filename)
        ts = TimeStepper(*io.read_time_stepper())
        steps = nm.arange(ts.n_step, dtype=nm.int32)

        ths = io.read_variables_time_history(var_names, ts)

        objs = OneTypeList(History)
        for name, th in ths.iteritems():
            hist = History(name, steps=steps, times=ts.times, th=th)
            objs.append(hist)

        obj = Histories(objs, dt=ts.dt, name=' '.join(var_names))
        return obj
Пример #6
0
    def verify_correctors(self, sign, state0, filename, problem=None):

        problem = get_default(problem, self.problem)

        io = HDF5MeshIO(filename)
        ts = TimeStepper(*io.read_time_stepper())

        ts.set_step(0)
        problem.equations.init_time(ts)

        variables = self.problem.get_variables()

        vu, vp = self.dump_variables
        vdp = self.verify_variables[-1]

        p0 = sign * state0[vp]

        format = '====== time %%e (step %%%dd of %%%dd) ====='\
                 % ((ts.n_digit,) * 2)
        vv = variables
        ok = True
        for step, time in ts:
            output(format % (time, step + 1, ts.n_step))

            data = io.read_data(step)
            if step == 0:
                assert_(nm.allclose(data[vp].data, p0))

            state0 = problem.create_state()
            state0.set_full(data[vu].data, vu)
            state0.set_full(data[vp].data, vp)
            vv[vdp].set_data(data['d'+vp].data)

            problem.update_time_stepper(ts)
            state = problem.solve(state0)
            state, state0 = state(), state0()
            err = nla.norm(state - state0) / nla.norm(state0)
            output(state.min(), state.max())
            output(state0.min(), state0.max())
            output('>>>>>', err)

            ok = ok and (err < 1e-12)
            problem.advance(ts)

        return ok
Пример #7
0
def get_correctors_from_file_hdf5(coefs_filename='coefs.h5', dump_names=None):

    if dump_names == None:
        coefs = Coefficients.from_file_hdf5(coefs_filename)
        if hasattr(coefs, 'save_names'):
            dump_names = coefs.save_names
        else:
            raise ValueError(' "filenames" coefficient must be used!')

    out = {}

    for key, val in six.iteritems(dump_names):
        if type(val) in [tuple, list]:
            h5name, corr_name = val
        else:
            h5name, corr_name = val, op.split(val)[-1]

        io = HDF5MeshIO(h5name + '.h5')
        try:
            ts = io.read_time_stepper()
        except ValueError:
            ts = None

        if ts is None:
            data = io.read_data(0)
            dkeys = list(data.keys())
            corr = {}
            for dk in dkeys:
                corr[dk] = data[dk].data.reshape(data[dk].shape)

            out[corr_name] = corr
        else:
            n_step = ts[3]
            out[corr_name] = []
            for step in range(n_step):
                data = io.read_data(step)
                dkeys = list(data.keys())
                corr = {}
                for dk in dkeys:
                    corr[dk] = data[dk].data.reshape(data[dk].shape)

                out[corr_name].append(corr)
            out[corr_name + '_ts'] = ts

    return out
Пример #8
0
def get_correctors_from_file(coefs_filename='coefs.h5', dump_names=None):

    if dump_names == None:
        coefs = Coefficients.from_file_hdf5(coefs_filename)
        if hasattr(coefs, 'dump_names'):
            dump_names = coefs.dump_names
        else:
            raise ValueError(' "filenames" coefficient must be used!')

    out = {}

    for key, val in dump_names.iteritems():
        corr_name = op.split(val)[-1]
        io = HDF5MeshIO(val + '.h5')
        data = io.read_data(0)
        dkeys = data.keys()
        corr = {}
        for dk in dkeys:
            corr[dk] = data[dk].data.reshape(data[dk].shape)

        out[corr_name] = corr

    return out
Пример #9
0
    def test_hdf5_meshio(self):
        try:
            from igakit import igalib
        except ImportError:
            self.report('hdf5_meshio not-tested (missing igalib module)!')
            return True

        import tempfile
        import numpy as nm
        import scipy.sparse as sps
        from sfepy.discrete.fem.meshio import HDF5MeshIO
        from sfepy.base.base import Struct
        from sfepy.base.ioutils import Cached, Uncached, SoftLink, \
                                       DataSoftLink
        from sfepy.discrete.iga.domain import IGDomain
        from sfepy.discrete.iga.domain_generators import gen_patch_block_domain
        from sfepy.solvers.ts import TimeStepper
        from sfepy.discrete.fem import Mesh

        conf_dir = op.dirname(__file__)
        mesh0 = Mesh.from_file(data_dir +
                               '/meshes/various_formats/small3d.mesh',
                               prefix_dir=conf_dir)

        shape = [4, 4, 4]
        dims = [5, 5, 5]
        centre = [0, 0, 0]
        degrees = [2, 2, 2]

        nurbs, bmesh, regions = gen_patch_block_domain(dims,
                                                       shape,
                                                       centre,
                                                       degrees,
                                                       cp_mode='greville',
                                                       name='iga')
        ig_domain = IGDomain('iga', nurbs, bmesh, regions=regions)

        int_ar = nm.arange(4)

        data = {
            'list':
            range(4),
            'mesh1':
            mesh0,
            'mesh2':
            mesh0,
            'mesh3':
            Uncached(mesh0),
            'mesh4':
            SoftLink('/step0/__cdata/data/data/mesh2'),
            'mesh5':
            DataSoftLink('Mesh', '/step0/__cdata/data/data/mesh1/data'),
            'mesh6':
            DataSoftLink('Mesh', '/step0/__cdata/data/data/mesh2/data', mesh0),
            'mesh7':
            DataSoftLink('Mesh', '/step0/__cdata/data/data/mesh1/data', True),
            'iga':
            ig_domain,
            'cached1':
            Cached(1),
            'cached2':
            Cached(int_ar),
            'cached3':
            Cached(int_ar),
            'types': (True, False, None),
            'tuple': ('first string', 'druhý UTF8 řetězec'),
            'struct':
            Struct(double=nm.arange(4, dtype=float),
                   int=nm.array([2, 3, 4, 7]),
                   sparse=sps.csr_matrix(
                       nm.array([1, 0, 0, 5]).reshape((2, 2))))
        }

        with tempfile.NamedTemporaryFile(suffix='.h5', delete=False) as fil:
            io = HDF5MeshIO(fil.name)
            ts = TimeStepper(0, 1., 0.1, 10)

            io.write(fil.name,
                     mesh0, {
                         'cdata':
                         Struct(mode='custom', data=data, unpack_markers=False)
                     },
                     ts=ts)
            ts.advance()

            mesh = io.read()
            data['problem_mesh'] = DataSoftLink('Mesh', '/mesh', mesh)

            io.write(fil.name,
                     mesh0, {
                         'cdata':
                         Struct(mode='custom', data=data, unpack_markers=True)
                     },
                     ts=ts)

            cache = {'/mesh': mesh}
            fout = io.read_data(0, cache=cache)
            fout2 = io.read_data(1, cache=cache)
            out = fout['cdata']
            out2 = fout2['cdata']

            assert_(out['mesh7'] is out2['mesh7'],
                    'These two meshes should be in fact the same object')

            assert_(out['mesh6'] is out2['mesh6'],
                    'These two meshes should be in fact the same object')

            assert_(out['mesh5'] is not out2['mesh5'],
                    'These two meshes shouldn'
                    't be in fact the same object')

            assert_(out['mesh1'] is out['mesh2'],
                    'These two meshes should be in fact the same object')

            assert_(out['mesh1'] is out['mesh2'],
                    'These two meshes should be in fact the same object')

            assert_(out['mesh4'] is out['mesh2'],
                    'These two meshes should be in fact the same object')

            assert_(out['mesh5'] is not out['mesh2'],
                    'These two meshes shouldn'
                    't be in fact the same object')

            assert_(out['mesh6'] is out['mesh2'],
                    'These two meshes should be in fact the same object')

            assert_(out['mesh7'] is not out['mesh2'],
                    'These two meshes shouldn'
                    't be in fact the same object')

            assert_(out['mesh3'] is not out['mesh2'],
                    'These two meshes should be different objects')

            assert_(out['cached2'] is out['cached3'],
                    'These two array should be the same object')

            assert_(out2['problem_mesh'] is mesh,
                    'These two meshes should be the same objects')

            assert_(self._compare_meshes(out['mesh1'], mesh0),
                    'Failed to restore mesh')

            assert_(self._compare_meshes(out['mesh3'], mesh0),
                    'Failed to restore mesh')

            assert_((
                out['struct'].sparse == data['struct'].sparse).todense().all(),
                    'Sparse matrix restore failed')

            ts.advance()
            io.write(fil.name,
                     mesh0, {
                         'cdata':
                         Struct(mode='custom',
                                data=[
                                    DataSoftLink(
                                        'Mesh',
                                        '/step0/__cdata/data/data/mesh1/data',
                                        mesh0), mesh0
                                ])
                     },
                     ts=ts)
            out3 = io.read_data(2)['cdata']
            assert_(out3[0] is out3[1])

        os.remove(fil.name)

        #this property is not restored
        del data['iga'].nurbs.nurbs

        #not supporting comparison
        del data['iga']._bnf
        del out2['iga']._bnf

        #restoration of this property fails
        del data['iga'].vertex_set_bcs
        del out2['iga'].vertex_set_bcs

        #these soflink has no information how to unpack, so it must be
        #done manually
        data['mesh4'] = mesh0
        data['mesh5'] = mesh0
        data['mesh7'] = mesh0

        for key, val in six.iteritems(out2):
            self.report('comparing:', key)
            self.assert_equal(val, data[key])

        return True