How to use the nevergrad.instrumentation function in nevergrad

To help you get started, we’ve selected a few nevergrad examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github facebookresearch / nevergrad / nevergrad / benchmark / test_xpbase.py View on Github external
def __init__(self, dimension: int):
        super().__init__(self.oracle_call, inst.var.Gaussian(0, 1, shape=[dimension]))
github facebookresearch / nevergrad / nevergrad / benchmark / test_xpbase.py View on Github external
from typing import Optional, List, Tuple, Any, Dict
import numpy as np
from ..common import testing
from ..optimization import test_base
from ..functions import ArtificialFunction
from ..functions.test_functionlib import DESCRIPTION_KEYS as ARTIFICIAL_KEYS
from .. import instrumentation as inst
from . import execution
from . import xpbase


DESCRIPTION_KEYS = {"seed", "elapsed_time", "elapsed_budget", "loss", "optimizer_name", "pseudotime",
                    "num_workers", "budget", "error", "batch_mode"} | ARTIFICIAL_KEYS


class Function(inst.InstrumentedFunction, execution.PostponedObject):

    def __init__(self, dimension: int):
        super().__init__(self.oracle_call, inst.var.Gaussian(0, 1, shape=[dimension]))

    def oracle_call(self, x: np.ndarray) -> float:
        return float(x[0])

    # pylint: disable=unused-argument
    def get_postponing_delay(self, args: Tuple[Any, ...], kwargs: Dict[str, Any], value: float) -> float:
        return 5 - value


def test_run_artificial_function() -> None:
    func = ArtificialFunction(name="sphere", block_dimension=2)
    xp = xpbase.Experiment(func, optimizer="OnePlusOne", budget=24, num_workers=2, batch_mode=True, seed=12)
    summary = xp.run()
github facebookresearch / nevergrad / nevergrad / functions / games / game.py View on Github external
c = cards[0]  # at most 13
        # print(a, b, c, a*26*13+b*13+c, len(policy))
        if self.batawaf:
            seed = policy[a*18*6+b*6+c]  # type: ignore
        else:
            seed = policy[a*26*13+b*13+c]  # type: ignore
        if seed == 0.:
            return cards
        state = np.random.RandomState(hash(seed) % (2**32))
        state.shuffle(cards)
        return [c for c in cards]


# Real life is more complicated! This is a very simple model.
# pylint: disable=too-many-instance-attributes,too-many-arguments,too-many-statements,too-many-locals
class Game(inst.InstrumentedFunction):
    """
    Parameters
    ----------
    nint intaum_stocks: number of stocks to be managed
    depth: number of layers in the neural networks
    width: number of neurons per hidden layer
    """

    def __init__(self, game: str = "war") -> None:
        self.game = game
        self.game_object = _Game()
        the_dimension = self.game_object.play_game(self.game) * 2  # times 2 because we consider both players separately.
        instrumentation = Instrumentation(inst.var.Array(the_dimension))
        super().__init__(self._simulate_game, instrumentation)
        self.instrumentation.probably_noisy = True
        self.instrumentation.scrambled = True
github facebookresearch / nevergrad / nevergrad / functions / stsp / core.py View on Github external
# LICENSE file in the root directory of this source tree.
#
# Based on a discussion at Dagstuhl's seminar on Computational Intelligence in Games with:
# - Dan Ashlock
# - Chiara Sironi
# - Guenter Rudolph
# - Jialin Liu

import matplotlib.pyplot as plt
import numpy as np
from ... import instrumentation as inst
from ...instrumentation.multivariables import Instrumentation


# pylint: disable=too-many-instance-attributes,too-many-arguments,too-many-statements,too-many-locals
class STSP(inst.InstrumentedFunction):

    def __init__(self, seed: int = 0, the_dimension: int = 500) -> None:
        instrumentation = Instrumentation(inst.var.Array(the_dimension))
        self.x = instrumentation.random_state.normal(size=the_dimension)
        self.y = instrumentation.random_state.normal(size=the_dimension)
        super().__init__(self._simulate_stsp, instrumentation)
        self._descriptors.update(seed=seed)
        self.order = np.arange(0, self.instrumentation.dimension)

    def _simulate_stsp(self, x: np.ndarray) -> float:
        order = np.argsort(x)
        self.order = order
        x = self.x[order]
        y = self.y[order]
        output = np.sqrt((x[0] - x[-1])**2 + (y[0] - y[-1])**2) + sum(np.sqrt((x[i] - x[i + 1])**2 + (y[i] - y[i + 1])**2)
                                                                      for i in range(self.dimension - 1))
github facebookresearch / nevergrad / nevergrad / functions / rl / agents.py View on Github external
def __init__(self, module: nn.Module,
                 deterministic: bool = True,
                 instrumentation_std: float = 0.1) -> None:
        super().__init__()
        self.deterministic = deterministic
        self.module = module
        kwargs = {
            name: inst.var.Array(*value.shape).affined(a=instrumentation_std).bounded(-10, 10, transform="arctan")
            for name, value in module.state_dict().items()  # type: ignore
        }  # bounded to avoid overflows
        self.instrumentation = inst.Instrumentation(**kwargs)
github facebookresearch / nevergrad / nevergrad / functions / powersystems / core.py View on Github external
self.consumption_noise = consumption_noise
        self.num_thermal_plants = num_thermal_plants
        self.number_of_years = num_years
        self.failure_cost = failure_cost
        self.hydro_prod_per_time_step: List[Any] = []  # TODO @oteytaud initial values?
        self.consumption_per_time_step: List[Any] = []

        self.average_consumption = self.constant_to_year_ratio * self.year_to_day_ratio
        self.thermal_power_capacity = self.average_consumption * np.random.rand(self.num_thermal_plants)
        self.thermal_power_prices = np.random.rand(num_thermal_plants)
        dam_agents: List[Any] = []
        for _ in range(num_dams):
            dam_agents += [Agent(10 + num_dams + 2 * self.num_thermal_plants, depth, width)]
        the_dimension = sum([a.GetParamNumbers() for a in dam_agents])
        self.dam_agents = dam_agents
        super().__init__(self._simulate_power_system, Instrumentation(inst.var.Array(the_dimension)))
        self._descriptors.update(num_dams=num_dams, depth=depth, width=width)