예제 #1
0
    def __init__(self, problem, dims, w=0.2):
        """
        Arguments
        ---------
        problem : Problem
            Pointer to the Problem object being wrapped.
        dims : int or list/tuple of ints
            Either the number of dimensions or a list of the dimension indices that this
            problem uses.
        w : float
            The value to use for all unaccounted for inputs where 0/1 is lower/upper bound.
        """
        self.problem = problem
        self.w = w

        if isinstance(dims, int):
            self.dims = np.arange(dims)
            assert dims <= problem.options["ndim"]
        elif isinstance(dims, (list, tuple, np.ndarray)):
            self.dims = np.array(dims, int)
            assert np.max(dims) < problem.options["ndim"]
        else:
            raise ValueError("dims is invalid")

        self.options = OptionsDictionary()
        self.options.declare("ndim", len(self.dims), types=int)
        self.options.declare("return_complex", False, types=bool)
        self.options.declare("name",
                             "R_" + self.problem.options["name"],
                             types=str)

        self.xlimits = np.zeros((self.options["ndim"], 2))
        for idim, idim_reduced in enumerate(self.dims):
            self.xlimits[idim, :] = problem.xlimits[idim_reduced, :]
예제 #2
0
    def __init__(self, **kwargs):
        """
        Constructor where values of options can be passed in.

        For the list of options, see the documentation for the problem being used.

        Parameters
        ----------
        **kwargs : named arguments
            Set of options that can be optionally set; each option must have been declared.

        Examples
        --------
        >>> import numpy as np
        >>> from smt.sampling_methods import Random
        >>> sampling = Random(xlimits=np.arange(2).reshape((1, 2)))
        """
        self.options = OptionsDictionary()
        self.options.declare(
            "xlimits",
            types=np.ndarray,
            desc=
            "The interval of the domain in each dimension with shape nx x 2 (required)",
        )
        self._initialize()
        self.options.update(kwargs)
예제 #3
0
    def __init__(self, problem, dims, w=0.2):
        """
        Arguments
        ---------
        problem : Problem
            Pointer to the Problem object being wrapped.
        dims : int or list/tuple of ints
            Either the number of dimensions or a list of the dimension indices of problem
            that this problem uses.
        w : float
            The value to use for all unaccounted for inputs where 0/1 is lower/upper bound.
        """
        self.problem = problem
        self.w = w

        if isinstance(dims, int):
            self.dims = np.arange(dims)
            assert dims <= problem.options['ndim']
        elif isinstance(dims, (list, tuple)):
            self.dims = np.array(dims, int)
            assert numpy.max(dims) < problem.options['ndim']
        else:
            raise ValueError('dims is invalid')

        self.options = OptionsDictionary()
        self.options.declare('ndim', len(self.dims), types=int)
        self.options.declare('name',
                             'R_' + self.problem.options['name'],
                             types=str)

        self.xlimits = np.zeros((self.options['ndim'], 2))
        for idim in self.dims:
            self.xlimits[idim, :] = problem.xlimits[self.dims[idim], :]
예제 #4
0
class Sampling(object):
    def __init__(self, **kwargs):
        self.options = OptionsDictionary()
        self.options.declare('xlimits', types=np.ndarray)
        self._declare_options()
        self.options.update(kwargs)

    def _declare_options(self):
        pass

    def __call__(self, n):
        """
        Compute the requested number of sampling points.

        Arguments
        ---------
        n : int
            Number of points requested.

        Returns
        -------
        ndarray[n, nx]
            The sampling locations in the input space.
        """
        xlimits = self.options['xlimits']
        nx = xlimits.shape[0]

        x = self._compute(n)
        for kx in range(nx):
            x[:,
              kx] = xlimits[kx,
                            0] + x[:, kx] * (xlimits[kx, 1] - xlimits[kx, 0])

        return x
예제 #5
0
    def __init__(self, **kwargs):
        """
        Constructor where values of options can be passed in.

        For the list of options, see the documentation for the problem being used.

        Parameters
        ----------
        **kwargs : named arguments
            Set of options that can be optionally set; each option must have been declared.

        Examples
        --------
        >>> from smt.problems import Sphere
        >>> prob = Sphere(ndim=3)
        """
        self.options = OptionsDictionary()
        self.options.declare("ndim", 1, types=int)
        self.options.declare("return_complex", False, types=bool)
        self._initialize()
        self.options.update(kwargs)

        self.xlimits = np.zeros((self.options["ndim"], 2))

        self._setup()
