Skip to content

Design-of-experiments¤

The Domain class defines the parameter space for your experiments, supporting continuous, discrete, categorical, constant, and array parameters.

f3dasm.design.Domain ¤

Main class for defining the domain of the design of experiments.

Parameters:

Name Type Description Default
input_space dict[str, Parameter]

Dict of input parameters, by default empty dict.

<factory>
output_space dict[str, Parameter]

Dict of output parameters, by default empty dict.

<factory>
Source code in src/f3dasm/_src/design/domain.py
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
@dataclass
class Domain:
    """Main class for defining the domain of the design of
    experiments.

    Parameters
    ----------
    input_space : dict[str, Parameter], optional
        Dict of input parameters, by default empty dict.
    output_space : dict[str, Parameter], optional
        Dict of output parameters, by default empty dict.
    """

    input_space: dict[str, Parameter] = field(default_factory=dict)
    output_space: dict[str, Parameter] = field(default_factory=dict)

    def __len__(self) -> int:
        """The len() method returns the number of input parameters.

        Returns
        -------
        int
            Number of input parameters.
        """
        return len(self.input_space)

    def __bool__(self) -> bool:
        """Check if the Domain object is empty.

        Returns
        -------
        bool
            False if both input and output spaces are empty, True
            otherwise.
        """
        return bool(self.input_space) or bool(self.output_space)

    def __str__(self):
        """Return a string representation of the Domain.

        Returns
        -------
        str
            String representation showing input and output spaces.
        """
        input_space_str = ", ".join(
            f"{k}: {v}" for k, v in self.input_space.items()
        )
        output_space_str = ", ".join(
            f"{k}: {v}" for k, v in self.output_space.items()
        )
        return (
            f"Domain(\n"
            f"  Input Space: {{ {input_space_str} }}\n"
            f"  Output Space: {{ {output_space_str} }}\n)"
        )

    def __repr__(self):
        """Return a representation of the Domain.

        Returns
        -------
        str
            Representation string of the Domain object.
        """
        return (
            f"{self.__class__.__name__}("
            f"input_space={repr(self.input_space)}, "
            f"output_space={repr(self.output_space)})"
        )

    def __add__(self, __o: Domain) -> Domain:
        """Add two Domain objects together.

        Parameters
        ----------
        __o : Domain
            The other Domain object to add.

        Returns
        -------
        Domain
            Combined Domain with merged input and output spaces.

        Raises
        ------
        TypeError
            If __o is not a Domain object.

        Notes
        -----
        For parameters that exist in both domains, their values are
        combined using the parameter's __add__ method.
        """
        if not isinstance(__o, Domain):
            raise TypeError(f"Cannot add Domain with {type(__o)}")

        combined_space = {}
        # Merge values for keys that are present in both dictionaries
        for key in self.input_space.keys():
            if key in __o.input_space:
                combined_space[key] = (
                    self.input_space[key] + __o.input_space[key]
                )
            else:
                combined_space[key] = self.input_space[key]

        # Add keys from dict2 that are not present in dict1
        for key in __o.input_space.keys():
            if key not in self.input_space:
                combined_space[key] = __o.input_space[key]

        return Domain(
            input_space=combined_space,
            output_space={**self.output_space, **__o.output_space},
        )

    def _copy(self) -> Domain:
        """
        Return a copy of the Domain object.

        Returns
        -------
        Domain
            Copy of the Domain object.
        """
        return Domain(
            input_space={k: copy.copy(v) for k, v in self.input_space.items()},
            output_space={
                k: copy.copy(v) for k, v in self.output_space.items()
            },
        )

    @property
    def input_names(self) -> list[str]:
        """
        Retrieve the input space names.

        Returns
        -------
        list[str]
            List of the names of the input parameters.
        """
        return list(self.input_space.keys())

    @property
    def output_names(self) -> list[str]:
        """
        Retrieve the output space names.

        Returns
        -------
        list[str]
            List of the names of the output parameters.
        """
        return list(self.output_space.keys())

    #                                                  Alternative constructors
    # =========================================================================

    @classmethod
    def from_file(cls: type[Domain], filename: Path | str) -> Domain:
        """
        Create a Domain object from a JSON file.

        Parameters
        ----------
        filename : Path or str
            Path of the JSON file to load the Domain object from.

        Returns
        -------
        Domain
            Domain object containing the loaded design spaces.

        Examples
        --------
        >>> domain = Domain.from_file('domain.json')
        """
        # convert filename to Path object
        filename = Path(filename).with_suffix(".json")

        # Check if filename exists
        if not filename.exists():
            raise FileNotFoundError(f"Domain file {filename} does not exist.")

        if filename.stat().st_size == 0:
            raise EmptyFileError(filename)

        try:
            with open(filename) as f:
                domain_dict = json.load(f)
        except json.JSONDecodeError as exc:
            raise DecodeError(filename) from exc

        input_space = {
            k: Parameter.from_dict(v)
            for k, v in domain_dict["input_space"].items()
        }
        output_space = {
            k: Parameter.from_dict(v)
            for k, v in domain_dict["output_space"].items()
        }

        return cls(input_space=input_space, output_space=output_space)

    @classmethod
    def from_yaml(cls: type[Domain], cfg: DictConfig) -> Domain:
        """Initialize a Domain from a Hydra YAML configuration file key.

        Parameters
        ----------
        cfg : DictConfig
            YAML dictionary key of the domain.

        Returns
        -------
        Domain
            Domain object.

        Notes
        ----
        The YAML file should have the following structure:

        .. code-block:: yaml

            domain:
                input:
                    <parameter_name>:
                        type: <parameter_type>
                        <parameter_type_specific_parameters>
                    <parameter_name>:
                        type: <parameter_type>
                        <parameter_type_specific_parameters>
                output:
                    <parameter_name>:
                        to_disk: <bool>
        """

        def process_input(items):
            for key, value in items.items():
                _dict = OmegaConf.to_container(value, resolve=True)
                domain.add(name=key, type=_dict.pop("type", None), **_dict)

        def process_output(items):
            for key, value in items.items():
                _dict = OmegaConf.to_container(value, resolve=True)
                domain.add_output(name=key, **_dict)

        domain = cls()

        if "input" in cfg:
            process_input(cfg.input)
        else:
            process_input(cfg)

        if "output" in cfg:
            process_output(cfg.output)

        return domain

    @classmethod
    def from_data(
        cls,
        input_data: list[dict[str, Any]],
        output_data: list[dict[str, Any]],
    ) -> Domain:
        """
        Initialize a Domain from input and output data.

        Parameters
        ----------
        input_data : list[dict[str, Any]]
            List of dictionaries containing the input parameters.
        output_data : list[dict[str, Any]]
            List of dictionaries containing the output parameters.

        Returns
        -------
        Domain
            Domain object containing the input and output parameter names.
        """
        all_input_parameters, all_output_parameters = set(), set()
        for experiment_input, experiment_output in zip_longest(
            input_data, output_data, fillvalue={}
        ):
            all_input_parameters.update(experiment_input.keys())
            all_output_parameters.update(experiment_output.keys())

        input_names = sorted(list(all_input_parameters))
        output_names = sorted(list(all_output_parameters))

        input_space = {name: Parameter() for name in input_names}
        output_space = {name: Parameter() for name in output_names}

        return cls(input_space=input_space, output_space=output_space)

    #                                                                    Export
    # =========================================================================

    def store(self, filename: Path | str) -> None:
        """
        Store the Domain object and its parameters as a JSON file.

        Parameters
        ----------
        filename : Path or str
            Path of the JSON file to store the Domain object.

        Examples
        --------
        >>> domain.store('domain.json')
        """
        domain_dict = {
            "input_space": {
                k: v.to_dict() for k, v in self.input_space.items()
            },
            "output_space": {
                k: v.to_dict() for k, v in self.output_space.items()
            },
        }
        with open(Path(filename).with_suffix(".json"), "w") as f:
            json.dump(domain_dict, f, indent=4)

    #                                              Append and remove parameters
    # =========================================================================

    def _add(self, name: str, parameter: Parameter):
        """
        Add a new input parameter to the domain.

        Parameters
        ----------
        name : str
            Name of the input parameter.
        parameter : Parameter
            Parameter object to be added to the domain.
        """
        # Check if parameter is already in the domain
        if name in self.input_space:
            raise KeyError(
                f"Parameter {name} already exists in the domain! \
                     Choose a different name."
            )

        self.input_space[name] = parameter

    def add_parameter(
        self,
        name: str,
        to_disk=False,
        store_function: Optional[StoreFunction] = None,
        load_function: Optional[LoadFunction] = None,
        load_kwargs: Optional[dict[str, Any]] = None,
    ):
        """Add a new parameter to the domain.

        Parameters
        ----------
        name : str
            Name of the input parameter.
        to_disk : bool, optional
            Whether to store the parameter to disk, by default False.
        store_function : StoreFunction, optional
            Function to store the parameter, by default None.
        load_function : LoadFunction, optional
            Function to load the parameter, by default None.
        load_kwargs : dict[str, Any], optional
            Extra keyword arguments forwarded to `load_function` each
            time the stored object is loaded. Useful when the
            deserialiser needs auxiliary state (e.g. an `equinox`
            template via ``load_kwargs={"like": template}``). Defaults
            to None.

        Examples
        -------
        >>> domain = Domain()
        >>> domain.add_parameter('param1', store_function, load_function)
        >>> domain.input_space
        {'param1': Parameter(store_function=store_function,
        load_function=load_function)}
        """
        self._add(
            name,
            Parameter(
                store_function=store_function,
                load_function=load_function,
                load_kwargs=load_kwargs,
                to_disk=to_disk,
            ),
        )

    def add_int(self, name: str, low: int, high: int, step: int = 1):
        """Add a new discrete input parameter to the domain.

        Parameters
        ----------
        name : str
            Name of the input parameter.
        low : int
            Lower bound of the input parameter.
        high : int
            Upper bound of the input parameter.
        step : int, optional
            Step size of the input parameter, by default 1.

        Examples
        -------
        >>> domain = Domain()
        >>> domain.add_int('param1', 0, 10, 2)
        >>> domain.input_space
        {'param1': DiscreteParameter(lower_bound=0, upper_bound=10, step=2)}

        Notes
        -----
        If the lower and upper bound are equal, then a constant parameter
        will be added to the domain.
        """
        if low == high:
            self.add_constant(name, low)
        else:
            self._add(name, DiscreteParameter(low, high, step))

    def add_float(
        self,
        name: str,
        low: float = -np.inf,
        high: float = np.inf,
        log: bool = False,
    ):
        """Add a new continuous input parameter to the domain.

        Parameters
        ----------
        name : str
            Name of the input parameter.
        low : float, optional
            Lower bound of the input parameter, by default -np.inf.
        high : float, optional
            Upper bound of the input parameter, by default np.inf.
        log : bool, optional
            Whether to use a logarithmic scale, by default False.

        Examples
        -------
        >>> domain = Domain()
        >>> domain.add_float('param1', 0., 10., log=True)
        >>> domain.input_space
        {'param1': ContinuousParameter(lower_bound=0.,
         upper_bound=10., log=True)}

        Notes
        -----
        If the lower and upper bound are equal, then a constant parameter
        will be added to the domain.
        """
        if math.isclose(low, high):
            self.add_constant(name, low)
        else:
            self._add(name, ContinuousParameter(low, high, log))

    def add_category(self, name: str, categories: Sequence[CategoricalType]):
        """Add a new categorical input parameter to the domain.

        Parameters
        ----------
        name : str
            Name of the input parameter.
        categories : Sequence[CategoricalType]
            Categories of the input parameter.

        Examples
        -------
        >>> domain = Domain()
        >>> domain.add_category('param1', [0, 1, 2])
        >>> domain.input_space
        {'param1': CategoricalParameter(categories=[0, 1, 2])}
        """
        self._add(name, CategoricalParameter(categories))

    def add_constant(self, name: str, value: Any):
        """Add a new constant input parameter to the domain.

        Parameters
        ----------
        name : str
            Name of the input parameter.
        value : Any
            Value of the input parameter.

        Examples
        -------
        >>> domain = Domain()
        >>> domain.add_constant('param1', 0)
        >>> domain.input_space
        {'param1': ConstantParameter(value=0)}
        """
        self._add(name, ConstantParameter(value))

    def add_array(
        self,
        name: str,
        shape: int | Sequence[int],
        low: float = -np.inf,
        high: float = np.inf,
    ):
        """Add a new array input parameter to the domain.

        Parameters
        ----------
        name : str
            Name of the input parameter.
        shape : Sequence[int] or int
            Shape of the array input parameter.
        low : float or np.ndarray, optional
            Lower bound of the input parameter, by default -np.inf.
        high : float or np.ndarray, optional
            Upper bound of the input parameter, by default np.inf.

        Examples
        -------
        >>> domain = Domain()
        >>> domain.add_array('param1', [3, 4], 0., 1.)
        >>> domain.input_space
        {'param1': ArrayParameter(shape=[3, 4], lower_bound=0.0,
        upper_bound=1.0)}
        """
        self._add(
            name,
            ArrayParameter(shape=shape, lower_bound=low, upper_bound=high),
        )

    def add(
        self,
        name: str,
        type: Literal["float", "int", "category", "constant", "array"],
        **kwargs,
    ):
        """Add a new input parameter to the domain.

        Parameters
        ----------
        name : str
            Name of the input parameter.
        type : {'float', 'int', 'category', 'constant', 'array'}
            Type of the input parameter.
        **kwargs
            Keyword arguments for the input parameter.

        Raises
        ------
        ValueError
            If the type is not known.

        Examples
        -------
        >>> domain = Domain()
        >>> domain.add('param1', 'float', low=0., high=1.)
        >>> domain.input_space
        {'param1': ContinuousParameter(lower_bound=0., upper_bound=1.)}
        """

        if type == "float":
            self.add_float(name, **kwargs)
        elif type == "int":
            self.add_int(name, **kwargs)
        elif type == "category":
            self.add_category(name, **kwargs)
        elif type == "constant":
            self.add_constant(name, **kwargs)
        elif type == "array":
            self.add_array(name, **kwargs)
        else:
            raise ValueError(
                f"Unknown type {type}!"
                f"Possible types are: 'float', 'int', 'category', 'constant'."
            )

    def add_output(
        self,
        name: str,
        to_disk: bool = False,
        exist_ok: bool = False,
        store_function: Optional[StoreFunction] = None,
        load_function: Optional[LoadFunction] = None,
        load_kwargs: Optional[dict[str, Any]] = None,
    ):
        """Add a new output parameter to the domain.

        Parameters
        ----------
        name : str
            Name of the output parameter.
        to_disk : bool, optional
            Whether to store the output parameter on disk,
            by default False.
        exist_ok : bool, optional
            Whether to raise an error if the output parameter
            already exists, by default False.
        store_function : StoreFunction, optional
            Function to store the parameter, by default None.
        load_function : LoadFunction, optional
            Function to load the parameter, by default None.
        load_kwargs : dict[str, Any], optional
            Extra keyword arguments forwarded to `load_function` each
            time the stored object is loaded. Defaults to None.

        Examples
        -------
        >>> domain = Domain()
        >>> domain.add_output('param1', True)
        >>> domain.output_space
        {'param1': Parameter(to_disk=True)}
        """
        if name in self.output_space:
            if not exist_ok:
                raise KeyError(
                    f"Parameter {name} already exists in the domain! \
                        Choose a different name."
                )
            return

        self.output_space[name] = Parameter(
            to_disk=to_disk,
            store_function=store_function,
            load_function=load_function,
            load_kwargs=load_kwargs,
        )

    #                                                                   Getters
    # =========================================================================

    def get_bounds(self) -> np.ndarray:
        """Return the boundary constraints of the continuous input
        parameters.

        Returns
        -------
        np.ndarray
            Numpy array with lower and upper bound for each continuous
            input dimension.

        Examples
        -------
        >>> domain = Domain()
        >>> domain.input_space = {
        ...     'param1': ContinuousParameter(lower_bound=0, upper_bound=1),
        ...     'param2': ContinuousParameter(lower_bound=-1, upper_bound=1),
        ...     'param3': ContinuousParameter(lower_bound=0, upper_bound=10)
        ... }
        >>> bounds = domain.get_bounds()
        >>> bounds
        array([[ 0.,  1.],
            [-1.,  1.],
            [ 0., 10.]])
        """
        return np.array(
            [
                [parameter.lower_bound, parameter.upper_bound]
                for _, parameter in self.input_space.items()
            ]
        )

    def _filter(self, type: type[Parameter]) -> Domain:
        """Filter the parameters of the domain by type.

        Parameters
        ----------
        type : type[Parameter]
            Type of the parameters to be filtered.

        Returns
        -------
        Domain
            Domain with the filtered parameters.

        Examples
        -------
        >>> domain = Domain()
        >>> domain.input_space = {
        ...     'param1': ContinuousParameter(lower_bound=0., upper_bound=1.),
        ...     'param2': DiscreteParameter(lower_bound=0, upper_bound=8),
        ...     'param3': CategoricalParameter(categories=['cat1', 'cat2'])
        ... }
        >>> filtered_domain = domain._filter(ContinuousParameter)
        >>> filtered_domain.input_space
        {'param1': ContinuousParameter(lower_bound=0, upper_bound=1)}

        """
        return Domain(
            input_space={
                name: parameter
                for name, parameter in self.input_space.items()
                if isinstance(parameter, type)
            }
        )
