Skip to content

autora.experimentalist.nearest_value

sample(conditions, reference_conditions, num_samples)

A experimentalist which returns the nearest values between the input samples and the allowed values, without replacement.

Parameters:

Name Type Description Default
conditions Union[DataFrame, ndarray]

The candidate samples of experimental conditions to be evaluated.

required
reference_conditions Union[DataFrame, ndarray]

Experimental conditions to which the distance is calculated

required
num_samples int

number of samples

required

Returns:

Type Description

the nearest values from allowed_samples to the samples

Source code in temp_dir/nearest-value/src/autora/experimentalist/nearest_value/__init__.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def sample(
    conditions: Union[pd.DataFrame, np.ndarray],
    reference_conditions: Union[pd.DataFrame, np.ndarray],
    num_samples: int,
):
    """
    A experimentalist which returns the nearest values between the input samples and the allowed
    values, without replacement.

    Args:
        conditions: The candidate samples of experimental conditions to be evaluated.
        reference_conditions: Experimental conditions to which the distance is calculated
        num_samples: number of samples

    Returns:
        the nearest values from `allowed_samples` to the `samples`

    """

    if isinstance(conditions, Iterable):
        conditions = np.array(list(conditions))

    if len(conditions.shape) == 1:
        conditions = conditions.reshape(-1, 1)

    if conditions.shape[0] < num_samples:
        raise Exception(
            "More samples requested than samples available in the set allowed of values."
        )

    X = np.array(reference_conditions)

    if X.shape[0] < num_samples:
        raise Exception("More samples requested than samples available in the pool.")

    x_new = np.empty((num_samples, conditions.shape[1]))

    # get index of row in x that is closest to each sample
    for row, sample in enumerate(X):

        if row >= num_samples:
            break

        dist = np.linalg.norm(conditions - sample, axis=1)
        idx = np.argmin(dist)
        x_new[row, :] = conditions[idx, :]
        conditions = np.delete(conditions, idx, axis=0)

    if isinstance(reference_conditions, pd.DataFrame):
        x_new = pd.DataFrame(x_new, columns=reference_conditions.columns)
    else:
        x_new = pd.DataFrame(x_new)

    return x_new