예제 #6
0
    def __init__(self, **kwargs):
        """
        Constructor where values of options can be passed in.

        For the list of options, see the documentation for the surrogate model being used.

        Parameters
        ----------
        **kwargs : named arguments
            Set of options that can be optionally set; each option must have been declared.

        Examples
        --------
        >>> from smt.surrogate_models import RBF
        >>> sm = RBF(print_global=False)
        """
        self.options = OptionsDictionary()

        self.supports = supports = {}
        supports["training_derivatives"] = False
        supports["derivatives"] = False
        supports["output_derivatives"] = False
        supports["adjoint_api"] = False
        supports["variances"] = False

        declare = self.options.declare

        declare(
            "print_global",
            True,
            types=bool,
            desc="Global print toggle. If False, all printing is suppressed",
        )
        declare(
            "print_training",
            True,
            types=bool,
            desc="Whether to print training information",
        )
        declare(
            "print_prediction",
            True,
            types=bool,
            desc="Whether to print prediction information",
        )
        declare(
            "print_problem",
            True,
            types=bool,
            desc="Whether to print problem information",
        )
        declare("print_solver",
                True,
                types=bool,
                desc="Whether to print solver information")

        self._initialize()
        self.options.update(kwargs)
        self.training_points = defaultdict(dict)
        self.printer = Printer()
예제 #7
0
파일: application.py 프로젝트: SMTorg/smt
class SurrogateBasedApplication:

    if compiled_available:
        _surrogate_type = {
            "KRG": KRG,
            "LS": LS,
            "QP": QP,
            "KPLS": KPLS,
            "KPLSK": KPLSK,
            "GEKPLS": GEKPLS,
            "RBF": RBF,
            "RMTC": RMTC,
            "RMTB": RMTB,
            "IDW": IDW,
            "MGP": MGP,
        }
    else:
        _surrogate_type = {
            "KRG": KRG,
            "LS": LS,
            "QP": QP,
            "KPLS": KPLS,
            "KPLSK": KPLSK,
            "GEKPLS": GEKPLS,
            "MGP": MGP,
        }

    def __init__(self, **kwargs):
        """
        Constructor where values of options can be passed in.

        For the list of options, see the documentation for the surrogate model being used.

        Parameters
        ----------
        **kwargs : named arguments
            Set of options that can be optionally set; each option must have been declared.

        Examples
        --------
        >>> from smt.applications import VFM
        >>> extension = VFM(type_bridge = 'Additive', name_model_LF = QP, name_model_bridge =
                           LS, X_LF = xLF, y_LF = yLF, X_HF = xHF, y_HF = yHF, options_LF =
                           dictOptionLFModel, options_bridge = dictOptionBridgeModel)
        """
        self.options = OptionsDictionary()

        self._initialize()
        self.options.update(kwargs)

    def _initialize(self):
        """
        Implemented by the application to declare options and declare what they support (optional).

        Examples
        --------
        self.options.declare('option_name', default_value, types=(bool, int), desc='description')
        """
        pass
예제 #8
0
class Extensions(object):

    if compiled_available:
        _surrogate_type = {
            'KRG': KRG,'LS': LS,'QP': QP,'KPLS':KPLS,'KPLSK':KPLSK,'GEKPLS':GEKPLS,
            'RBF':RBF,'RMTC':RMTC,'RMTB':RMTB,'IDW':IDW}
    else:
        _surrogate_type = {
            'KRG': KRG,'LS': LS,'QP': QP,'KPLS':KPLS,'KPLSK':KPLSK,'GEKPLS':GEKPLS}

    def __init__(self, **kwargs):
        """
        Constructor where values of options can be passed in.

        For the list of options, see the documentation for the surrogate model being used.

        Parameters
        ----------
        **kwargs : named arguments
            Set of options that can be optionally set; each option must have been declared.

        Examples
        --------
        >>> from smt.extensions import VFM
        >>> extension = VFM(type_bridge = 'Additive', name_model_LF = QP, name_model_bridge =
                           LS, X_LF = xLF, y_LF = yLF, X_HF = xHF, y_HF = yHF, options_LF =
                           dictOptionLFModel, options_bridge = dictOptionBridgeModel)
        """
        self.options = OptionsDictionary()

        self._initialize()
        self.options.update(kwargs)

    def _initialize(self):
        """
        Implemented by the application to declare options and declare what they support (optional).

        Examples
        --------
        self.options.declare('option_name', default_value, types=(bool, int), desc='description')
        """
        pass

    def apply_method(self):
        """
        Run the complete algorithm of the SMT application; e.g.: VFM, ME, EGO...

        """
        self._apply()

    def analyse_results(self, **kwargs):
        """
        Get the final results; e.g., for VFM, two possible analysis are available:
        - kwargs = {x = x, operation = 'predict_values'}
        - kwargs = {x = x, operation = 'predict_derivatives, kx = i}

        """
        return self._analyse_results(**kwargs)
예제 #9
0
    def __init__(self, ndim=1, width=10.0):
        self.problem = TensorProduct(ndim=ndim, func="tanh", width=width)

        self.options = OptionsDictionary()
        self.options.declare("ndim", ndim, types=int)
        self.options.declare("return_complex", False, types=bool)
        self.options.declare("name", "NdimStepFunction", types=str)

        self.xlimits = self.problem.xlimits