input_names property ¤

Retrieve the input space names.

Returns:

Type Description
list[str]

List of the names of the input parameters.

output_names property ¤

Retrieve the output space names.

Returns:

Type Description
list[str]

List of the names of the output parameters.

_add(name: str, parameter: Parameter) ¤

Add a new input parameter to the domain.

Parameters:

Name Type Description Default
name str

Name of the input parameter.

required
parameter Parameter

Parameter object to be added to the domain.

required
Source code in src/f3dasm/_src/design/domain.py
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
def _add(self, name: str, parameter: Parameter):
    """
    Add a new input parameter to the domain.

    Parameters
    ----------
    name : str
        Name of the input parameter.
    parameter : Parameter
        Parameter object to be added to the domain.
    """
    # Check if parameter is already in the domain
    if name in self.input_space:
        raise KeyError(
            f"Parameter {name} already exists in the domain! \
                 Choose a different name."
        )

    self.input_space[name] = parameter
_copy() -> Domain ¤

Return a copy of the Domain object.

Returns:

Type Description
Domain

Copy of the Domain object.

Source code in src/f3dasm/_src/design/domain.py
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
def _copy(self) -> Domain:
    """
    Return a copy of the Domain object.

    Returns
    -------
    Domain
        Copy of the Domain object.
    """
    return Domain(
        input_space={k: copy.copy(v) for k, v in self.input_space.items()},
        output_space={
            k: copy.copy(v) for k, v in self.output_space.items()
        },
    )
