Example #1
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
Example #2
0
    def call(self, verbose=False, ret_all=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.

        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)

        volume = get_volume_from_options(opts, self.problem)

        for vk, vv in volume.iteritems():
            output('volume: %s = %.2f' % (vk, vv))

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

        aux = he( ret_all = ret_all)
        if ret_all:
            coefs, dependencies = aux
        else:
            coefs = aux

        coefs = Coefficients( **coefs.to_dict() )
        coefs.volume = volume

        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)

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

        if ret_all:
            return coefs, dependencies
        else:
            return coefs
Example #3
0
def get_homog_coefs_linear(ts, coor, mode,
                           micro_filename=None, regenerate=False,
                           coefs_filename=None, define_args=None):

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

    required, other = get_standard_keywords()
    required.remove( 'equations' )

    conf = ProblemConf.from_file(micro_filename, required, other,
                                 verbose=False, define_args=define_args)
    if coefs_filename is None:
        coefs_filename = conf.options.get('coefs_filename', 'coefs')
        coefs_filename = op.join(conf.options.get('output_dir', '.'),
                                 coefs_filename) + '.h5'

    if not regenerate:
        if op.exists( coefs_filename ):
            if not pt.is_hdf5_file( coefs_filename ):
                regenerate = True
        else:
            regenerate = True

    if regenerate:
        options = Struct( output_filename_trunk = None )

        app = HomogenizationApp( conf, options, 'micro:' )
        coefs = app()
        if type(coefs) is tuple:
            coefs = coefs[0]

        coefs.to_file_hdf5( coefs_filename )
    else:
        coefs = Coefficients.from_file_hdf5( coefs_filename )

    out = {}
    if mode == None:
        for key, val in six.iteritems(coefs.__dict__):
            out[key] = val

    elif mode == 'qp':
        for key, val in six.iteritems(coefs.__dict__):
            if type( val ) == nm.ndarray or type(val) == nm.float64:
                out[key] = nm.tile( val, (coor.shape[0], 1, 1) )
            elif type(val) == dict:
                for key2, val2 in six.iteritems(val):
                    if type(val2) == nm.ndarray or type(val2) == nm.float64:
                        out[key+'_'+key2] = \
                                          nm.tile(val2, (coor.shape[0], 1, 1))

    else:
        out = None

    output.prefix = oprefix

    return out
def load_coefs( filename ):
    coefs = Coefficients.from_file_hdf5( filename )

    try:
        options = import_file( coefs.filename ).options
        plot_info = options['plot_info']
        tex_names = options['tex_names']
    except:
        plot_info = coefs.plot_info
        tex_names = coefs.tex_names
        
    return coefs, plot_info, tex_names
Example #5
0
    def call(self, ret_all=False, verbose=False):
        opts = self.app_options

        volume = {}
        if opts.volumes is not None:
            for vk, vv in opts.volumes.iteritems():
                if 'value' in vv:
                    volume[vk] = nm.float64(vv['value'])
                else:
                    volume[vk] = Volume('volume', self.problem, vv)()
        else:
            if opts.volume is not None:
                if 'value' in opts.volume:
                    vol = nm.float64(opts.volume['value'])
                else:
                    vol = Volume('volume', self.problem, opts.volume)()
                volume['total'] = vol

        for vk, vv in volume.iteritems():
            output('volume: %s = %.2f' % (vk, vv))

        if hasattr(opts, 'return_all'):
            ret_all = opts.return_all

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

        aux = he( ret_all = ret_all)
        if ret_all:
            coefs, dependencies = aux
        else:
            coefs = aux

        coefs = Coefficients( **coefs.to_dict() )
        coefs.volume = volume

        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)

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

        if ret_all:
            return coefs, dependencies
        else:
            return coefs
