How to use nevergrad - 10 common examples

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 / functions / photonics / core.py View on Github external
assert not dimension % 4, f"points length should be a multiple of 4, got {dimension}"
    n = dimension // 4
    arrays: List[inst.var.Array] = []
    if name == "bragg":
        # n multiple of 2, from 16 to 80
        # domain (n=60): [2,3]^30 x [0,300]^30
        arrays.extend([inst.var.Array(n).bounded(2, 3, transform=transform) for _ in range(2)])
        arrays.extend([inst.var.Array(n).bounded(0, 300, transform=transform) for _ in range(2)])
    elif name == "chirped":
        # n multiple of 2, from 10 to 80
        # domain (n=60): [0,300]^60
        arrays = [inst.var.Array(n).bounded(0, 300, transform=transform) for _ in range(4)]
    elif name == "morpho":
        # n multiple of 4, from 16 to 60
        # domain (n=60): [0,300]^15 x [0,600]^15 x [30,600]^15 x [0,300]^15
        arrays.extend([inst.var.Array(n).bounded(0, 300, transform=transform),
                       inst.var.Array(n).bounded(0, 600, transform=transform),
                       inst.var.Array(n).bounded(30, 600, transform=transform),
                       inst.var.Array(n).bounded(0, 300, transform=transform)])
    else:
        raise NotImplementedError(f"Transform for {name} is not implemented")
    instrumentation = inst.Instrumentation(*arrays)
    assert instrumentation.dimension == dimension
    return instrumentation
