Beispiel #1
0
    def select_variables(self):
        """
        Return model variables depending on problem config.
        """

        if self.mode not in modes_catalog.keys():
            raise ValueError('Problem mode %s not implemented' % self.mode)

        vars_catalog = modes_catalog[self.mode]

        variables = []
        for datatype in self.datatypes:
            if datatype in vars_catalog.keys():
                if self.mode == 'geometry':
                    if self.source_type in vars_catalog[datatype].keys():
                        source = vars_catalog[datatype][self.source_type]
                        svars = set(source.keys())

                        if isinstance(source(),
                                      (PyrockoRS, gf.ExplosionSource)):
                            svars.discard('magnitude')

                        variables += utility.weed_input_rvs(
                            svars, self.mode, datatype)
                    else:
                        raise ValueError('Source Type not supported for type'
                                         ' of problem, and datatype!')

                    if datatype == 'seismic':
                        if self.stf_type in stf_catalog.keys():
                            stf = stf_catalog[self.stf_type]
                            variables += utility.weed_input_rvs(
                                set(stf.keys()), self.mode, datatype)
                else:
                    variables += vars_catalog[datatype]
            else:
                raise ValueError(
                    'Datatype %s not supported for type of'
                    ' problem! Supported datatype are: %s' %
                    (datatype, ', '.join('"%s"' % d
                                         for d in vars_catalog.keys())))

        unique_variables = utility.unique_list(variables)

        if len(unique_variables) == 0:
            raise Exception('Mode and datatype combination not implemented'
                            ' or not resolvable with given datatypes.')

        return unique_variables
Beispiel #2
0
    def built_model(self):
        """
        Initialise :class:`pymc3.Model` depending on problem composites,
        geodetic and/or seismic data are included. Composites also determine
        the problem to be solved.
        """

        logger.info('... Building model ...\n')

        pc = self.config.problem_config

        with Model() as self.model:

            self.rvs, self.fixed_params = self.get_random_variables()

            self.init_hyperparams()

            total_llk = tt.zeros((1), tconfig.floatX)

            for datatype, composite in self.composites.iteritems():
                if datatype in bconfig.modes_catalog[pc.mode].keys():
                    input_rvs = utility.weed_input_rvs(self.rvs,
                                                       pc.mode,
                                                       datatype=datatype)
                    fixed_rvs = utility.weed_input_rvs(self.fixed_params,
                                                       pc.mode,
                                                       datatype=datatype)

                    if pc.mode == 'ffi':
                        # do the optimization only on the
                        # reference velocity model
                        logger.info("Loading %s Green's Functions" % datatype)
                        data_config = self.config[datatype + '_config']
                        composite.load_gfs(crust_inds=[
                            data_config.gf_config.reference_model_idx
                        ],
                                           make_shared=True)

                    total_llk += composite.get_formula(input_rvs, fixed_rvs,
                                                       self.hyperparams, pc)

            # deterministic RV to write out llks to file
            like = Deterministic('tmp', total_llk)

            # will overwrite deterministic name ...
            llk = Potential(self._like_name, like)
            logger.info('Model building was successful!')
Beispiel #3
0
    def built_model(self):
        """
        Initialise :class:`pymc3.Model` depending on problem composites,
        geodetic and/or seismic data are included. Composites also determine
        the problem to be solved.
        """

        logger.info('... Building model ...\n')

        pc = self.config.problem_config

        with Model() as self.model:

            self.rvs, self.fixed_params = self.get_random_variables()

            self.init_hyperparams()

            total_llk = tt.zeros((1), tconfig.floatX)

            for datatype, composite in self.composites.items():
                if datatype in bconfig.modes_catalog[pc.mode].keys():
                    input_rvs = weed_input_rvs(self.rvs,
                                               pc.mode,
                                               datatype=datatype)
                    fixed_rvs = weed_input_rvs(self.fixed_params,
                                               pc.mode,
                                               datatype=datatype)

                else:
                    input_rvs = self.rvs
                    fixed_rvs = self.fixed_params

                total_llk += composite.get_formula(input_rvs, fixed_rvs,
                                                   self.hyperparams, pc)

            # deterministic RV to write out llks to file
            like = Deterministic('tmp', total_llk)

            # will overwrite deterministic name ...
            llk = Potential(self._like_name, like)
            logger.info('Model building was successful! \n')