예제 #10
0
    def __init__(self, ndim=1, w=0.2):
        self.problem = ReducedProblem(CantileverBeam(ndim=3*ndim), np.arange(1, 3*ndim, 3), w=w)

        self.options = OptionsDictionary()
        self.options.declare('ndim', ndim, types=int)
        self.options.declare('return_complex', False, types=bool)
        self.options.declare('name', 'NdimCantileverBeam', types=str)

        self.xlimits = self.problem.xlimits
예제 #11
0
    def __init__(self, **kwargs):
        self.mtx = None
        self.rhs = None

        self.options = OptionsDictionary()
        self.options.declare("print_init", True, types=bool)
        self.options.declare("print_solve", True, types=bool)
        self._initialize()
        self.options.update(kwargs)
예제 #12
0
    def __init__(self, **kwargs):
        self.mtx = None
        self.rhs = None

        self.options = OptionsDictionary()
        self.options.declare('print_init', True, types=bool)
        self.options.declare('print_solve', False, types=bool)
        self._declare_options()
        self.options.update(kwargs)
예제 #13
0
파일: problem.py 프로젝트: JustinSGray/SMT
    def __init__(self, **kwargs):
        self.options = OptionsDictionary()
        self.options.declare('ndim', 1, types=int)
        self._declare_options()
        self.options.update(kwargs)

        self.xlimits = np.zeros((self.options['ndim'], 2))

        self._initialize()
예제 #14
0
    def __init__(self, ndim=1, width=10.0):
        self.problem = TensorProduct(ndim=ndim, func='tanh', width=width)

        self.options = OptionsDictionary()
        self.options.declare('ndim', ndim, types=int)
        self.options.declare('return_complex', False, types=bool)
        self.options.declare('name', 'NdimStepFunction', types=str)

        self.xlimits = self.problem.xlimits
예제 #15
0
    def __init__(self, ndim=1, w=0.2):
        self.problem = ReducedProblem(RobotArm(ndim=2 * (ndim + 1)),
                                      np.arange(3, 2 * (ndim + 1), 2),
                                      w=w)

        self.options = OptionsDictionary()
        self.options.declare('ndim', ndim, types=int)
        self.options.declare('return_complex', False, types=bool)
        self.options.declare('name', 'NdimRobotArm', types=str)

        self.xlimits = self.problem.xlimits
예제 #16
0
    def __init__(self, ndim=1, w=0.2):
        self.problem = ReducedProblem(Rosenbrock(ndim=ndim + 1),
                                      np.arange(1, ndim + 1),
                                      w=w)

        self.options = OptionsDictionary()
        self.options.declare("ndim", ndim, types=int)
        self.options.declare("return_complex", False, types=bool)
        self.options.declare("name", "NdimRosenbrock", types=str)

        self.xlimits = self.problem.xlimits
예제 #17
0
class NdimRosenbrock(Problem):
    def __init__(self, ndim=1, w=0.2):
        self.problem = ReducedProblem(Rosenbrock(ndim=ndim + 1),
                                      np.arange(1, ndim + 1),
                                      w=w)

        self.options = OptionsDictionary()
        self.options.declare('ndim', ndim, types=int)
        self.options.declare('return_complex', False, types=bool)
        self.options.declare('name', 'NdimRosenbrock', types=str)

        self.xlimits = self.problem.xlimits

    def _evaluate(self, x, kx):
        return self.problem._evaluate(x, kx)
예제 #18
0
    def __init__(self, **kwargs):
        '''
        Constructor.

        Arguments
        ---------
        **kwargs : named arguments
            Set of options that can be optionally set; each option must have been declared.
        '''
        self.options = OptionsDictionary()
        self._declare_options()
        self.options.update(kwargs)

        self.training_pts = {'exact': {}}

        self.printer = Printer()
예제 #19
0
파일: problem.py 프로젝트: JustinSGray/SMT
class Problem(object):
    def __init__(self, **kwargs):
        self.options = OptionsDictionary()
        self.options.declare('ndim', 1, types=int)
        self._declare_options()
        self.options.update(kwargs)

        self.xlimits = np.zeros((self.options['ndim'], 2))

        self._initialize()

    def _declare_options(self):
        pass

    def _initialize(self):
        pass

    def __call__(self, x, kx=None):
        """
        Arguments
        ---------
        x : ndarray[ne, nx]
            Evaluation points.
        kx : int or None
            Index of derivative (0-based) to return values with respect to.
            None means return function value rather than derivative.

        Returns
        -------
        ndarray[ne, 1]
            Functions values if kx=None or derivative values if kx is an int.
        """
        if not isinstance(x, np.ndarray) or len(x.shape) != 2:
            raise TypeError('x should be a rank-2 array.')
        elif x.shape[1] != self.options['ndim']:
            raise ValueError('The second dimension of x should be %i' %
                             self.options['ndim'])

        if kx is not None:
            if not isinstance(kx, int) or kx < 0:
                raise TypeError('kx should be None or a non-negative int.')

        return self._evaluate(x, kx)