Example #6
0
def recover_micro_hook(micro_filename,
                       region,
                       macro,
                       naming_scheme='step_iel',
                       recovery_file_tag=''):

    # Create a micro-problem instance.
    required, other = get_standard_keywords()
    required.remove('equations')
    pb = ProblemDefinition.from_conf_file(micro_filename,
                                          required=required,
                                          other=other,
                                          init_equations=False,
                                          init_solvers=False)

    coefs_filename = pb.conf.options.get_default_attr('coefs_filename',
                                                      'coefs')
    output_dir = pb.conf.options.get_default_attr('output_dir', '.')
    coefs_filename = op.join(output_dir, coefs_filename) + '.h5'

    # Coefficients and correctors
    coefs = Coefficients.from_file_hdf5(coefs_filename)
    corrs = get_correctors_from_file(dump_names=coefs.dump_names)

    recovery_hook = get_default_attr(pb.conf.options, 'recovery_hook', None)

    if recovery_hook is not None:
        recovery_hook = pb.conf.get_function(recovery_hook)

        aux = max(pb.domain.shape.n_gr, 2)
        format = get_print_info( aux, fill = '0' )[1] \
            + '_' + get_print_info( pb.domain.mesh.n_el, fill = '0' )[1]

        for ig, ii, iel in region.iter_cells():
            print 'ig: %d, ii: %d, iel: %d' % (ig, ii, iel)

            local_macro = {}
            for k, v in macro.iteritems():
                local_macro[k] = v[ii, 0]

            out = recovery_hook(pb, corrs, local_macro)

            # save data
            suffix = format % (ig, iel)
            micro_name = pb.get_output_name(extra='recovered_'\
                                            + recovery_file_tag + suffix)
            filename = op.join(output_dir, op.basename(micro_name))
            fpv = pb.conf.options.get_default_attr('file_per_var', False)
            pb.save_state(filename, out=out, file_per_var=fpv)
Example #7
0
def recover_micro_hook( micro_filename, region, macro,
                        naming_scheme = 'step_iel',
                        recovery_file_tag='' ):

    # Create a micro-problem instance.
    required, other = get_standard_keywords()
    required.remove( 'equations' )
    pb = ProblemDefinition.from_conf_file(micro_filename,
                                          required=required,
                                          other=other,
                                          init_equations=False,
                                          init_solvers=False)

    coefs_filename = pb.conf.options.get_default_attr('coefs_filename', 'coefs')
    output_dir = pb.conf.options.get_default_attr('output_dir', '.')
    coefs_filename = op.join(output_dir, coefs_filename) + '.h5'

    # Coefficients and correctors
    coefs = Coefficients.from_file_hdf5( coefs_filename )
    corrs = get_correctors_from_file( dump_names = coefs.dump_names ) 

    recovery_hook = get_default_attr( pb.conf.options,
                                      'recovery_hook', None )

    if recovery_hook is not None:
        recovery_hook = getattr( pb.conf.funmod, recovery_hook )

        aux = max(pb.domain.shape.n_gr, 2)
        format = get_print_info( aux, fill = '0' )[1] \
            + '_' + get_print_info( pb.domain.mesh.n_el, fill = '0' )[1]

        for ig, ii, iel in region.iter_cells():
            print 'ig: %d, ii: %d, iel: %d' % (ig, ii, iel)

            local_macro = {}
            for k, v in macro.iteritems():
                local_macro[k] = v[ii,0]

            out = recovery_hook( pb, corrs, local_macro )

            # save data
            suffix = format % (ig, iel)
            micro_name = pb.get_output_name(extra='recovered_'\
                                            + recovery_file_tag + suffix)
            filename = op.join(output_dir, op.basename(micro_name))
            fpv = pb.conf.options.get_default_attr('file_per_var', False)
            pb.save_state(filename, out=out,
                          file_per_var=fpv)
Example #8
0
def load_coefs(filename):
    coefs = Coefficients.from_file_hdf5(filename)

    try:
        options = import_file(coefs.filename).options
    except:
        options = None

    if options is not None:
        plot_info = options['plot_info']
        tex_names = options['tex_names']

    else:
        plot_info = get_default_attr(coefs, 'plot_info', {})
        tex_names = get_default_attr(coefs, 'tex_names', {})

    return coefs, plot_info, tex_names
Example #9
0
def load_coefs( filename ):
    coefs = Coefficients.from_file_hdf5( filename )

    try:
        options = import_file( coefs.filename ).options
    except:
        options = None

    if options is not None:
        plot_info = options['plot_info']
        tex_names = options['tex_names']

    else:
        plot_info = get_default_attr(coefs, 'plot_info', {})
        tex_names = get_default_attr(coefs, 'tex_names', {})

    return coefs, plot_info, tex_names
Example #10
0
def load_coefs(filename):
    coefs = Coefficients.from_file_hdf5(filename)

    try:
        options = import_file(coefs.filename).options
    except:
        options = None

    if options is not None:
        plot_info = options["plot_info"]
        tex_names = options["tex_names"]

    else:
        plot_info = coefs.get("plot_info", {})
        tex_names = coefs.get("tex_names", {})

    return coefs, plot_info, tex_names