_filter(type: type[Parameter]) -> Domain ¤

Filter the parameters of the domain by type.

Parameters:

Name Type Description Default
type type[Parameter]

Type of the parameters to be filtered.

required

Returns:

Type Description
Domain

Domain with the filtered parameters.

Examples:

>>> domain = Domain()
>>> domain.input_space = {
...     'param1': ContinuousParameter(lower_bound=0., upper_bound=1.),
...     'param2': DiscreteParameter(lower_bound=0, upper_bound=8),
...     'param3': CategoricalParameter(categories=['cat1', 'cat2'])
... }
>>> filtered_domain = domain._filter(ContinuousParameter)
>>> filtered_domain.input_space
{'param1': ContinuousParameter(lower_bound=0, upper_bound=1)}
Source code in src/f3dasm/_src/design/domain.py
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
def _filter(self, type: type[Parameter]) -> Domain:
    """Filter the parameters of the domain by type.

    Parameters
    ----------
    type : type[Parameter]
        Type of the parameters to be filtered.

    Returns
    -------
    Domain
        Domain with the filtered parameters.

    Examples
    -------
    >>> domain = Domain()
    >>> domain.input_space = {
    ...     'param1': ContinuousParameter(lower_bound=0., upper_bound=1.),
    ...     'param2': DiscreteParameter(lower_bound=0, upper_bound=8),
    ...     'param3': CategoricalParameter(categories=['cat1', 'cat2'])
    ... }
    >>> filtered_domain = domain._filter(ContinuousParameter)
    >>> filtered_domain.input_space
    {'param1': ContinuousParameter(lower_bound=0, upper_bound=1)}

    """
    return Domain(
        input_space={
            name: parameter
            for name, parameter in self.input_space.items()
            if isinstance(parameter, type)
        }
    )