예제 #20
0
    def __init__(self, **kwargs):
        """

        Examples
        --------
        >>> from methods import localGEKPLS
        >>> local1 = localGEKPLS(para_file='data/local1.npy')
        """
        self.options = OptionsDictionary()
        declare = self.options.declare
        declare(
            'para_file',
            values=None,
            types=str,
            desc=
            'Directory for loading / saving cached data; None means do not save or load'
        )

        self.options.update(kwargs)
        self._readPara()
def globalSurrogateModel(data, pr):
    pr.callingFunction = "globalSurrogate"
    data["prediction"] = pr.predict(data)

    ttdE = testTrainData(data, pr, encoded=True)
    ttdNE = testTrainData(data, pr, encoded=False)

    options = OptionsDictionary()
    options.declare("ndim", 1.0, types=float)
    options.declare("return_complex", False, types=bool)
    xlimits = np.zeros((int(options["ndim"]), 4))
    xlimits[:, 0] = -2.0
    xlimits[:, 1] = 2.0
    funXLimits = xlimits
    ndim = 4

    # models retrieved from https://github.com/SMTorg/smt/blob/master/tutorial/SMT_Tutorial.ipynb
    models = pd.Series()
    models["linear"] = Model(linearModel, ttdE)
    models["quadratic"] = Model(quadraticModel, ttdE)
    # models["kriging"] = Model(kriging, ttdE, ndim=ndim)
    # models["KPLSK"] = Model(kPLSK, ttdE)
    models["IDW"] = Model(iDW, ttdE)
    models["RBF"] = Model(rBF, ttdE)
    #models["RMTBSimba"] = Model(rMTBSimba, ttdNE,  xL = funXLimits)
    #models["GEKPLS"] = Model(gEKPLS, ttdNE, xL = funXLimits, ndim = ndim)
    #models["DEKPLS"] = Model(dEKPLS, ttdNE, xL = funXLimits, ndim = ndim)

    for model in models:
        compareToOrig(model.t, model.title, model.xtest, model.ytest)
예제 #22
0
class LinearSolver(object):
    def __init__(self, **kwargs):
        self.mtx = None
        self.rhs = None

        self.options = OptionsDictionary()
        self.options.declare("print_init", True, types=bool)
        self.options.declare("print_solve", True, types=bool)
        self._initialize()
        self.options.update(kwargs)

    def _initialize(self):
        pass

    def _setup(self, mtx, printer, mg_matrices=[]):
        pass

    def _solve(self, rhs, sol=None, ind_y=0):
        pass

    def _clone(self):
        clone = self.__class__()
        clone.options.update(clone.options._dict)
        return clone

    @contextlib.contextmanager
    def _active(self, active):
        orig_active = self.printer.active

        self.printer.active = self.printer.active and active
        yield self.printer
        self.printer.active = orig_active
예제 #23
0
파일: application.py 프로젝트: SMTorg/smt
    def __init__(self, **kwargs):
        """
        Constructor where values of options can be passed in.

        For the list of options, see the documentation for the surrogate model being used.

        Parameters
        ----------
        **kwargs : named arguments
            Set of options that can be optionally set; each option must have been declared.

        Examples
        --------
        >>> from smt.applications import VFM
        >>> extension = VFM(type_bridge = 'Additive', name_model_LF = QP, name_model_bridge =
                           LS, X_LF = xLF, y_LF = yLF, X_HF = xHF, y_HF = yHF, options_LF =
                           dictOptionLFModel, options_bridge = dictOptionBridgeModel)
        """
        self.options = OptionsDictionary()

        self._initialize()
        self.options.update(kwargs)
예제 #24
0
    def __init__(self, **kwargs):
        """

        Examples
        --------
        >>> from methods import localGEKPLS
        >>> clmodel = MoE(func='cl',nlocal=20)
        """
        self.options = OptionsDictionary()
        declare = self.options.declare
        declare('func',
                values=('Cl', 'Cd', 'Cm'),
                types=str,
                desc='Which model to construct')
        declare('nlocal',
                values=None,
                types=int,
                desc='How many local models to use')

        self.options.update(kwargs)
        self.models = []
        self.posteriors = []

        self._setup()
예제 #25
0
class NdimRobotArm(Problem):
    def __init__(self, ndim=1, w=0.2):
        self.problem = ReducedProblem(RobotArm(ndim=2 * (ndim + 1)),
                                      np.arange(3, 2 * (ndim + 1), 2),
                                      w=w)

        self.options = OptionsDictionary()
        self.options.declare("ndim", ndim, types=int)
        self.options.declare("return_complex", False, types=bool)
        self.options.declare("name", "NdimRobotArm", types=str)

        self.xlimits = self.problem.xlimits

    def _evaluate(self, x, kx):
        return self.problem._evaluate(x, kx)