Example #11
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
Example #12
0
def get_homog_coefs_linear( ts, coor, mode, region, ig,
                            micro_filename = None, regenerate = False ):

    oprefix = output.prefix
    output.prefix = 'micro:'
    
    required, other = get_standard_keywords()
    required.remove( 'equations' )
        
    conf = ProblemConf.from_file(micro_filename, required, other, verbose=False)

    coefs_filename = conf.options.get_default_attr('coefs_filename', 'coefs.h5')

    if not regenerate:
        if op.exists( coefs_filename ):
            if not pt.isHDF5File( coefs_filename ):
                regenerate = True
        else:
            regenerate = True

    if regenerate:
        options = Struct( output_filename_trunk = None )
            
        app = HomogenizationApp( conf, options, 'micro:' )
        coefs = app()

        coefs.to_file_hdf5( coefs_filename )
    else:
        coefs = Coefficients.from_file_hdf5( coefs_filename )

    out = {}
    if mode == None:
        for key, val in coefs.__dict__.iteritems():
            out[key] = val 
    elif mode == 'qp':
        for key, val in coefs.__dict__.iteritems():
            if type( val ) == nm.ndarray:
                out[key] = nm.tile( val, (coor.shape[0], 1, 1) )
    else:
        out = None

    output.prefix = oprefix

    return out
Example #13
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
Example #14
0
    def call( self, ret_all = False ):
        opts = self.app_options

        if 'value' in opts.volume:
            volume = nm.float64( opts.options.volume['value'] )
        else:
            volume = Volume( 'volume', self.problem, opts.volume )()
        output( 'volume: %.2f' % volume )
        
        if hasattr(opts.options, 'return_all'):
            ret_all = opts.options.return_all

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

        aux = he( ret_all = ret_all)
        if ret_all:
            coefs, dependencies = aux
        else:
            coefs = aux

        coefs = Coefficients( **coefs.to_dict() )
        coefs.volume = volume
        
        prec = nm.get_printoptions()[ 'precision']
        if hasattr( opts, 'print_digits' ):
            nm.set_printoptions( precision = opts.print_digits )
        print coefs
        nm.set_printoptions( precision = prec )
##        pause()

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

        if ret_all:
            return coefs, dependencies
        else:
            return coefs
Example #15
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
Example #16
0
    def call(self, ret_all=False, verbose=False):
        opts = self.app_options

        volume = get_volume_from_options(opts, self.problem)

        for vk, vv in volume.iteritems():
            output('volume: %s = %.2f' % (vk, vv))

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

        aux = he( ret_all = ret_all)
        if ret_all:
            coefs, dependencies = aux
        else:
            coefs = aux

        coefs = Coefficients( **coefs.to_dict() )
        coefs.volume = volume

        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)

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

        if ret_all:
            return coefs, dependencies
        else:
            return coefs
Example #17
0
# aluminium, in 1e+10 Pa
D_m = get_pars(dim, 5.898, 2.681)
density_m = 0.2799  # in 1e4 kg/m3

# epoxy, in 1e+10 Pa
D_c = get_pars(dim, 0.1798, 0.148)
density_c = 0.1142  # in 1e4 kg/m3

# lead, in 1e+10 Pa, does not matter
D_r = get_pars(dim, 4.074, 0.5556)
density_r = 1.1340  # in 1e4 kg/m3

mat_pars = Coefficients(D_m=D_m,
                        density_m=density_m,
                        D_c=D_c,
                        density_c=density_c,
                        D_r=D_r,
                        density_r=density_r)

region_selects = Struct(matrix=('elements of group 1', {}),
                        inclusion=('elements of group 2', {}))

corrs_save_names = {'evp': 'evp'}