Beispiel #4
0
    def built_model(self):
        """
        Initialise :class:`pymc3.Model` depending on configuration file,
        geodetic and/or seismic data are included. Estimates the fault(s)
        geometry.
        """

        logger.info('... Building model ...\n')

        self.outfolder = os.path.join(self.config.project_dir, 'geometry')
        util.ensuredir(self.outfolder)

        with pm.Model() as self.model:

            logger.debug('Optimization for %i sources', len(self.sources))

            pc = self.config.problem_config

            input_rvs = []
            for param in pc.priors:
                input_rvs.append(pm.Uniform(
                    param.name,
                    shape=param.dimension,
                    lower=param.lower,
                    upper=param.upper,
                    testval=param.testvalue,
                    transform=None))

            self.hyperparams = {}

            for hp_name in bconfig.hyper_pars.values():
                if hp_name in pc.hyperparameters:
                    hyperpar = pc.hyperparameters[hp_name]
                    self.hyperparams[hp_name] = pm.Uniform(
                        hyperpar.name,
                        shape=hyperpar.dimension,
                        lower=hyperpar.lower,
                        upper=hyperpar.upper,
                        testval=hyperpar.testvalue,
                        transform=None)
                else:
                    self.hyperparams[hp_name] = 0.

            total_llk = tt.zeros((1), tconfig.floatX)

            if self._seismic_flag:
                self.seis_input_rvs = utility.weed_input_rvs(
                    input_rvs, dataset='seismic')
                # seis
                seis_names = [param.name for param in self.seis_input_rvs]
                logger.debug(
                    'Teleseismic optimization on: \n '
                    ' %s' % ', '.join(seis_names))

                t2 = time.time()
                synths, tmins = self.get_seis_synths(*self.seis_input_rvs)
                t3 = time.time()
                logger.debug(
                    'Teleseismic forward model on test model takes: %f' % \
                        (t3 - t2))

                data_trcs = self.chop_traces(tmins)

                seis_res = data_trcs - synths

                logpts_s = tt.zeros((self.ns_t), tconfig.floatX)
                M = seis_res.shape[1]

                for k, target in enumerate(self.stargets):
                    sfactor = target.covariance.log_norm_factor
                    hp_name = bconfig.hyper_pars[target.codes[3]]

                    logpts_s = tt.set_subtensor(logpts_s[k:k + 1],
                        (-0.5) * (sfactor - \
                        (M * 2 * self.hyperparams[hp_name]) + \
                        tt.exp(self.hyperparams[hp_name] * 2) * \
                        (seis_res[k, :].dot(
                            self.sweights[k]).dot(seis_res[k, :].T))
                                 )
                                                )

                seis_llk = pm.Deterministic(self._seis_like_name, logpts_s)

                total_llk = total_llk + seis_llk.sum()

            if self._geodetic_flag:
                self.geo_input_rvs = utility.weed_input_rvs(
                    input_rvs, dataset='geodetic')

                ## calc residuals
                # geo
                geo_names = [param.name for param in self.geo_input_rvs]
                logger.debug(
                    'Geodetic optimization on: \n '
                    '%s' % ', '.join(geo_names))

                t0 = time.time()
                disp = self.get_geo_synths(*self.geo_input_rvs)
                t1 = time.time()
                logger.debug(
                    'Geodetic forward model on test model takes: %f' % \
                        (t1 - t0))

                los = (disp[:, 0] * self.lv[:, 0] + \
                       disp[:, 1] * self.lv[:, 1] + \
                       disp[:, 2] * self.lv[:, 2]) * self.odws
                geo_res = self.Bij.srmap(
                    tt.cast((self.wdata - los), tconfig.floatX))

                logpts_g = tt.zeros((self.ng_t), tconfig.floatX)

                for l, target in enumerate(self.gtargets):
                    M = target.displacement.size
                    gfactor = target.covariance.log_norm_factor
                    hp_name = bconfig.hyper_pars[target.typ]

                    logpts_g = tt.set_subtensor(logpts_g[l:l + 1],
                         (-0.5) * (gfactor - \
                         (M * 2 * self.hyperparams[hp_name]) + \
                         tt.exp(self.hyperparams[hp_name] * 2) * \
                         (geo_res[l].dot(self.gweights[l]).dot(geo_res[l].T))
                                  )
                                               )

                geo_llk = pm.Deterministic(self._geo_like_name, logpts_g)

                total_llk = total_llk + geo_llk.sum()

            like = pm.Deterministic(
                self._like_name, total_llk)

            llk = pm.Potential(self._like_name, like)
            logger.info('Model building was successful!')