예제 #26
0
class NdimCantileverBeam(Problem):
    def __init__(self, ndim=1, w=0.2):
        self.problem = ReducedProblem(CantileverBeam(ndim=3 * ndim),
                                      np.arange(1, 3 * ndim, 3),
                                      w=w)

        self.options = OptionsDictionary()
        self.options.declare("ndim", ndim, types=int)
        self.options.declare("return_complex", False, types=bool)
        self.options.declare("name", "NdimCantileverBeam", types=str)

        self.xlimits = self.problem.xlimits

    def _evaluate(self, x, kx):
        return self.problem._evaluate(x, kx)
예제 #27
0
class SurrogateModel(object):
    """
    Base class for all surrogate models.

    Attributes
    ----------
    options : OptionsDictionary
        Dictionary of options. Options values can be set on this attribute directly
        or they can be passed in as keyword arguments during instantiation.
    supports : dict
        Dictionary containing information about what this surrogate model supports.

    Examples
    --------
    >>> from smt.surrogate_models import RBF
    >>> sm = RBF(print_training=False)
    >>> sm.options['print_prediction'] = False
    """
    def __init__(self, **kwargs):
        """
        Constructor where values of options can be passed in.

        For the list of options, see the documentation for the surrogate model being used.

        Parameters
        ----------
        **kwargs : named arguments
            Set of options that can be optionally set; each option must have been declared.

        Examples
        --------
        >>> from smt.surrogate_models import RBF
        >>> sm = RBF(print_global=False)
        """
        self.options = OptionsDictionary()

        self.supports = supports = {}
        supports["training_derivatives"] = False
        supports["derivatives"] = False
        supports["output_derivatives"] = False
        supports["adjoint_api"] = False
        supports["variances"] = False

        declare = self.options.declare

        declare(
            "print_global",
            True,
            types=bool,
            desc="Global print toggle. If False, all printing is suppressed",
        )
        declare(
            "print_training",
            True,
            types=bool,
            desc="Whether to print training information",
        )
        declare(
            "print_prediction",
            True,
            types=bool,
            desc="Whether to print prediction information",
        )
        declare(
            "print_problem",
            True,
            types=bool,
            desc="Whether to print problem information",
        )
        declare("print_solver",
                True,
                types=bool,
                desc="Whether to print solver information")

        self._initialize()
        self.options.update(kwargs)
        self.training_points = defaultdict(dict)
        self.printer = Printer()

    def set_training_values(self, xt, yt, name=None):
        """
        Set training data (values).

        Parameters
        ----------
        xt : np.ndarray[nt, nx] or np.ndarray[nt]
            The input values for the nt training points.
        yt : np.ndarray[nt, ny] or np.ndarray[nt]
            The output values for the nt training points.
        name : str or None
            An optional label for the group of training points being set.
            This is only used in special situations (e.g., multi-fidelity applications).
        """
        xt = check_2d_array(xt, "xt")
        yt = check_2d_array(yt, "yt")

        if xt.shape[0] != yt.shape[0]:
            raise ValueError(
                "the first dimension of xt and yt must have the same length")

        self.nt = xt.shape[0]
        self.nx = xt.shape[1]
        self.ny = yt.shape[1]
        kx = 0
        self.training_points[name][kx] = [np.array(xt), np.array(yt)]

    def update_training_values(self, yt, name=None):
        """
        Update the training data (values) at the previously set input values.

        Parameters
        ----------
        yt : np.ndarray[nt, ny] or np.ndarray[nt]
            The output values for the nt training points.
        name : str or None
            An optional label for the group of training points being set.
            This is only used in special situations (e.g., multi-fidelity applications).
        """
        yt = check_2d_array(yt, "yt")

        kx = 0

        if kx not in self.training_points[name]:
            raise ValueError(
                "The training points must be set first with set_training_values "
                + "before calling update_training_values.")

        xt = self.training_points[name][kx][0]
        if xt.shape[0] != yt.shape[0]:
            raise ValueError(
                "The number of training points does not agree with the earlier call of "
                + "set_training_values.")

        self.training_points[name][kx][1] = np.array(yt)

    def set_training_derivatives(self, xt, dyt_dxt, kx, name=None):
        """
        Set training data (derivatives).

        Parameters
        ----------
        xt : np.ndarray[nt, nx] or np.ndarray[nt]
            The input values for the nt training points.
        dyt_dxt : np.ndarray[nt, ny] or np.ndarray[nt]
            The derivatives values for the nt training points.
        kx : int
            0-based index of the derivatives being set.
        name : str or None
            An optional label for the group of training points being set.
            This is only used in special situations (e.g., multi-fidelity applications).
        """
        check_support(self, "training_derivatives")

        xt = check_2d_array(xt, "xt")
        dyt_dxt = check_2d_array(dyt_dxt, "dyt_dxt")

        if xt.shape[0] != dyt_dxt.shape[0]:
            raise ValueError(
                "the first dimension of xt and dyt_dxt must have the same length"
            )

        if not isinstance(kx, int):
            raise ValueError("kx must be an int")

        self.training_points[name][kx + 1] = [np.array(xt), np.array(dyt_dxt)]

    def update_training_derivatives(self, dyt_dxt, kx, name=None):
        """
        Update the training data (values) at the previously set input values.

        Parameters
        ----------
        dyt_dxt : np.ndarray[nt, ny] or np.ndarray[nt]
            The derivatives values for the nt training points.
        kx : int
            0-based index of the derivatives being set.
        name : str or None
            An optional label for the group of training points being set.
            This is only used in special situations (e.g., multi-fidelity applications).
        """
        check_support(self, "training_derivatives")

        dyt_dxt = check_2d_array(dyt_dxt, "dyt_dxt")

        if kx not in self.training_points[name]:
            raise ValueError(
                "The training points must be set first with set_training_values "
                + "before calling update_training_values.")

        xt = self.training_points[name][kx][0]
        if xt.shape[0] != dyt_dxt.shape[0]:
            raise ValueError(
                "The number of training points does not agree with the earlier call of "
                + "set_training_values.")

        self.training_points[name][kx + 1][1] = np.array(dyt_dxt)

    def train(self):
        """
        Train the model
        """
        n_exact = self.training_points[None][0][0].shape[0]

        self.printer.active = self.options["print_global"]
        self.printer._line_break()
        self.printer._center(self.name)

        self.printer.active = (self.options["print_global"]
                               and self.options["print_problem"])
        self.printer._title("Problem size")
        self.printer("   %-25s : %i" % ("# training points.", n_exact))
        self.printer()

        self.printer.active = (self.options["print_global"]
                               and self.options["print_training"])
        if self.name == "MixExp":
            # Mixture of experts model
            self.printer._title("Training of the Mixture of experts")
        else:
            self.printer._title("Training")

        # Train the model using the specified model-method
        with self.printer._timed_context("Training", "training"):
            self._train()

    def predict_values(self, x):
        """
        Predict the output values at a set of points.

        Parameters
        ----------
        x : np.ndarray[nt, nx] or np.ndarray[nt]
            Input values for the prediction points.

        Returns
        -------
        y : np.ndarray[nt, ny]
            Output values at the prediction points.
        """
        x = check_2d_array(x, "x")
        check_nx(self.nx, x)
        n = x.shape[0]
        self.printer.active = (self.options["print_global"]
                               and self.options["print_prediction"])

        if self.name == "MixExp":
            # Mixture of experts model
            self.printer._title("Evaluation of the Mixture of experts")
        else:
            self.printer._title("Evaluation")
        self.printer("   %-12s : %i" % ("# eval points.", n))
        self.printer()

        # Evaluate the unknown points using the specified model-method
        with self.printer._timed_context("Predicting", key="prediction"):
            y = self._predict_values(x)

        time_pt = self.printer._time("prediction")[-1] / n
        self.printer()
        self.printer("Prediction time/pt. (sec) : %10.7f" % time_pt)
        self.printer()
        return y.reshape((n, self.ny))

    def predict_derivatives(self, x, kx):
        """
        Predict the dy_dx derivatives at a set of points.

        Parameters
        ----------
        x : np.ndarray[nt, nx] or np.ndarray[nt]
            Input values for the prediction points.
        kx : int
            The 0-based index of the input variable with respect to which derivatives are desired.

        Returns
        -------
        dy_dx : np.ndarray[nt, ny]
            Derivatives.
        """
        check_support(self, "derivatives")
        x = check_2d_array(x, "x")
        check_nx(self.nx, x)
        n = x.shape[0]
        self.printer.active = (self.options["print_global"]
                               and self.options["print_prediction"])

        if self.name == "MixExp":
            # Mixture of experts model
            self.printer._title("Evaluation of the Mixture of experts")
        else:
            self.printer._title("Evaluation")
        self.printer("   %-12s : %i" % ("# eval points.", n))
        self.printer()

        # Evaluate the unknown points using the specified model-method
        with self.printer._timed_context("Predicting", key="prediction"):
            y = self._predict_derivatives(x, kx)

        time_pt = self.printer._time("prediction")[-1] / n
        self.printer()
        self.printer("Prediction time/pt. (sec) : %10.7f" % time_pt)
        self.printer()

        return y.reshape((n, self.ny))

    def predict_output_derivatives(self, x):
        """
        Predict the derivatives dy_dyt at a set of points.

        Parameters
        ----------
        x : np.ndarray[nt, nx] or np.ndarray[nt]
            Input values for the prediction points.

        Returns
        -------
        dy_dyt : dict of np.ndarray[nt, nt]
            Dictionary of output derivatives.
            Key is None for derivatives wrt yt and kx for derivatives wrt dyt_dxt.
        """
        check_support(self, "output_derivatives")
        check_nx(self.nx, x)

        dy_dyt = self._predict_output_derivatives(x)
        return dy_dyt

    def predict_variances(self, x):
        """
        Predict the variances at a set of points.

        Parameters
        ----------
        x : np.ndarray[nt, nx] or np.ndarray[nt]
            Input values for the prediction points.

        Returns
        -------
        s2 : np.ndarray[nt, ny]
            Variances.
        """
        check_support(self, "variances")
        check_nx(self.nx, x)
        n = x.shape[0]
        s2 = self._predict_variances(x)
        return s2.reshape((n, self.ny))

    def _initialize(self):
        """
        Implemented by surrogate models to declare options and declare what they support (optional).

        Examples
        --------
        self.options.declare('option_name', default_value, types=(bool, int), desc='description')
        self.supports['derivatives'] = True
        """
        pass

    def _train(self):
        """
        Implemented by surrogate models to perform training (optional, but typically implemented).
        """
        pass

    def _predict_values(self, x):
        """
        Implemented by surrogate models to predict the output values.

        Parameters
        ----------
        x : np.ndarray[nt, nx]
            Input values for the prediction points.

        Returns
        -------
        y : np.ndarray[nt, ny]
            Output values at the prediction points.
        """
        raise Exception("This surrogate model is incorrectly implemented")

    def _predict_derivatives(self, x, kx):
        """
        Implemented by surrogate models to predict the dy_dx derivatives (optional).

        If this method is implemented, the surrogate model should have

        ::
            self.supports['derivatives'] = True

        in the _initialize() implementation.

        Parameters
        ----------
        x : np.ndarray[nt, nx]
            Input values for the prediction points.
        kx : int
            The 0-based index of the input variable with respect to which derivatives are desired.

        Returns
        -------
        dy_dx : np.ndarray[nt, ny]
            Derivatives.
        """
        check_support(self, "derivatives", fail=True)

    def _predict_output_derivatives(self, x):
        """
        Implemented by surrogate models to predict the dy_dyt derivatives (optional).

        If this method is implemented, the surrogate model should have

        ::
            self.supports['output_derivatives'] = True

        in the _initialize() implementation.

        Parameters
        ----------
        x : np.ndarray[nt, nx]
            Input values for the prediction points.

        Returns
        -------
        dy_dyt : dict of np.ndarray[nt, nt]
            Dictionary of output derivatives.
            Key is None for derivatives wrt yt and kx for derivatives wrt dyt_dxt.
        """
        check_support(self, "output_derivatives", fail=True)

    def _predict_variances(self, x):
        """
        Implemented by surrogate models to predict the variances at a set of points (optional).

        If this method is implemented, the surrogate model should have

        ::
            self.supports['variances'] = True

        in the _initialize() implementation.

        Parameters
        ----------
        x : np.ndarray[nt, nx]
            Input values for the prediction points.

        Returns
        -------
        s2 : np.ndarray[nt, ny]
            Variances.
        """
        check_support(self, "variances", fail=True)
