Exemplo n.º 1
0
    def call(self, verbose=False, ret_all=None, itime=None, iiter=None):
        """
        Call the homogenization engine and compute the homogenized
        coefficients.

        Parameters
        ----------
        verbose : bool
            If True, print the computed coefficients.
        ret_all : bool or None
            If not None, it can be used to override the 'return_all' option.
            If True, also the dependencies are returned.
        time_tag: str
            The time tag used in file names.

        Returns
        -------
        coefs : Coefficients instance
            The homogenized coefficients.
        dependencies : dict
            The dependencies, if `ret_all` is True.
        """
        opts = self.app_options

        ret_all = get_default(ret_all, opts.return_all)

        if not hasattr(self, 'he'):
            volumes = {}
            if hasattr(opts, 'volumes') and (opts.volumes is not None):
                volumes.update(opts.volumes)
            elif hasattr(opts, 'volume') and (opts.volume is not None):
                volumes['total'] = opts.volume
            else:
                volumes['total'] = 1.0

            self.he = HomogenizationEngine(self.problem,
                                           self.options,
                                           volumes=volumes)

        if self.micro_coors is not None:
            self.he.set_micro_coors(self.update_micro_coors(ret_val=True))

        multiproc_mode = None
        if opts.multiprocessing and multi.use_multiprocessing:
            multiproc, multiproc_mode = multi.get_multiproc(mpi=opts.use_mpi)

            if multiproc_mode is not None:
                upd_var = self.app_options.mesh_update_variable
                if upd_var is not None:
                    uvar = self.problem.create_variables([upd_var])[upd_var]
                    uvar.field.mappings0 = multiproc.get_dict('mappings0',
                                                              soft_set=True)
                per.periodic_cache = multiproc.get_dict('periodic_cache',
                                                        soft_set=True)

        time_tag = ('' if itime is None else '_t%03d' % itime)\
            + ('' if iiter is None else '_i%03d' % iiter)

        aux = self.he(ret_all=ret_all, time_tag=time_tag)
        if ret_all:
            coefs, dependencies = aux
            # store correctors for coors update
            if opts.mesh_update_corrector is not None:
                self.updating_corrs =\
                    dependencies[opts.mesh_update_corrector]
        else:
            coefs = aux

        if coefs is not None:
            coefs = Coefficients(**coefs.to_dict())

            if verbose:
                prec = nm.get_printoptions()['precision']
                if hasattr(opts, 'print_digits'):
                    nm.set_printoptions(precision=opts.print_digits)
                print(coefs)
                nm.set_printoptions(precision=prec)

            ms_cache = self.micro_state_cache
            for ii in self.app_options.store_micro_idxs:
                key = self.get_micro_cache_key('coors', ii, itime)
                ms_cache[key] = self.micro_coors[ii, ...]

            coef_save_name = op.join(opts.output_dir, opts.coefs_filename)
            coefs.to_file_hdf5(coef_save_name + '%s.h5' % time_tag)
            coefs.to_file_txt(coef_save_name + '%s.txt' % time_tag,
                              opts.tex_names, opts.float_format)

        if ret_all:
            return coefs, dependencies
        else:
            return coefs
Exemplo n.º 2
0
def get_homog_coefs_nonlinear(ts, coor, mode, mtx_f=None,
                              term=None, problem=None,
                              iteration=None, **kwargs):
    if not (mode == 'qp'):
        return

    oprefix = output.prefix
    output.prefix = 'micro:'

    if not hasattr(problem, 'homogen_app'):
        required, other = get_standard_keywords()
        required.remove('equations')
        micro_file = problem.conf.options.micro_filename
        conf = ProblemConf.from_file(micro_file, required, other,
                                     verbose=False)
        options = Struct(output_filename_trunk=None)
        app = HomogenizationApp(conf, options, 'micro:',
                                n_micro=coor.shape[0], update_micro_coors=True)
        problem.homogen_app = app

        if hasattr(app.app_options, 'use_mpi') and app.app_options.use_mpi:
            multiproc, multiproc_mode = multi.get_multiproc(mpi=True)
            multi_mpi = multiproc if multiproc_mode == 'mpi' else None
        else:
            multi_mpi = None

        app.multi_mpi = multi_mpi

        if multi_mpi is not None:
            multi_mpi.master_send_task('init', (micro_file, coor.shape[0]))
    else:
        app = problem.homogen_app
        multi_mpi = app.multi_mpi

    def_grad = mtx_f(problem, term) if callable(mtx_f) else mtx_f
    if hasattr(problem, 'def_grad_prev'):
        rel_def_grad = la.dot_sequences(def_grad,
                                        nm.linalg.inv(problem.def_grad_prev),
                                        'AB')
    else:
        rel_def_grad = def_grad.copy()

    problem.def_grad_prev = def_grad.copy()
    app.setup_macro_deformation(rel_def_grad)

    if multi_mpi is not None:
        multi_mpi.master_send_task('calculate', (rel_def_grad, ts, iteration))

    coefs, deps = app(ret_all=True, itime=ts.step, iiter=iteration)

    if type(coefs) is tuple:
        coefs = coefs[0]

    out = {}
    for key, val in six.iteritems(coefs.__dict__):
        if isinstance(val, list):
            out[key] = nm.array(val)
        elif isinstance(val, dict):
            for key2, val2 in six.iteritems(val):
                out[key+'_'+key2] = nm.array(val2)

    for key in six.iterkeys(out):
        shape = out[key].shape
        if len(shape) == 1:
            out[key] = out[key].reshape(shape + (1, 1))
        elif len(shape) == 2:
            out[key] = out[key].reshape(shape + (1,))

    output.prefix = oprefix

    return out