add(name: str, type: Literal[float, int, category, constant, array], **kwargs) ¤

Add a new input parameter to the domain.

Parameters:

Name Type Description Default
name str

Name of the input parameter.

required
type (float, int, category, constant, array)

Type of the input parameter.

'float'
**kwargs

Keyword arguments for the input parameter.

required

Raises:

Type Description
ValueError

If the type is not known.

Examples:

>>> domain = Domain()
>>> domain.add('param1', 'float', low=0., high=1.)
>>> domain.input_space
{'param1': ContinuousParameter(lower_bound=0., upper_bound=1.)}
Source code in src/f3dasm/_src/design/domain.py
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
def add(
    self,
    name: str,
    type: Literal["float", "int", "category", "constant", "array"],
    **kwargs,
):
    """Add a new input parameter to the domain.

    Parameters
    ----------
    name : str
        Name of the input parameter.
    type : {'float', 'int', 'category', 'constant', 'array'}
        Type of the input parameter.
    **kwargs
        Keyword arguments for the input parameter.

    Raises
    ------
    ValueError
        If the type is not known.

    Examples
    -------
    >>> domain = Domain()
    >>> domain.add('param1', 'float', low=0., high=1.)
    >>> domain.input_space
    {'param1': ContinuousParameter(lower_bound=0., upper_bound=1.)}
    """

    if type == "float":
        self.add_float(name, **kwargs)
    elif type == "int":
        self.add_int(name, **kwargs)
    elif type == "category":
        self.add_category(name, **kwargs)
    elif type == "constant":
        self.add_constant(name, **kwargs)
    elif type == "array":
        self.add_array(name, **kwargs)
    else:
        raise ValueError(
            f"Unknown type {type}!"
            f"Possible types are: 'float', 'int', 'category', 'constant'."
        )
add_array(name: str, shape: int | Sequence[int], low: float = -inf, high: float = inf) ¤

Add a new array input parameter to the domain.

Parameters:

Name Type Description Default
name str

Name of the input parameter.

required
shape Sequence[int] or int

Shape of the array input parameter.

required
low float or ndarray

Lower bound of the input parameter, by default -np.inf.

-inf
high float or ndarray

Upper bound of the input parameter, by default np.inf.

inf

Examples:

>>> domain = Domain()
>>> domain.add_array('param1', [3, 4], 0., 1.)
>>> domain.input_space
{'param1': ArrayParameter(shape=[3, 4], lower_bound=0.0,
upper_bound=1.0)}
Source code in src/f3dasm/_src/design/domain.py
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
def add_array(
    self,
    name: str,
    shape: int | Sequence[int],
    low: float = -np.inf,
    high: float = np.inf,
):
    """Add a new array input parameter to the domain.

    Parameters
    ----------
    name : str
        Name of the input parameter.
    shape : Sequence[int] or int
        Shape of the array input parameter.
    low : float or np.ndarray, optional
        Lower bound of the input parameter, by default -np.inf.
    high : float or np.ndarray, optional
        Upper bound of the input parameter, by default np.inf.

    Examples
    -------
    >>> domain = Domain()
    >>> domain.add_array('param1', [3, 4], 0., 1.)
    >>> domain.input_space
    {'param1': ArrayParameter(shape=[3, 4], lower_bound=0.0,
    upper_bound=1.0)}
    """
    self._add(
        name,
        ArrayParameter(shape=shape, lower_bound=low, upper_bound=high),
    )