예제 #28
0
class ReducedProblem(Problem):
    def __init__(self, problem, dims, w=0.2):
        """
        Arguments
        ---------
        problem : Problem
            Pointer to the Problem object being wrapped.
        dims : int or list/tuple of ints
            Either the number of dimensions or a list of the dimension indices that this
            problem uses.
        w : float
            The value to use for all unaccounted for inputs where 0/1 is lower/upper bound.
        """
        self.problem = problem
        self.w = w

        if isinstance(dims, int):
            self.dims = np.arange(dims)
            assert dims <= problem.options["ndim"]
        elif isinstance(dims, (list, tuple, np.ndarray)):
            self.dims = np.array(dims, int)
            assert np.max(dims) < problem.options["ndim"]
        else:
            raise ValueError("dims is invalid")

        self.options = OptionsDictionary()
        self.options.declare("ndim", len(self.dims), types=int)
        self.options.declare("return_complex", False, types=bool)
        self.options.declare("name",
                             "R_" + self.problem.options["name"],
                             types=str)

        self.xlimits = np.zeros((self.options["ndim"], 2))
        for idim, idim_reduced in enumerate(self.dims):
            self.xlimits[idim, :] = problem.xlimits[idim_reduced, :]

    def _evaluate(self, x, kx):
        """
        Arguments
        ---------
        x : ndarray[ne, nx]
            Evaluation points.
        kx : int or None
            Index of derivative (0-based) to return values with respect to.
            None means return function value rather than derivative.

        Returns
        -------
        ndarray[ne, 1]
            Functions values if kx=None or derivative values if kx is an int.
        """
        ne, nx = x.shape

        nx_prob = self.problem.options["ndim"]
        x_prob = np.zeros((ne, nx_prob), complex)
        for ix in range(nx_prob):
            x_prob[:, ix] = (1 - self.w) * self.problem.xlimits[
                ix, 0] + self.w * self.problem.xlimits[ix, 1]

        for ix in range(nx):
            x_prob[:, self.dims[ix]] = x[:, ix]

        if kx is None:
            y = self.problem._evaluate(x_prob, None)
        else:
            y = self.problem._evaluate(x_prob, self.dims[kx])

        return y