github facebookresearch / nevergrad / nevergrad / optimization / optimizerlib.py View on Github external
else:
            if not num_optims:  # if no num_vars and no num_optims, just assume 2.
                num_optims = 2
            # num_vars not given: we will distribute variables equally.
        if num_optims > self.dimension:
            num_optims = self.dimension
        self.num_optims = num_optims
        self.optims: List[Any] = []
        self.num_vars: List[Any] = num_vars if num_vars else []
        self.instrumentations: List[Any] = []
        for i in range(self.num_optims):
            if not self.num_vars or len(self.num_vars) < i+1:
                self.num_vars += [(self.dimension // self.num_optims) + (self.dimension % self.num_optims > i)]
            
            assert self.num_vars[i] >= 1, "At least one variable per optimizer."
            self.instrumentations += [Instrumentation(inst.variables.Array(self.num_vars[i]).affined(1, 0))]
            assert len(self.optims) == i
            if self.num_vars[i] > 1:
                self.optims += [multivariate_optimizer(self.instrumentations[i], budget, num_workers)]  # noqa: F405
            else:
                self.optims += [monovariate_optimizer(self.instrumentations[i], budget, num_workers)]  # noqa: F405

        assert sum(self.num_vars) == self.dimension, f"sum(num_vars)={sum(self.num_vars)} should be equal to the dimension {self.dimension}."
github facebookresearch / nevergrad / nevergrad / functions / photonics / core.py View on Github external
Parameters
    name: str
        problem name, among bragg, chirped and morpho
    dimension: int
        size of the problem among 16, 40 and 60 (morpho) or 80 (bragg and chirped)
    transform: str
        transform type for the bounding ("arctan", "tanh" or "clipping", see `Array.bounded`)

    Returns
    -------
    Instrumentation
        the instrumentation for the problem
    """
    assert not dimension % 4, f"points length should be a multiple of 4, got {dimension}"
    n = dimension // 4
    arrays: List[inst.var.Array] = []
    if name == "bragg":
        # n multiple of 2, from 16 to 80
        # domain (n=60): [2,3]^30 x [0,300]^30
        arrays.extend([inst.var.Array(n).bounded(2, 3, transform=transform) for _ in range(2)])
        arrays.extend([inst.var.Array(n).bounded(0, 300, transform=transform) for _ in range(2)])
    elif name == "chirped":
        # n multiple of 2, from 10 to 80
        # domain (n=60): [0,300]^60
        arrays = [inst.var.Array(n).bounded(0, 300, transform=transform) for _ in range(4)]
    elif name == "morpho":
        # n multiple of 4, from 16 to 60
        # domain (n=60): [0,300]^15 x [0,600]^15 x [30,600]^15 x [0,300]^15
        arrays.extend([inst.var.Array(n).bounded(0, 300, transform=transform),
                       inst.var.Array(n).bounded(0, 600, transform=transform),
                       inst.var.Array(n).bounded(30, 600, transform=transform),
                       inst.var.Array(n).bounded(0, 300, transform=transform)])
github facebookresearch / nevergrad / nevergrad / common / test_testing.py View on Github external
@testing.parametrized(
    equal=([2, 3, 1], ""),
    missing=((1, 2), ["  - missing element(s): {3}."]),
    additional=((1, 4, 3, 2), ["  - additional element(s): {4}."]),
    both=((1, 2, 4), ["  - additional element(s): {4}.", "  - missing element(s): {3}."]),
)
def test_assert_set_equal(estimate: Iterable[int], message: str) -> None:
    reference = {1, 2, 3}
    try:
        testing.assert_set_equal(estimate, reference)
    except AssertionError as error:
        if not message:
            raise AssertionError("An error has been raised while it should not.")
        np.testing.assert_equal(error.args[0].split("\n")[1:], message)
    else:
        if message:
            raise AssertionError("An error should have been raised.")
github facebookresearch / nevergrad / nevergrad / benchmark / test_core.py View on Github external
def test_experiment_chunk_split() -> None:
    chunk = core.BenchmarkChunk(name="repeated_basic", seed=12, repetitions=2)
    chunks = chunk.split(2)
    chunks = [chunks[0]] + chunks[1].split(3)
    chained = [x[0] for x in itertools.chain.from_iterable(chunks)]
    # check full order (everythink only once)
    np.testing.assert_array_equal(chained, [0, 2, 4, 6, 8, 10, 12, 14, 16, 18,
                                            1, 7, 13, 19,
                                            3, 9, 15,
                                            5, 11, 17])
    testing.assert_set_equal(chained, range(20))
    assert chunks[0].id.endswith("_i0m2"), f"Wrong id {chunks[0].id}"
    assert chunks[0].id[:-4] == chunk.id[:-4], "Id prefix should be inherited"
github facebookresearch / nevergrad / nevergrad / benchmark / test_xpbase.py View on Github external
def test_seed_generator(seed: Optional[int], randsize: int, expected: List[Optional[int]]) -> None:
    output = []
    generator = xpbase.create_seed_generator(seed)
    for _ in range(4):
        if randsize:  # call the standard random generator
            np.random.normal(0, 1, size=randsize)
        value = next(generator)
        output.append(value if value is None else value % 1000)
    np.testing.assert_array_equal(output, expected)
github facebookresearch / nevergrad / nevergrad / instrumentation / test_transforms.py View on Github external
@testing.parametrized(
    tanh=(transforms.TanhBound(0, 5), [2, 4], None),
    tanh_err=(transforms.TanhBound(0, 5), [2, 4, 6], ValueError),
    clipping=(transforms.Clipping(0), [2, 4, 6], None),
    clipping_err=(transforms.Clipping(0), [-2, 4, 6], ValueError),
    arctan=(transforms.ArctanBound(0, 5), [2, 4, 5], None),
    arctan_err=(transforms.ArctanBound(0, 5), [-1, 4, 5], ValueError),
    cumdensity=(transforms.CumulativeDensity(), [0, .5], None),
    cumdensity_err=(transforms.CumulativeDensity(), [-0.1, .5], ValueError),
)
def test_out_of_bound(transform: transforms.Transform, x: List[float], expected: Optional[Type[Exception]]) -> None:
    if expected is None:
        transform.backward(np.array(x))
    else:
        with pytest.raises(expected):
            transform.backward(np.array(x))
github facebookresearch / nevergrad / nevergrad / instrumentation / test_discretization.py View on Github external
@testing.parametrized(
    arity2=(2, [0, -4, 0, 4, 0, 0], [0, 1, .5], [0, 1, 0]),
    arity2_1=(2, [0, 40], [1], [1]),
    arity3=(3, [0, -4, 0, 0, 4, 0], [1, 1], [0, 1]),  # first is 0 or 2, second is 1
    arity2_0_sum=(2, [0, 0], [.5], [0]),  # first is 0 or 2, second is 1
    pinf_case=(2, [0, np.inf], [1], [1]),
    nan_case=(2, [np.nan, 0], [1], [1]),
    ninf_case=(2, [-np.inf, 0], [1], [1]),
    all_ninf_case=(2, [-np.inf, -np.inf], [.5], [0]),
)
def test_softmax_discretization(arity: int, data: List[float], expected: List[float],
                                deterministic_expected: List[float]) -> None:
    coeffs = np.array(data, copy=True)
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        output = np.mean([discretization.softmax_discretization(coeffs, arity=arity) for _ in range(1000)], axis=0)
    np.testing.assert_array_equal(coeffs, data, err_msg="Input data was modified")
github facebookresearch / nevergrad / nevergrad / instrumentation / test_multivariables.py View on Github external
@testing.parametrized(
    empty=([], [], [])
)
def test_split_data(tokens: List[Variable], data: List[float], expected: List[List[float]]) -> None:
    instru = mvar.Instrumentation(*tokens)
    output = instru._split_data(np.array(data))
    testing.printed_assert_equal(output, expected)
github facebookresearch / nevergrad / nevergrad / functions / test_corefuncs.py View on Github external
@testing.parametrized(**{name: (name, func) for name, func in corefuncs.registry.items()})
def test_core_function(name: str, func: Callable[..., Any]) -> None:
    x = np.random.normal(0, 1, 100)
    outputs = []
    for _ in range(2):
        np.random.seed(12)
        outputs.append(func(x))
    np.testing.assert_equal(outputs[0], outputs[1], f'Function {name} is not deterministic')