add_category(name: str, categories: Sequence[CategoricalType]) ¤

Add a new categorical input parameter to the domain.

Parameters:

Name Type Description Default
name str

Name of the input parameter.

required
categories Sequence[Union]

Categories of the input parameter.

required

Examples:

>>> domain = Domain()
>>> domain.add_category('param1', [0, 1, 2])
>>> domain.input_space
{'param1': CategoricalParameter(categories=[0, 1, 2])}
Source code in src/f3dasm/_src/design/domain.py
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
def add_category(self, name: str, categories: Sequence[CategoricalType]):
    """Add a new categorical input parameter to the domain.

    Parameters
    ----------
    name : str
        Name of the input parameter.
    categories : Sequence[CategoricalType]
        Categories of the input parameter.

    Examples
    -------
    >>> domain = Domain()
    >>> domain.add_category('param1', [0, 1, 2])
    >>> domain.input_space
    {'param1': CategoricalParameter(categories=[0, 1, 2])}
    """
    self._add(name, CategoricalParameter(categories))
add_constant(name: str, value: Any) ¤

Add a new constant input parameter to the domain.

Parameters:

Name Type Description Default
name str

Name of the input parameter.

required
value Any

Value of the input parameter.

required

Examples:

>>> domain = Domain()
>>> domain.add_constant('param1', 0)
>>> domain.input_space
{'param1': ConstantParameter(value=0)}
Source code in src/f3dasm/_src/design/domain.py
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
def add_constant(self, name: str, value: Any):
    """Add a new constant input parameter to the domain.

    Parameters
    ----------
    name : str
        Name of the input parameter.
    value : Any
        Value of the input parameter.

    Examples
    -------
    >>> domain = Domain()
    >>> domain.add_constant('param1', 0)
    >>> domain.input_space
    {'param1': ConstantParameter(value=0)}
    """
    self._add(name, ConstantParameter(value))
add_float(name: str, low: float = -inf, high: float = inf, log: bool = False) ¤

Add a new continuous input parameter to the domain.

Parameters:

Name Type Description Default
name str

Name of the input parameter.

required
low float

Lower bound of the input parameter, by default -np.inf.

-inf
high float

Upper bound of the input parameter, by default np.inf.

inf
log bool

Whether to use a logarithmic scale, by default False.

False

Examples:

>>> domain = Domain()
>>> domain.add_float('param1', 0., 10., log=True)
>>> domain.input_space
{'param1': ContinuousParameter(lower_bound=0.,
 upper_bound=10., log=True)}
Notes

If the lower and upper bound are equal, then a constant parameter will be added to the domain.

Source code in src/f3dasm/_src/design/domain.py
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
def add_float(
    self,
    name: str,
    low: float = -np.inf,
    high: float = np.inf,
    log: bool = False,
):
    """Add a new continuous input parameter to the domain.

    Parameters
    ----------
    name : str
        Name of the input parameter.
    low : float, optional
        Lower bound of the input parameter, by default -np.inf.
    high : float, optional
        Upper bound of the input parameter, by default np.inf.
    log : bool, optional
        Whether to use a logarithmic scale, by default False.

    Examples
    -------
    >>> domain = Domain()
    >>> domain.add_float('param1', 0., 10., log=True)
    >>> domain.input_space
    {'param1': ContinuousParameter(lower_bound=0.,
     upper_bound=10., log=True)}

    Notes
    -----
    If the lower and upper bound are equal, then a constant parameter
    will be added to the domain.
    """
    if math.isclose(low, high):
        self.add_constant(name, low)
    else:
        self._add(name, ContinuousParameter(low, high, log))
add_int(name: str, low: int, high: int, step: int = 1) ¤

Add a new discrete input parameter to the domain.

Parameters:

Name Type Description Default
name str

Name of the input parameter.

required
low int

Lower bound of the input parameter.

required
high int

Upper bound of the input parameter.

required
step int

Step size of the input parameter, by default 1.

1

Examples:

>>> domain = Domain()
>>> domain.add_int('param1', 0, 10, 2)
>>> domain.input_space
{'param1': DiscreteParameter(lower_bound=0, upper_bound=10, step=2)}
Notes

If the lower and upper bound are equal, then a constant parameter will be added to the domain.

Source code in src/f3dasm/_src/design/domain.py
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
def add_int(self, name: str, low: int, high: int, step: int = 1):
    """Add a new discrete input parameter to the domain.

    Parameters
    ----------
    name : str
        Name of the input parameter.
    low : int
        Lower bound of the input parameter.
    high : int
        Upper bound of the input parameter.
    step : int, optional
        Step size of the input parameter, by default 1.

    Examples
    -------
    >>> domain = Domain()
    >>> domain.add_int('param1', 0, 10, 2)
    >>> domain.input_space
    {'param1': DiscreteParameter(lower_bound=0, upper_bound=10, step=2)}

    Notes
    -----
    If the lower and upper bound are equal, then a constant parameter
    will be added to the domain.
    """
    if low == high:
        self.add_constant(name, low)
    else:
        self._add(name, DiscreteParameter(low, high, step))
add_output(name: str, to_disk: bool = False, exist_ok: bool = False, store_function: Optional[StoreFunction] = None, load_function: Optional[LoadFunction] = None, load_kwargs: Optional[dict[str, Any]] = None) ¤

Add a new output parameter to the domain.

Parameters:

Name Type Description Default
name str

Name of the output parameter.

required
to_disk bool

Whether to store the output parameter on disk, by default False.

False
exist_ok bool

Whether to raise an error if the output parameter already exists, by default False.

False
store_function StoreFunction

Function to store the parameter, by default None.

None
load_function LoadFunction

Function to load the parameter, by default None.

None
load_kwargs dict[str, Any]

Extra keyword arguments forwarded to load_function each time the stored object is loaded. Defaults to None.

None

Examples:

>>> domain = Domain()
>>> domain.add_output('param1', True)
>>> domain.output_space
{'param1': Parameter(to_disk=True)}
Source code in src/f3dasm/_src/design/domain.py
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
def add_output(
    self,
    name: str,
    to_disk: bool = False,
    exist_ok: bool = False,
    store_function: Optional[StoreFunction] = None,
    load_function: Optional[LoadFunction] = None,
    load_kwargs: Optional[dict[str, Any]] = None,
):
    """Add a new output parameter to the domain.

    Parameters
    ----------
    name : str
        Name of the output parameter.
    to_disk : bool, optional
        Whether to store the output parameter on disk,
        by default False.
    exist_ok : bool, optional
        Whether to raise an error if the output parameter
        already exists, by default False.
    store_function : StoreFunction, optional
        Function to store the parameter, by default None.
    load_function : LoadFunction, optional
        Function to load the parameter, by default None.
    load_kwargs : dict[str, Any], optional
        Extra keyword arguments forwarded to `load_function` each
        time the stored object is loaded. Defaults to None.

    Examples
    -------
    >>> domain = Domain()
    >>> domain.add_output('param1', True)
    >>> domain.output_space
    {'param1': Parameter(to_disk=True)}
    """
    if name in self.output_space:
        if not exist_ok:
            raise KeyError(
                f"Parameter {name} already exists in the domain! \
                    Choose a different name."
            )
        return

    self.output_space[name] = Parameter(
        to_disk=to_disk,
        store_function=store_function,
        load_function=load_function,
        load_kwargs=load_kwargs,
    )
add_parameter(name: str, to_disk=False, store_function: Optional[StoreFunction] = None, load_function: Optional[LoadFunction] = None, load_kwargs: Optional[dict[str, Any]] = None) ¤

Add a new parameter to the domain.

Parameters:

Name Type Description Default
name str

Name of the input parameter.

required
to_disk bool

Whether to store the parameter to disk, by default False.

False
store_function StoreFunction

Function to store the parameter, by default None.

None
load_function LoadFunction

Function to load the parameter, by default None.

None
load_kwargs dict[str, Any]

Extra keyword arguments forwarded to load_function each time the stored object is loaded. Useful when the deserialiser needs auxiliary state (e.g. an equinox template via load_kwargs={"like": template}). Defaults to None.

None

Examples:

>>> domain = Domain()
>>> domain.add_parameter('param1', store_function, load_function)
>>> domain.input_space
{'param1': Parameter(store_function=store_function,
load_function=load_function)}
Source code in src/f3dasm/_src/design/domain.py
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
def add_parameter(
    self,
    name: str,
    to_disk=False,
    store_function: Optional[StoreFunction] = None,
    load_function: Optional[LoadFunction] = None,
    load_kwargs: Optional[dict[str, Any]] = None,
):
    """Add a new parameter to the domain.

    Parameters
    ----------
    name : str
        Name of the input parameter.
    to_disk : bool, optional
        Whether to store the parameter to disk, by default False.
    store_function : StoreFunction, optional
        Function to store the parameter, by default None.
    load_function : LoadFunction, optional
        Function to load the parameter, by default None.
    load_kwargs : dict[str, Any], optional
        Extra keyword arguments forwarded to `load_function` each
        time the stored object is loaded. Useful when the
        deserialiser needs auxiliary state (e.g. an `equinox`
        template via ``load_kwargs={"like": template}``). Defaults
        to None.

    Examples
    -------
    >>> domain = Domain()
    >>> domain.add_parameter('param1', store_function, load_function)
    >>> domain.input_space
    {'param1': Parameter(store_function=store_function,
    load_function=load_function)}
    """
    self._add(
        name,
        Parameter(
            store_function=store_function,
            load_function=load_function,
            load_kwargs=load_kwargs,
            to_disk=to_disk,
        ),
    )
from_data(input_data: list[dict[str, Any]], output_data: list[dict[str, Any]]) -> Domain classmethod ¤

Initialize a Domain from input and output data.

Parameters:

Name Type Description Default
input_data list[dict[str, Any]]

List of dictionaries containing the input parameters.

required
output_data list[dict[str, Any]]

List of dictionaries containing the output parameters.

required

Returns:

Type Description
Domain

Domain object containing the input and output parameter names.

Source code in src/f3dasm/_src/design/domain.py
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
@classmethod
def from_data(
    cls,
    input_data: list[dict[str, Any]],
    output_data: list[dict[str, Any]],
) -> Domain:
    """
    Initialize a Domain from input and output data.

    Parameters
    ----------
    input_data : list[dict[str, Any]]
        List of dictionaries containing the input parameters.
    output_data : list[dict[str, Any]]
        List of dictionaries containing the output parameters.

    Returns
    -------
    Domain
        Domain object containing the input and output parameter names.
    """
    all_input_parameters, all_output_parameters = set(), set()
    for experiment_input, experiment_output in zip_longest(
        input_data, output_data, fillvalue={}
    ):
        all_input_parameters.update(experiment_input.keys())
        all_output_parameters.update(experiment_output.keys())

    input_names = sorted(list(all_input_parameters))
    output_names = sorted(list(all_output_parameters))

    input_space = {name: Parameter() for name in input_names}
    output_space = {name: Parameter() for name in output_names}

    return cls(input_space=input_space, output_space=output_space)
from_file(filename: Path | str) -> Domain classmethod ¤

Create a Domain object from a JSON file.

Parameters:

Name Type Description Default
filename Path or str

Path of the JSON file to load the Domain object from.

required

Returns:

Type Description
Domain

Domain object containing the loaded design spaces.

Examples:

>>> domain = Domain.from_file('domain.json')
Source code in src/f3dasm/_src/design/domain.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
@classmethod
def from_file(cls: type[Domain], filename: Path | str) -> Domain:
    """
    Create a Domain object from a JSON file.

    Parameters
    ----------
    filename : Path or str
        Path of the JSON file to load the Domain object from.

    Returns
    -------
    Domain
        Domain object containing the loaded design spaces.

    Examples
    --------
    >>> domain = Domain.from_file('domain.json')
    """
    # convert filename to Path object
    filename = Path(filename).with_suffix(".json")

    # Check if filename exists
    if not filename.exists():
        raise FileNotFoundError(f"Domain file {filename} does not exist.")

    if filename.stat().st_size == 0:
        raise EmptyFileError(filename)

    try:
        with open(filename) as f:
            domain_dict = json.load(f)
    except json.JSONDecodeError as exc:
        raise DecodeError(filename) from exc

    input_space = {
        k: Parameter.from_dict(v)
        for k, v in domain_dict["input_space"].items()
    }
    output_space = {
        k: Parameter.from_dict(v)
        for k, v in domain_dict["output_space"].items()
    }

    return cls(input_space=input_space, output_space=output_space)