예제 #29
0
class Problem(object):
    def __init__(self, **kwargs):
        """
        Constructor where values of options can be passed in.

        For the list of options, see the documentation for the problem being used.

        Parameters
        ----------
        **kwargs : named arguments
            Set of options that can be optionally set; each option must have been declared.

        Examples
        --------
        >>> from smt.problems import Sphere
        >>> prob = Sphere(ndim=3)
        """
        self.options = OptionsDictionary()
        self.options.declare("ndim", 1, types=int)
        self.options.declare("return_complex", False, types=bool)
        self._initialize()
        self.options.update(kwargs)

        self.xlimits = np.zeros((self.options["ndim"], 2))

        self._setup()

    def _initialize(self):
        """
        Implemented by problem to declare options (optional).

        Examples
        --------
        self.options.declare('option_name', default_value, types=(bool, int), desc='description')
        """
        pass

    def _setup(self):
        pass

    def __call__(self, x, kx=None):
        """
        Evaluate the function.

        Parameters
        ----------
        x : ndarray[n, nx] or ndarray[n]
            Evaluation points where n is the number of evaluation points.
        kx : int or None
            Index of derivative (0-based) to return values with respect to.
            None means return function value rather than derivative.

        Returns
        -------
        ndarray[n, 1]
            Functions values if kx=None or derivative values if kx is an int.
        """
        x = ensure_2d_array(x, "x")

        if x.shape[1] != self.options["ndim"]:
            raise ValueError("The second dimension of x should be %i" %
                             self.options["ndim"])

        if kx is not None:
            if not isinstance(kx, int) or kx < 0:
                raise TypeError("kx should be None or a non-negative int.")

        y = self._evaluate(x, kx)

        if self.options["return_complex"]:
            return y
        else:
            return np.real(y)

    def _evaluate(self, x, kx=None):
        """
        Implemented by surrogate models to evaluate the function.

        Parameters
        ----------
        x : ndarray[n, nx]
            Evaluation points where n is the number of evaluation points.
        kx : int or None
            Index of derivative (0-based) to return values with respect to.
            None means return function value rather than derivative.

        Returns
        -------
        ndarray[n, 1]
            Functions values if kx=None or derivative values if kx is an int.
        """
        raise Exception("This problem has not been implemented correctly")