evp_options = {
    'eigensolver': 'eig.sgscipy',
    'save_eig_vectors': (12, 0),
    'scale_epsilon': 1.0,
    'elasticity_contrast': 1.0,
}
Example #18
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
Example #19
0
def recover_micro_hook( micro_filename, region, macro,
                        naming_scheme = 'step_iel',
                        recovery_file_tag='' ):

    # Create a micro-problem instance.
    required, other = get_standard_keywords()
    required.remove( 'equations' )
    pb = Problem.from_conf_file(micro_filename, required=required, other=other,
                                init_equations=False, init_solvers=False)

    coefs_filename = pb.conf.options.get('coefs_filename', 'coefs')
    output_dir = pb.conf.options.get('output_dir', '.')
    coefs_filename = op.join(output_dir, coefs_filename) + '.h5'

    # Coefficients and correctors
    coefs = Coefficients.from_file_hdf5( coefs_filename )
    corrs = get_correctors_from_file( dump_names = coefs.dump_names ) 

    recovery_hook = pb.conf.options.get('recovery_hook', None)

    if recovery_hook is not None:
        recovery_hook = pb.conf.get_function(recovery_hook)

        aux = max(pb.domain.shape.n_gr, 2)
        format = get_print_info( aux, fill = '0' )[1] \
            + '_' + get_print_info( pb.domain.mesh.n_el, fill = '0' )[1]

        for ig, ii, iel in region.iter_cells():
            print 'ig: %d, ii: %d, iel: %d' % (ig, ii, iel)

            local_macro = {}
            for k, v in macro.iteritems():
                local_macro[k] = v[ii,0]

            out = recovery_hook( pb, corrs, local_macro )

            if ii == 0:
                new_keys = []
                new_data = {}
                new_idxs = []
                for k in local_macro.iterkeys():
                    if k not in macro:
                        new_keys.append(k)
                        new_data[k] = []

            new_idxs.append(ii)
            for jj in new_keys:
                new_data[jj].append(local_macro[jj])

            # save data
            if out is not None:
                suffix = format % (ig, iel)
                micro_name = pb.get_output_name(extra='recovered_'\
                                                + recovery_file_tag + suffix)
                filename = op.join(output_dir, op.basename(micro_name))
                fpv = pb.conf.options.get('file_per_var', False)
                pb.save_state(filename, out=out,
                              file_per_var=fpv)

        for jj in new_keys:
            lout = new_data[jj]
            macro[jj] = nm.zeros((nm.max(new_idxs) + 1,1) + lout[0].shape,
                                 dtype=lout[0].dtype)
            out = macro[jj]
            for kk, ii in enumerate(new_idxs):
                out[ii,0] = lout[kk]