Exemplo n.º 3
0
    def call(self, ret_all=False, time_tag=''):
        problem = self.problem
        opts = self.app_options

        # Some coefficients can require other coefficients - resolve their
        # order here.
        req_info = getattr(self.conf, opts.requirements, {})
        coef_info = getattr(self.conf, opts.coefs, {})
        coef_info = self.define_volume_coef(coef_info, self.volumes)

        is_store_filenames = coef_info.pop('filenames', None) is not None

        multiproc_mode = None
        if opts.multiprocessing and multi.use_multiprocessing:
            multiproc, multiproc_mode = multi.get_multiproc(mpi=opts.use_mpi)
            if multiproc_mode == 'mpi':
                HomogWorkerMulti = HomogenizationWorkerMultiMPI
            elif multiproc_mode == 'proc':
                HomogWorkerMulti = HomogenizationWorkerMulti
            else:
                multiproc_mode = None

        if multiproc_mode is not None:
            num_workers = multi.get_num_workers()
            # if self.micro_states is not None:
            #     n_micro = len(self.micro_states['coors'])
            #     if num_workers > n_micro:
            #         num_workers = n_micro
            worker = HomogWorkerMulti(num_workers)
            dependencies, save_names = \
                worker(problem, opts, self.post_process_hook,
                       req_info, coef_info, self.micro_states,
                       self.app_options.store_micro_idxs,
                       self.app_options.chunks_per_worker, time_tag)

        else:  # no multiprocessing
            worker = HomogenizationWorker()
            dependencies, save_names = \
                worker(problem, opts, self.post_process_hook,
                       req_info, coef_info, self.micro_states,
                       self.app_options.store_micro_idxs, time_tag)

        deps = {}

        if save_names is None and dependencies is not None:  # slave mode
            coefs = None
            for name in dependencies.keys():
                data = dependencies[name]
                if not name.startswith('c.'):
                    deps[name] = data
        else:
            coefs = Struct()
            for name in dependencies.keys():
                data = dependencies[name]
                if name.startswith('c.'):
                    coef_name = name[2:]
                    cstat = coef_info[coef_name].get('status', 'main')
                    # remove "auxiliary" coefs
                    if not cstat == 'auxiliary':
                        setattr(coefs, coef_name, data)
                else:
                    deps[name] = data

            # Store filenames of all requirements as a "coefficient".
            if is_store_filenames:
                for name in save_names.keys():
                    if '|multiprocessing_' in name:
                        mname = rm_multi(name)
                        if mname in save_names:
                            save_names[mname] += save_names[name]
                        else:
                            save_names[mname] = save_names[name]
                        del (save_names[name])

                if multiproc_mode == 'proc':
                    coefs.save_names = save_names._getvalue()
                else:
                    coefs.save_names = save_names

            if opts.coefs_info is not None:
                coefs.info = opts.coefs_info

        if ret_all:
            return coefs, deps
        else:
            return coefs