예제 #30
0
class SamplingMethod(object):
    def __init__(self, **kwargs):
        """
        Constructor where values of options can be passed in.

        For the list of options, see the documentation for the problem being used.

        Parameters
        ----------
        **kwargs : named arguments
            Set of options that can be optionally set; each option must have been declared.

        Examples
        --------
        >>> import numpy as np
        >>> from smt.sampling_methods import Random
        >>> sampling = Random(xlimits=np.arange(2).reshape((1, 2)))
        """
        self.options = OptionsDictionary()
        self.options.declare(
            "xlimits",
            types=np.ndarray,
            desc=
            "The interval of the domain in each dimension with shape nx x 2 (required)",
        )
        self._initialize()
        self.options.update(kwargs)

    def _initialize(self):
        """
        Implemented by sampling methods to declare options (optional).

        Examples
        --------
        self.options.declare('option_name', default_value, types=(bool, int), desc='description')
        """
        pass

    def __call__(self, nt):
        """
        Compute the requested number of sampling points.

        The number of dimensions (nx) is determined based on `xlimits.shape[0]`.

        Arguments
        ---------
        nt : int
            Number of points requested.

        Returns
        -------
        ndarray[nt, nx]
            The sampling locations in the input space.
        """
        xlimits = self.options["xlimits"]
        nx = xlimits.shape[0]

        x = self._compute(nt)
        for kx in range(nx):
            x[:,
              kx] = xlimits[kx,
                            0] + x[:, kx] * (xlimits[kx, 1] - xlimits[kx, 0])

        return x

    def _compute(self, nt):
        """
        Implemented by sampling methods to compute the requested number of sampling points.

        The number of dimensions (nx) is determined based on `xlimits.shape[0]`.

        Arguments
        ---------
        nt : int
            Number of points requested.

        Returns
        -------
        ndarray[nt, nx]
            The sampling locations in the input space.
        """
        raise Exception(
            "This sampling method has not been implemented correctly")