Example #20
0
def recover_micro_hook_eps(micro_filename, region,
                           eval_var, nodal_values, const_values, eps0,
                           recovery_file_tag='',
                           define_args=None, verbose=False):
    # Create a micro-problem instance.
    required, other = get_standard_keywords()
    required.remove('equations')
    conf = ProblemConf.from_file(micro_filename, required, other,
                                 verbose=False, define_args=define_args)

    coefs_filename = conf.options.get('coefs_filename', 'coefs')
    output_dir = conf.options.get('output_dir', '.')
    coefs_filename = op.join(output_dir, coefs_filename) + '.h5'

    # Coefficients and correctors
    coefs = Coefficients.from_file_hdf5(coefs_filename)
    corrs = get_correctors_from_file(dump_names=coefs.dump_names)

    recovery_hook = conf.options.get('recovery_hook', None)

    if recovery_hook is not None:
        recovery_hook = conf.get_function(recovery_hook)
        pb = Problem.from_conf(conf, init_equations=False, init_solvers=False)

        # Get tiling of a given region
        rcoors = region.domain.mesh.coors[region.get_entities(0), :]
        rcmin = nm.min(rcoors, axis=0)
        rcmax = nm.max(rcoors, axis=0)
        nn = nm.round((rcmax - rcmin) / eps0)
        if nm.prod(nn) == 0:
            output('inconsistency in recovery region and microstructure size!')
            return

        cs = []
        for ii, n in enumerate(nn):
            cs.append(nm.arange(n) * eps0 + rcmin[ii])

        x0 = nm.empty((int(nm.prod(nn)), nn.shape[0]), dtype=nm.float64)
        for ii, icoor in enumerate(nm.meshgrid(*cs, indexing='ij')):
            x0[:, ii] = icoor.flatten()

        mesh = pb.domain.mesh
        coors, conn, outs, ndoffset = [], [], [], 0
        # Recover region
        mic_coors = (mesh.coors - mesh.get_bounding_box()[0, :]) * eps0
        evfield = eval_var.field

        output('recovering microsctructures...')
        tt = time.clock()
        output_fun = output.output_function
        output_level = output.level

        for ii, c0 in enumerate(x0):
            local_macro = {'eps0': eps0}
            local_coors = mic_coors + c0
            # Inside recovery region?
            v = nm.ones((evfield.region.entities[0].shape[0], 1))
            v[evfield.vertex_remap[region.entities[0]]] = 0
            no = nm.sum(v)
            aux = evfield.evaluate_at(local_coors, v)
            if (nm.sum(aux) / no) > 1e-3:
                continue

            output.level = output_level
            output('micro: %d' % ii)

            for k, v in six.iteritems(nodal_values):
                local_macro[k] = evfield.evaluate_at(local_coors, v)
            for k, v in six.iteritems(const_values):
                local_macro[k] = v

            output.set_output(quiet=not(verbose))
            outs.append(recovery_hook(pb, corrs, local_macro))
            output.output_function = output_fun
            coors.append(local_coors)
            conn.append(mesh.get_conn(mesh.descs[0]) + ndoffset)
            ndoffset += mesh.n_nod

    output('...done in %.2f s' % (time.clock() - tt))

    # Collect output variables
    outvars = {}
    for k, v in six.iteritems(outs[0]):
        if v.var_name in outvars:
            outvars[v.var_name].append(k)
        else:
            outvars[v.var_name] = [k]

    # Split output by variables/regions
    pvs = pb.create_variables(outvars.keys())
    outregs = {k: pvs[k].field.region.get_entities(-1) for k in outvars.keys()}
    nrve = len(coors)
    coors = nm.vstack(coors)
    ngroups = nm.tile(mesh.cmesh.vertex_groups.squeeze(), (nrve,))
    conn = nm.vstack(conn)
    cgroups = nm.tile(mesh.cmesh.cell_groups.squeeze(), (nrve,))

    # Get region mesh and data
    for k, cidxs in six.iteritems(outregs):
        gcidxs = nm.hstack([cidxs + mesh.n_el * ii for ii in range(nrve)])
        rconn = conn[gcidxs]
        remap = -nm.ones((coors.shape[0],), dtype=nm.int32)
        remap[rconn] = 1
        vidxs = nm.where(remap > 0)[0]
        remap[vidxs] = nm.arange(len(vidxs))
        rconn = remap[rconn]
        rcoors = coors[vidxs, :]

        out = {}
        for ifield in outvars[k]:
            data = [outs[ii][ifield].data for ii in range(nrve)]
            out[ifield] = Struct(name='output_data',
                                 mode=outs[0][ifield].mode,
                                 dofs=None,
                                 var_name=k,
                                 data=nm.vstack(data))

        micro_name = pb.get_output_name(extra='recovered%s_%s'
                                        % (recovery_file_tag, k))
        filename = op.join(output_dir, op.basename(micro_name))
        mesh_out = Mesh.from_data('recovery_%s' % k, rcoors, ngroups[vidxs],
                                  [rconn], [cgroups[gcidxs]], [mesh.descs[0]])
        mesh_out.write(filename, io='auto', out=out)
Example #21
0
def recover_micro_hook(micro_filename, region, macro,
                       naming_scheme='step_iel',
                       recovery_file_tag='',
                       define_args=None, verbose=False):
    # Create a micro-problem instance.
    required, other = get_standard_keywords()
    required.remove('equations')
    conf = ProblemConf.from_file(micro_filename, required, other,
                                 verbose=False, define_args=define_args)

    coefs_filename = conf.options.get('coefs_filename', 'coefs')
    output_dir = conf.options.get('output_dir', '.')
    coefs_filename = op.join(output_dir, coefs_filename) + '.h5'

    # Coefficients and correctors
    coefs = Coefficients.from_file_hdf5(coefs_filename)
    corrs = get_correctors_from_file(dump_names=coefs.dump_names)

    recovery_hook = conf.options.get('recovery_hook', None)

    if recovery_hook is not None:
        recovery_hook = conf.get_function(recovery_hook)
        pb = Problem.from_conf(conf, init_equations=False, init_solvers=False)

        format = get_print_info(pb.domain.mesh.n_el, fill='0')[1]

        output('recovering microsctructures...')
        tt = time.clock()
        output_fun = output.output_function
        output_level = output.level
        for ii, iel in enumerate(region.cells):
            output.level = output_level
            output('micro: %d (el=%d)' % (ii, iel))

            local_macro = {}
            for k, v in six.iteritems(macro):
                local_macro[k] = v[ii, 0]

            output.set_output(quiet=not(verbose))
            out = recovery_hook(pb, corrs, local_macro)
            output.output_function = output_fun

            if ii == 0:
                new_keys = []
                new_data = {}
                new_idxs = []
                for k in six.iterkeys(local_macro):
                    if k not in macro:
                        new_keys.append(k)
                        new_data[k] = []

            new_idxs.append(ii)
            for jj in new_keys:
                new_data[jj].append(local_macro[jj])

            # save data
            if out is not None:
                suffix = format % iel
                micro_name = pb.get_output_name(extra='recovered_'
                                                + recovery_file_tag + suffix)
                filename = op.join(output_dir, op.basename(micro_name))
                fpv = pb.conf.options.get('file_per_var', False)
                pb.save_state(filename, out=out,
                              file_per_var=fpv)

        output('...done in %.2f s' % (time.clock() - tt))

        for jj in new_keys:
            lout = new_data[jj]
            macro[jj] = nm.zeros((nm.max(new_idxs) + 1, 1) + lout[0].shape,
                                 dtype=lout[0].dtype)
            out = macro[jj]
            for kk, ii in enumerate(new_idxs):
                out[ii, 0] = lout[kk]