from_yaml(cfg: DictConfig) -> Domain classmethod ¤

Initialize a Domain from a Hydra YAML configuration file key.

Parameters:

Name Type Description Default
cfg DictConfig

YAML dictionary key of the domain.

required

Returns:

Type Description
Domain

Domain object.

Notes

The YAML file should have the following structure:

.. code-block:: yaml

domain:
    input:
        <parameter_name>:
            type: <parameter_type>
            <parameter_type_specific_parameters>
        <parameter_name>:
            type: <parameter_type>
            <parameter_type_specific_parameters>
    output:
        <parameter_name>:
            to_disk: <bool>
Source code in src/f3dasm/_src/design/domain.py
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
@classmethod
def from_yaml(cls: type[Domain], cfg: DictConfig) -> Domain:
    """Initialize a Domain from a Hydra YAML configuration file key.

    Parameters
    ----------
    cfg : DictConfig
        YAML dictionary key of the domain.

    Returns
    -------
    Domain
        Domain object.

    Notes
    ----
    The YAML file should have the following structure:

    .. code-block:: yaml

        domain:
            input:
                <parameter_name>:
                    type: <parameter_type>
                    <parameter_type_specific_parameters>
                <parameter_name>:
                    type: <parameter_type>
                    <parameter_type_specific_parameters>
            output:
                <parameter_name>:
                    to_disk: <bool>
    """

    def process_input(items):
        for key, value in items.items():
            _dict = OmegaConf.to_container(value, resolve=True)
            domain.add(name=key, type=_dict.pop("type", None), **_dict)

    def process_output(items):
        for key, value in items.items():
            _dict = OmegaConf.to_container(value, resolve=True)
            domain.add_output(name=key, **_dict)

    domain = cls()

    if "input" in cfg:
        process_input(cfg.input)
    else:
        process_input(cfg)

    if "output" in cfg:
        process_output(cfg.output)

    return domain
get_bounds() -> np.ndarray ¤

Return the boundary constraints of the continuous input parameters.

Returns:

Type Description
ndarray

Numpy array with lower and upper bound for each continuous input dimension.

Examples:

>>> domain = Domain()
>>> domain.input_space = {
...     'param1': ContinuousParameter(lower_bound=0, upper_bound=1),
...     'param2': ContinuousParameter(lower_bound=-1, upper_bound=1),
...     'param3': ContinuousParameter(lower_bound=0, upper_bound=10)
... }
>>> bounds = domain.get_bounds()
>>> bounds
array([[ 0.,  1.],
    [-1.,  1.],
    [ 0., 10.]])
Source code in src/f3dasm/_src/design/domain.py
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
def get_bounds(self) -> np.ndarray:
    """Return the boundary constraints of the continuous input
    parameters.

    Returns
    -------
    np.ndarray
        Numpy array with lower and upper bound for each continuous
        input dimension.

    Examples
    -------
    >>> domain = Domain()
    >>> domain.input_space = {
    ...     'param1': ContinuousParameter(lower_bound=0, upper_bound=1),
    ...     'param2': ContinuousParameter(lower_bound=-1, upper_bound=1),
    ...     'param3': ContinuousParameter(lower_bound=0, upper_bound=10)
    ... }
    >>> bounds = domain.get_bounds()
    >>> bounds
    array([[ 0.,  1.],
        [-1.,  1.],
        [ 0., 10.]])
    """
    return np.array(
        [
            [parameter.lower_bound, parameter.upper_bound]
            for _, parameter in self.input_space.items()
        ]
    )
store(filename: Path | str) -> None ¤

Store the Domain object and its parameters as a JSON file.

Parameters:

Name Type Description Default
filename Path or str

Path of the JSON file to store the Domain object.

required

Examples:

>>> domain.store('domain.json')
Source code in src/f3dasm/_src/design/domain.py
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
def store(self, filename: Path | str) -> None:
    """
    Store the Domain object and its parameters as a JSON file.

    Parameters
    ----------
    filename : Path or str
        Path of the JSON file to store the Domain object.

    Examples
    --------
    >>> domain.store('domain.json')
    """
    domain_dict = {
        "input_space": {
            k: v.to_dict() for k, v in self.input_space.items()
        },
        "output_space": {
            k: v.to_dict() for k, v in self.output_space.items()
        },
    }
    with open(Path(filename).with_suffix(".json"), "w") as f:
        json.dump(domain_dict, f, indent=4)

Built-in samplers¤

f3dasm.create_sampler(sampler: str | DictConfig, **parameters) -> Block ¤

Create a sampler block from one of the built-in samplers.

Parameters:

Name Type Description Default
sampler str | DictConfig