Exemplo n.º 4
0
    def call(self, verbose=False, ret_all=None, itime=None, iiter=None):
        """
        Call the homogenization engine and compute the homogenized
        coefficients.

        Parameters
        ----------
        verbose : bool
            If True, print the computed coefficients.
        ret_all : bool or None
            If not None, it can be used to override the 'return_all' option.
            If True, also the dependencies are returned.
        time_tag: str
            The time tag used in file names.

        Returns
        -------
        coefs : Coefficients instance
            The homogenized coefficients.
        dependencies : dict
            The dependencies, if `ret_all` is True.
        """
        opts = self.app_options

        ret_all = get_default(ret_all, opts.return_all)

        if not hasattr(self, 'he'):
            volumes = {}
            if hasattr(opts, 'volumes') and (opts.volumes is not None):
                volumes.update(opts.volumes)
            elif hasattr(opts, 'volume') and (opts.volume is not None):
                volumes['total'] = opts.volume
            else:
                volumes['total'] = 1.0

            self.he = HomogenizationEngine(self.problem, self.options,
                                           volumes=volumes)

        if self.micro_coors is not None:
            self.he.set_micro_coors(self.update_micro_coors(ret_val=True))

        multiproc_mode = None
        if opts.multiprocessing and multi.use_multiprocessing:
            multiproc, multiproc_mode = multi.get_multiproc(mpi=opts.use_mpi)

            if multiproc_mode is not None:
                upd_var = self.app_options.mesh_update_variable
                if upd_var is not None:
                    uvar = self.problem.create_variables([upd_var])[upd_var]
                    uvar.field.mappings0 = multiproc.get_dict('mappings0',
                                                              soft_set=True)
                per.periodic_cache = multiproc.get_dict('periodic_cache',
                                                        soft_set=True)

        time_tag = ('' if itime is None else '_t%03d' % itime)\
            + ('' if iiter is None else '_i%03d' % iiter)

        aux = self.he(ret_all=ret_all, time_tag=time_tag)
        if ret_all:
            coefs, dependencies = aux
            # store correctors for coors update
            if opts.mesh_update_corrector is not None:
                self.updating_corrs =\
                    dependencies[opts.mesh_update_corrector]
        else:
            coefs = aux

        if coefs is not None:
            coefs = Coefficients(**coefs.to_dict())

            if verbose:
                prec = nm.get_printoptions()['precision']
                if hasattr(opts, 'print_digits'):
                    nm.set_printoptions(precision=opts.print_digits)
                print(coefs)
                nm.set_printoptions(precision=prec)

            ms_cache = self.micro_state_cache
            for ii in self.app_options.store_micro_idxs:
                key = self.get_micro_cache_key('coors', ii, itime)
                ms_cache[key] = self.micro_coors[ii, ...]

            coef_save_name = op.join(opts.output_dir, opts.coefs_filename)
            coefs.to_file_hdf5(coef_save_name + '%s.h5' % time_tag)
            coefs.to_file_txt(coef_save_name + '%s.txt' % time_tag,
                              opts.tex_names,
                              opts.float_format)

        if ret_all:
            return coefs, dependencies
        else:
            return coefs
Exemplo n.º 5
0
Arquivo: engine.py Projeto: rc/sfepy
    def call(self, ret_all=False, time_tag=''):
        problem = self.problem
        opts = self.app_options

        # Some coefficients can require other coefficients - resolve their
        # order here.
        req_info = getattr(self.conf, opts.requirements, {})
        coef_info = getattr(self.conf, opts.coefs, {})
        coef_info = self.define_volume_coef(coef_info, self.volumes)

        is_store_filenames = coef_info.pop('filenames', None) is not None

        multiproc_mode = None
        if opts.multiprocessing and multi.use_multiprocessing:
            multiproc, multiproc_mode = multi.get_multiproc(mpi=opts.use_mpi)
            if multiproc_mode == 'mpi':
                HomogWorkerMulti = HomogenizationWorkerMultiMPI
            elif multiproc_mode == 'proc':
                HomogWorkerMulti = HomogenizationWorkerMulti
            else:
                multiproc_mode = None

        if multiproc_mode is not None:
            num_workers = multi.get_num_workers()
            worker = HomogWorkerMulti(num_workers)
            dependencies, save_names = \
                worker(problem, opts, self.post_process_hook,
                       req_info, coef_info, self.micro_coors,
                       self.app_options.store_micro_idxs,
                       self.app_options.chunks_per_worker, time_tag)

        else:  # no multiprocessing
            worker = HomogenizationWorker()
            dependencies, save_names = \
                worker(problem, opts, self.post_process_hook,
                       req_info, coef_info, self.micro_coors,
                       self.app_options.store_micro_idxs, time_tag)

        deps = {}

        if save_names is None and dependencies is not None:  # slave mode
            coefs = None
            for name in dependencies.keys():
                data = dependencies[name]
                if not name.startswith('c.'):
                    deps[name] = data
        else:
            coefs = Struct()
            for name in dependencies.keys():
                data = dependencies[name]
                if name.startswith('c.'):
                    coef_name = name[2:]
                    cstat = coef_info[coef_name].get('status', 'main')
                    # remove "auxiliary" coefs
                    if not cstat == 'auxiliary':
                        setattr(coefs, coef_name, data)
                else:
                    deps[name] = data

            # Store filenames of all requirements as a "coefficient".
            if is_store_filenames:
                for name in save_names.keys():
                    if '|multiprocessing_' in name:
                        mname = rm_multi(name)
                        if mname in save_names:
                            save_names[mname] += save_names[name]
                        else:
                            save_names[mname] = save_names[name]
                        del(save_names[name])

                if multiproc_mode == 'proc':
                    coefs.save_names = save_names._getvalue()
                else:
                    coefs.save_names = save_names


            if opts.coefs_info is not None:
                coefs.info = opts.coefs_info

        if ret_all:
            return coefs, deps
        else:
            return coefs