Example #22
0
    def call(self):
        """
        Construct and call the homogenization engine accoring to options.
        """
        options = self.options

        opts = self.app_options
        conf = self.problem.conf
        coefs_name = opts.coefs
        coef_info = conf.get(opts.coefs, None,
                             'missing "%s" in problem description!'
                             % opts.coefs)

        if options.detect_band_gaps:
            # Compute band gaps coefficients and data.
            keys = [key for key in coef_info if key.startswith('band_gaps')]

        elif options.analyze_dispersion or options.phase_velocity:

            # Insert incident wave direction to coefficients that need it.
            for key, val in coef_info.iteritems():
                coef_opts = val.get('options', None)
                if coef_opts is None: continue

                if (('incident_wave_dir' in coef_opts)
                    and (coef_opts['incident_wave_dir'] is None)):
                    coef_opts['incident_wave_dir'] = opts.incident_wave_dir

            if options.analyze_dispersion:
                # Compute dispersion coefficients and data.
                keys = [key for key in coef_info
                        if key.startswith('dispersion')
                        or key.startswith('polarization_angles')]

            else:
                # Compute phase velocity and its requirements.
                keys = [key for key in coef_info
                        if key.startswith('phase_velocity')]

        else:
            # Compute only the eigenvalue problems.
            names = [req for req in conf.get(opts.requirements, [''])
                     if req.startswith('evp')]
            coefs = {'dummy' : {'requires' : names,
                                'class' : CoefDummy,}}
            conf.coefs_dummy = coefs
            coefs_name = 'coefs_dummy'
            keys = ['dummy']

        he_options = Struct(coefs=coefs_name, requirements=opts.requirements,
                            compute_only=keys,
                            post_process_hook=self.post_process_hook)
        volume = get_volume_from_options(opts, self.problem)

        he = HomogenizationEngine(self.problem, options,
                                  app_options=he_options,
                                  volume=volume)
        coefs = he()

        coefs = Coefficients(**coefs.to_dict())
        coefs.volume = volume

        coefs_filename = op.join(opts.output_dir, opts.coefs_filename)
        coefs.to_file_txt(coefs_filename + '.txt',
                          opts.tex_names,
                          opts.float_format)

        bg_keys = [key for key in coefs.to_dict()
                   if key.startswith('band_gaps')
                   or key.startswith('dispersion')]
        for ii, key in enumerate(bg_keys):
            bg = coefs.get(key)
            log_save_name = bg.get('log_save_name', None)
            if log_save_name is not None:
                filename = op.join(self.problem.output_dir, log_save_name)
                bg.save_log(filename, opts.float_format, bg)

        if options.plot:
            if options.detect_band_gaps:
                self.plot_band_gaps(coefs)

            elif options.analyze_dispersion:
                self.plot_dispersion(coefs)

        elif options.phase_velocity:
            keys = [key for key in coefs.to_dict()
                    if key.startswith('phase_velocity')]
            for key in keys:
                output('%s:' % key, coefs.get(key))

        return coefs