Name of the built-in sampler. Accepted values (issue #289):

  • "random_sampler" (preferred) or "random" (deprecated): uniform random sampling. Accepted parameters: seed.
  • "latin_sampler" (preferred) or "latin" (deprecated): Latin-Hypercube sampling. Accepted parameters: seed.
  • "sobol_sampler" (preferred) or "sobol" (deprecated): Sobol low-discrepancy sequence sampling. Accepted parameters: seed.
  • "grid_sampler" (preferred) or "grid" (deprecated): full cross-product grid. Accepted parameters: stepsize_continuous_parameters.

Can also be a Hydra DictConfig that instantiates a sampler block directly.

required
**parameters

Additional keyword arguments passed when initializing the sampler. Only the keywords documented per-backend above are accepted; any other keyword raises a TypeError so typos and stale options do not silently get ignored.

required

Returns:

Type Description
Block

Block object of the sampler

Raises:

Type Description
KeyError

If the built-in sampler name is not recognized.

TypeError

If sampler is not a str or DictConfig, or if parameters contains a keyword the chosen backend does not accept.

Source code in src/f3dasm/_src/samplers.py
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
def create_sampler(sampler: str | DictConfig, **parameters) -> Block:
    """
    Create a sampler block from one of the built-in samplers.

    Parameters
    ----------
    sampler : str | DictConfig
        Name of the built-in sampler. Accepted values (issue #289):

        - ``"random_sampler"`` (preferred) or ``"random"`` (deprecated):
          uniform random sampling. Accepted ``parameters``: ``seed``.
        - ``"latin_sampler"`` (preferred) or ``"latin"`` (deprecated):
          Latin-Hypercube sampling. Accepted ``parameters``: ``seed``.
        - ``"sobol_sampler"`` (preferred) or ``"sobol"`` (deprecated):
          Sobol low-discrepancy sequence sampling. Accepted
          ``parameters``: ``seed``.
        - ``"grid_sampler"`` (preferred) or ``"grid"`` (deprecated): full
          cross-product grid. Accepted ``parameters``:
          ``stepsize_continuous_parameters``.

        Can also be a Hydra ``DictConfig`` that instantiates a sampler
        block directly.
    **parameters
        Additional keyword arguments passed when initializing the sampler.
        Only the keywords documented per-backend above are accepted; any
        other keyword raises a ``TypeError`` so typos and stale options
        do not silently get ignored.

    Returns
    -------
    Block
        Block object of the sampler

    Raises
    ------
    KeyError
        If the built-in sampler name is not recognized.
    TypeError
        If ``sampler`` is not a ``str`` or ``DictConfig``, or if
        ``parameters`` contains a keyword the chosen backend does not
        accept.
    """
    if isinstance(sampler, str):
        filtered_name = (
            sampler.lower().replace(" ", "").replace("-", "").replace("_", "")
        )

        if filtered_name in SAMPLER_MAPPING:
            # Old, short keys (issue #289): emit a DeprecationWarning so
            # users can move to the explicit `<name>_sampler` form.
            if not filtered_name.endswith("sampler"):
                _warn_deprecated_sampler_name(sampler)
            _validate_sampler_parameters(filtered_name, parameters)
            return SAMPLER_MAPPING[filtered_name](**parameters)

        else:
            raise KeyError(f"Unknown built-in sampler name: {sampler}")

    elif isinstance(sampler, DictConfig):
        return instantiate(sampler)

    else:
        raise TypeError(f"Unknown sampler type given: {type(sampler)}")

f3dasm.design.grid(stepsize_continuous_parameters: Optional[dict[str, float] | float] = None, **kwargs) -> Block ¤

Create a Grid sampler.

Parameters:

Name Type Description Default
stepsize_continuous_parameters dict[str, float] or float

Step size for continuous parameters. If a single float, the same step size is used for all continuous parameters. If a dict, maps parameter names to individual step sizes.

None
**kwargs dict

Additional parameters for the sampler.

required

Returns:

Type Description
Block

A Block instance of a grid sampler.

Source code in src/f3dasm/_src/samplers.py
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
def grid(
    stepsize_continuous_parameters: Optional[dict[str, float] | float] = None,
    **kwargs,
) -> Block:
    """
    Create a Grid sampler.

    Parameters
    ----------
    stepsize_continuous_parameters : dict[str, float] or float, optional
        Step size for continuous parameters. If a single float, the same
        step size is used for all continuous parameters. If a dict, maps
        parameter names to individual step sizes.
    **kwargs : dict
        Additional parameters for the sampler.

    Returns
    -------
    Block
        A Block instance of a grid sampler.
    """
    return Grid(
        stepsize_continuous_parameters=stepsize_continuous_parameters, **kwargs
    )

f3dasm.design.random(seed: Optional[int] = None, **kwargs) -> Block ¤

Create a RandomUniform sampler.

Parameters:

Name Type Description Default
seed Optional[int]

The random seed, by default None

None
**kwargs dict

Additional parameters for the sampler.

required

Returns:

Type Description
Block

An Block instance of a random uniform sampler.

Source code in src/f3dasm/_src/samplers.py
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
def random(seed: Optional[int] = None, **kwargs) -> Block:
    """
    Create a RandomUniform sampler.

    Parameters
    ----------
    seed : Optional[int], optional
        The random seed, by default None
    **kwargs : dict
        Additional parameters for the sampler.

    Returns
    -------
    Block
        An Block instance of a random uniform sampler.
    """
    return RandomUniform(seed=seed, **kwargs)

f3dasm.design.latin(seed: Optional[int] = None, **kwargs) -> Block ¤

Create a Latin Hypercube sampler.

Parameters:

Name Type Description Default
seed Optional[int]

The random seed, by default None

None
**kwargs dict

Additional parameters for the sampler.

required

Returns:

Type Description
Block

An Block instance of a latin hypercube sampler.

Source code in src/f3dasm/_src/samplers.py
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
def latin(seed: Optional[int] = None, **kwargs) -> Block:
    """
    Create a Latin Hypercube sampler.

    Parameters
    ----------
    seed : Optional[int], optional
        The random seed, by default None
    **kwargs : dict
        Additional parameters for the sampler.

    Returns
    -------
    Block
        An Block instance of a latin hypercube sampler.
    """
    return Latin(seed=seed, **kwargs)

f3dasm.design.sobol(seed: Optional[int] = None, **kwargs) -> Block ¤

Create a Sobol sampler.

Parameters:

Name Type Description Default
seed Optional[int]

The random seed, by default None

None
**kwargs dict

Additional parameters for the sampler.

required

Returns:

Type Description
Block

A Block instance of a sobol sequence sampler.

Source code in src/f3dasm/_src/samplers.py
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
def sobol(seed: Optional[int] = None, **kwargs) -> Block:
    """
    Create a Sobol sampler.

    Parameters
    ----------
    seed : Optional[int], optional
        The random seed, by default None
    **kwargs : dict
        Additional parameters for the sampler.

    Returns
    -------
    Block
        A Block instance of a sobol sequence sampler.
    """
    return Sobol(seed=seed, **kwargs)