Example #23
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
Example #24
0
def recover_micro_hook_eps(micro_filename, region,
                           eval_var, nodal_values, const_values, eps0,
                           recovery_file_tag='',
                           define_args=None):
    # Create a micro-problem instance.
    required, other = get_standard_keywords()
    required.remove('equations')
    conf = ProblemConf.from_file(micro_filename, required, other,
                                 verbose=False, define_args=define_args)

    coefs_filename = conf.options.get('coefs_filename', 'coefs')
    output_dir = conf.options.get('output_dir', '.')
    coefs_filename = op.join(output_dir, coefs_filename) + '.h5'

    # Coefficients and correctors
    coefs = Coefficients.from_file_hdf5(coefs_filename)
    corrs = get_correctors_from_file(dump_names=coefs.dump_names)

    recovery_hook = conf.options.get('recovery_hook', None)

    if recovery_hook is not None:
        recovery_hook = conf.get_function(recovery_hook)
        pb = Problem.from_conf(conf, init_equations=False, init_solvers=False)

        # Get tiling of a given region
        rcoors = region.domain.mesh.coors[region.get_entities(0), :]
        rcmin = nm.min(rcoors, axis=0)
        rcmax = nm.max(rcoors, axis=0)
        nn = nm.round((rcmax - rcmin) / eps0)
        if nm.prod(nn) == 0:
            output('inconsistency in recovery region and microstructure size!')
            return

        cs = []
        for ii, n in enumerate(nn):
            cs.append(nm.arange(n) * eps0 + rcmin[ii])

        x0 = nm.empty((int(nm.prod(nn)), nn.shape[0]), dtype=nm.float64)
        for ii, icoor in enumerate(nm.meshgrid(*cs, indexing='ij')):
            x0[:, ii] = icoor.flatten()

        mesh = pb.domain.mesh
        coors, conn, outs, ndoffset = [], [], [], 0
        # Recover region
        for ii, c0 in enumerate(x0):
            local_macro = {'eps0': eps0}
            local_coors = pb.domain.mesh.coors * eps0 + c0
            # Inside recovery region?
            v = nm.ones((eval_var.field.region.entities[0].shape[0], 1))
            v[region.entities[0]] = 0
            no = nm.sum(v)
            aux = eval_var.field.evaluate_at(local_coors, v)
            if (nm.sum(aux) / no) > 1e-3:
                continue

            output('ii: %d' % ii)

            for k, v in six.iteritems(nodal_values):
                local_macro[k] = eval_var.field.evaluate_at(local_coors, v)
            for k, v in six.iteritems(const_values):
                local_macro[k] = v

            outs.append(recovery_hook(pb, corrs, local_macro))
            coors.append(local_coors)
            conn.append(mesh.get_conn(mesh.descs[0]) + ndoffset)
            ndoffset += mesh.n_nod

    # Collect output variables
    outvars = {}
    for k, v in six.iteritems(outs[0]):
        if v.var_name in outvars:
            outvars[v.var_name].append(k)
        else:
            outvars[v.var_name] = [k]

    # Split output by variables/regions
    pvs = pb.create_variables(outvars.keys())
    outregs = {k: pvs[k].field.region.get_entities(-1) for k in outvars.keys()}
    nrve = len(coors)
    coors = nm.vstack(coors)
    ngroups = nm.tile(mesh.cmesh.vertex_groups.squeeze(), (nrve,))
    conn = nm.vstack(conn)
    cgroups = nm.tile(mesh.cmesh.cell_groups.squeeze(), (nrve,))

    # Get region mesh and data
    for k, cidxs in six.iteritems(outregs):
        gcidxs = nm.hstack([cidxs + mesh.n_el * ii for ii in range(nrve)])
        rconn = conn[gcidxs]
        remap = -nm.ones((coors.shape[0],), dtype=nm.int32)
        remap[rconn] = 1
        vidxs = nm.where(remap > 0)[0]
        remap[vidxs] = nm.arange(len(vidxs))
        rconn = remap[rconn]
        rcoors = coors[vidxs, :]

        out = {}
        for ifield in outvars[k]:
            data = [outs[ii][ifield].data for ii in range(nrve)]
            out[ifield] = Struct(name='output_data',
                                 mode=outs[0][ifield].mode,
                                 dofs=None,
                                 var_name=k,
                                 data=nm.vstack(data))

        micro_name = pb.get_output_name(extra='recovered%s_%s'
                                        % (recovery_file_tag, k))
        filename = op.join(output_dir, op.basename(micro_name))
        mesh_out = Mesh.from_data('recovery_%s' % k, rcoors, ngroups[vidxs],
                                  [rconn], [cgroups[gcidxs]], [mesh.descs[0]])
        mesh_out.write(filename, io='auto', out=out)