simoptlib 1.2.0.dev0__py3-none-any.whl → 1.2.0.post2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,163 @@
1
+ """Core module for creating data farming designs."""
2
+
3
+ from abc import ABC, abstractmethod
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+
8
+ class Scaler:
9
+ """Class to scale values from one range to another."""
10
+
11
+ @property
12
+ def original_min(self) -> float:
13
+ """The minimum value of the original range."""
14
+ return self._original_min
15
+
16
+ @original_min.setter
17
+ def original_min(self, value: float) -> None:
18
+ self._original_min = value
19
+ self._cached_scale = False
20
+
21
+ @property
22
+ def original_max(self) -> float:
23
+ """The maximum value of the original range."""
24
+ return self._original_max
25
+
26
+ @original_max.setter
27
+ def original_max(self, value: float) -> None:
28
+ self._original_max = value
29
+ self._cached_scale = False
30
+
31
+ @property
32
+ def scaled_min(self) -> float:
33
+ """The minimum value of the scaled range."""
34
+ return self._scaled_min
35
+
36
+ @scaled_min.setter
37
+ def scaled_min(self, value: float) -> None:
38
+ self._scaled_min = value
39
+ self._cached_scale = False
40
+
41
+ @property
42
+ def scaled_max(self) -> float:
43
+ """The maximum value of the scaled range."""
44
+ return self._scaled_max
45
+
46
+ @scaled_max.setter
47
+ def scaled_max(self, value: float) -> None:
48
+ self._scaled_max = value
49
+ self._cached_scale = False
50
+
51
+ @property
52
+ def precision(self) -> int:
53
+ """The number of decimal places to round to."""
54
+ return self._precision
55
+
56
+ @property
57
+ def scale_factor(self) -> int:
58
+ """The factor by which to scale values."""
59
+ return self._scale_factor
60
+
61
+ @precision.setter
62
+ def precision(self, value: int) -> None:
63
+ self._precision = value
64
+ self._scale_factor = 10**value
65
+ self._cached_scale = False
66
+
67
+ @property
68
+ def scale(self) -> float:
69
+ """The scale factor between the original and scaled ranges."""
70
+ if not self._cached_scale:
71
+ original_range = self.original_max - self.original_min
72
+ scaled_range = self.scaled_max - self.scaled_min
73
+ self._scale = (scaled_range / original_range) if original_range else 0
74
+ self._offset = self.scaled_max - (self.original_min * self._scale)
75
+ self._cached_scale = True
76
+ return self._scale
77
+
78
+ def __init__(
79
+ self,
80
+ original_min: float,
81
+ original_max: float,
82
+ scaled_min: float,
83
+ scaled_max: float,
84
+ precision: int = 0,
85
+ ) -> None:
86
+ """Initialize the Scaler.
87
+
88
+ Args:
89
+ original_min (float): The minimum value of the original range.
90
+ original_max (float): The maximum value of the original range.
91
+ scaled_min (float): The minimum value of the scaled range.
92
+ scaled_max (float): The maximum value of the scaled range.
93
+ precision (int, optional): The number of decimal places to round to.
94
+ Defaults to 0.
95
+ """
96
+ self._original_min = original_min
97
+ self._original_max = original_max
98
+ self._scaled_min = scaled_min
99
+ self._scaled_max = scaled_max
100
+ self.precision = precision
101
+ self._cached_scale = False
102
+
103
+ def scale_value(self, value: float) -> int | float:
104
+ """Scale a value from the original range to the scaled range.
105
+
106
+ Returns an int if the value has no decimal component after rounding,
107
+ otherwise returns a float.
108
+ """
109
+ if not (self.original_min <= value <= self.original_max):
110
+ raise ValueError(
111
+ f"Value {value} is out of bounds "
112
+ f"({self.original_min}, {self.original_max})"
113
+ )
114
+ new_value = self.scaled_min + (self.scale * (value - self.original_min))
115
+ rounded_val = round(new_value, self.precision)
116
+ # TODO: simplify int return logic
117
+ return int(rounded_val) if rounded_val == int(rounded_val) else rounded_val
118
+
119
+
120
+ class DesignType(ABC):
121
+ """Abstract base class for design types."""
122
+
123
+ @abstractmethod
124
+ def __init__(
125
+ self,
126
+ designs: list[tuple[float, float, int]] | None = None,
127
+ *args: Any, # noqa: ANN401
128
+ **kwargs: Any, # noqa: ANN401
129
+ ) -> None:
130
+ """Initialize the DesignType class."""
131
+ pass
132
+
133
+ @abstractmethod
134
+ def generate_design(self) -> list[list[float]]:
135
+ """Generate a design as a 2D list.
136
+
137
+ Returns:
138
+ list[list[float]]: A 2D list containing the scaled design points.
139
+ """
140
+ pass
141
+
142
+ def save_design(
143
+ self,
144
+ output_file: Path,
145
+ ) -> None:
146
+ """Save the design to a file.
147
+
148
+ Args:
149
+ output_file (Path): The path to the output file.
150
+ """
151
+ # Generate the design
152
+ design = self.generate_design()
153
+
154
+ # Ensure the directory exists
155
+ output_file.parent.mkdir(parents=True, exist_ok=True)
156
+
157
+ # Remove the output file if it exists
158
+ if output_file.exists():
159
+ output_file.unlink()
160
+
161
+ with output_file.open("w") as f:
162
+ for row in design:
163
+ f.write("\t".join(map(str, row)) + "\n")
@@ -0,0 +1,190 @@
1
+ """Module for generating Nearly Orthogonal Latin Hypercube Samples (NOLHS)."""
2
+
3
+ import bisect
4
+ import re
5
+ from pathlib import Path
6
+
7
+ import numpy as np
8
+
9
+ from simopt.data_farming.data_farming_core import DesignType, Scaler
10
+ from simopt.utils import classproperty
11
+
12
+
13
+ class NOLHS(DesignType):
14
+ """Class to generate Nearly Orthogonal Latin Hypercube Samples (NOLHS)."""
15
+
16
+ # Store the design table as a class property so it's cached across instances
17
+ _design_table: dict[int, np.ndarray] | None = None
18
+
19
+ def __init__(
20
+ self,
21
+ designs: list[tuple[float, float, int]] | Path,
22
+ num_stacks: int = 1,
23
+ ) -> None:
24
+ """Initialize the NOLHS class.
25
+
26
+ Args:
27
+ designs (list[tuple[float, float, int]] | Path): A list of tuples where each
28
+ tuple contains (min, max, precision) for a design variable, or a Path to
29
+ a file containing the design config.
30
+ num_stacks (int, optional): The number of stacks to generate. Defaults to 1.
31
+ """
32
+ if isinstance(designs, Path):
33
+ self._import_design_config(designs)
34
+ else:
35
+ self._set_designs(designs)
36
+
37
+ self.num_stacks = num_stacks
38
+
39
+ # Store the design table as a class property so it's cached across instances
40
+ # Original design table found here:
41
+ # https://gitlab.nps.edu/pjsanche/datafarmingrubyscripts/-/blob/v1.4.1/lib/datafarming/nolh_designs.rb
42
+ @classproperty
43
+ def design_table(cls) -> dict[int, np.ndarray]:
44
+ """The NOLHS design table.
45
+
46
+ Returns:
47
+ dict[int, np.ndarray]: A dictionary mapping the number of variables to
48
+ the corresponding NOLHS design matrix.
49
+ """
50
+ if cls._design_table is None:
51
+ current_dir = Path(__file__).parent
52
+ loaded_data = np.load(current_dir / "nolhs_design_table.npz")
53
+ cls._design_table = {int(k): v for k, v in loaded_data.items()}
54
+ return cls._design_table
55
+
56
+ @property
57
+ def num_stacks(self) -> int:
58
+ """Number of stacks in the design."""
59
+ return self._num_stacks
60
+
61
+ @num_stacks.setter
62
+ def num_stacks(self, value: int) -> None:
63
+ if value <= 0:
64
+ raise ValueError("Number of stacks must be positive.")
65
+ if self._nolhs_size and value > self._nolhs_size:
66
+ plural = "s" if self._design_size > 1 else ""
67
+ raise ValueError(
68
+ "Number of stacks cannot exceed the NOLHS size "
69
+ f"({self._nolhs_size} for {self._design_size} design variable{plural})."
70
+ )
71
+ self._num_stacks = value
72
+
73
+ def _set_designs(
74
+ self,
75
+ designs: list[tuple[float, float, int]],
76
+ ) -> None:
77
+ """Set the design configurations.
78
+
79
+ Args:
80
+ designs (list[tuple[float, float, int]]): A list of tuples where each tuple
81
+ contains (min, max, precision) for a design variable.
82
+ """
83
+ self._designs = designs
84
+ self._design_size = len(self._designs)
85
+ self._nolhs_size = self._determine_table_key(self._design_size)
86
+ self._scalers = [
87
+ Scaler(
88
+ original_min=1,
89
+ original_max=self._nolhs_size,
90
+ scaled_min=min_val,
91
+ scaled_max=max_val,
92
+ precision=num_digits,
93
+ )
94
+ for min_val, max_val, num_digits in self._designs
95
+ ]
96
+
97
+ def generate_design(self) -> list[list[float]]:
98
+ """Generate the scaled NOLHS design as a 2D list.
99
+
100
+ Returns:
101
+ list[list[float]]: A 2D list containing the scaled design points.
102
+ """
103
+ # If there are no design variables, return an empty list
104
+ if not self._nolhs_size or self._design_size == 0:
105
+ return []
106
+ # Copy the design to avoid modifying the original
107
+ design: np.ndarray = self.design_table[self._nolhs_size].copy()
108
+ mid_range = self._nolhs_size // 2
109
+
110
+ all_scaled_designs = []
111
+
112
+ for stack_idx in range(self._num_stacks):
113
+ for i, dp in enumerate(design):
114
+ scaled_dp = [
115
+ self._scalers[k].scale_value(x)
116
+ for k, x in enumerate(dp[: self._design_size])
117
+ ]
118
+
119
+ # TODO: revisit why this is needed
120
+ if not (stack_idx > 0 and i == mid_range and self._nolhs_size < 512):
121
+ all_scaled_designs.append(scaled_dp)
122
+
123
+ # Rotate the data point for the next iteration
124
+ design[i] = np.roll(dp, -1)
125
+
126
+ return all_scaled_designs
127
+
128
+ def _import_design_config(
129
+ self,
130
+ file_path: Path,
131
+ ) -> None:
132
+ """Import the design config from a file.
133
+
134
+ Args:
135
+ file_path (Path): The path to the file containing the design config.
136
+ """
137
+ # Read the design config from the specified file.
138
+ design_config = []
139
+ with file_path.open("r") as f:
140
+ for line in f:
141
+ line_data = re.split(r"\s*[,;:]\s*|\s+", line.strip())
142
+ # Skip empty lines
143
+ if len(line_data) == 0:
144
+ continue
145
+ # Each line must contain exactly three values
146
+ if len(line_data) != 3:
147
+ raise ValueError(
148
+ f"Error importing design config at Path: {file_path}. "
149
+ f"Each line must contain exactly three values: {line.strip()}"
150
+ )
151
+ # Add the design to the config
152
+ min_val, max_val, num_digits = line_data
153
+ design = (float(min_val), float(max_val), int(num_digits))
154
+ design_config.append(design)
155
+ # Update the class attributes based on the imported design config
156
+ self._set_designs(design_config)
157
+
158
+ def _determine_table_key(self, num_vars: int) -> int:
159
+ """Determine the key to use for the design table based on number of variables.
160
+
161
+ Args:
162
+ num_vars (int): The number of variables in the optimization problem.
163
+
164
+ Returns:
165
+ int: The key to use for the design table.
166
+
167
+ Raises:
168
+ ValueError: If num_vars is greater than 100.
169
+ """
170
+ if num_vars > 100:
171
+ raise ValueError("NOLHS only supports up to 100 variables at this time.")
172
+
173
+ # Keys are the minimum of each range, values are the return keys
174
+ ranges = {
175
+ 0: 1, # Special case for 0 variables
176
+ 1: 17,
177
+ 8: 33,
178
+ 12: 65,
179
+ 17: 129,
180
+ 23: 257,
181
+ 30: 512,
182
+ }
183
+
184
+ # Get a sorted list of the keys (the range minimums)
185
+ min_vars = sorted(ranges.keys())
186
+
187
+ # Use bisect to find the correct range
188
+ # It finds the insertion point for num_vars in the sorted list
189
+ idx = bisect.bisect_right(min_vars, num_vars) - 1
190
+ return ranges[min_vars[idx]]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: simoptlib
3
- Version: 1.2.0.dev0
3
+ Version: 1.2.0.post2
4
4
  Summary: A testbed for simulation-optimization experiments.
5
5
  Author-email: David Eckman <eckman@tamu.edu>, Shane Henderson <sgh9@cornell.edu>, Sara Shashaani <sshasha2@ncsu.edu>, William Grochocinski <wagrocho@ncsu.edu>
6
6
  License: MIT License
@@ -50,7 +50,7 @@ Requires-Dist: sphinx-autoapi>=3.6.1; extra == "docs"
50
50
  Requires-Dist: sphinx-rtd-theme>=3.0.2; extra == "docs"
51
51
  Dynamic: license-file
52
52
 
53
- ![SimOpt Logo](.github/resources/logo_full_magnifying_glass.png)
53
+ ![SimOpt Logo](https://raw.githubusercontent.com/simopt-admin/simopt/master/.github/resources/logo_full_magnifying_glass.png)
54
54
 
55
55
  ## About the Project
56
56
  SimOpt is a testbed of simulation-optimization problems and solvers. Its purpose is to encourage the development and constructive comparison of simulation-optimization (SO) solvers (algorithms). We are particularly interested in the finite-time performance of solvers, rather than the asymptotic results that one often finds in related literature.
@@ -16,6 +16,9 @@ simopt/problem_types.py,sha256=F4gnbMtzHRwMsTAfgNX7unEnOTKi0D1-zy-WyVuUq8E,1275
16
16
  simopt/solver.py,sha256=W3aw6_cM4OGuO46rITN1yEWAWw7N4sZF6fl9m189T_E,8235
17
17
  simopt/utils.py,sha256=KX0skAcSF3x-XBw6LxPDT04JvxzJZwRRuFfdmTBNxsE,8364
18
18
  simopt/utils.pyi,sha256=4x7SmIAFeHhd4OYk0E-Z-VGL4Bv_OlvqdYB24FFBTjM,532
19
+ simopt/data_farming/data_farming_core.py,sha256=6M807RODOKicWTmc0-kR6mMxP75MuxdOIvQ3OULFoJk,5100
20
+ simopt/data_farming/nolhs.py,sha256=vDONgtJmtRvxHJiI0RFsV4YKSEHRjROtXEezA-qArdE,6913
21
+ simopt/data_farming/nolhs_design_table.npz,sha256=ILcJvpFCSZr90lyrx6Hluyo1d6fH5BmgIlzyqiLxgZE,88625
19
22
  simopt/gui/data_farming_window.py,sha256=YuKo3DNRoVLBnkIllD5mqYq6Ogec3r0qCV0_WEsfjq8,53046
20
23
  simopt/gui/df_object.py,sha256=bnLOBl_vzGEtkNDzpCwzqmsBHx4e8Dn7PaIW7IFa1_s,22633
21
24
  simopt/gui/main_menu.py,sha256=ejohYezmQq4nVsl8ytWDz0JBrRla98j7s3RrZSyWqGo,3891
@@ -51,8 +54,8 @@ simopt/solvers/randomsearch.py,sha256=B_fa4lcg0reC6x8aVwS_5ZwLzeoX1V_TK9bNdXhjat
51
54
  simopt/solvers/spsa.py,sha256=vV5Z7Ez5hpQQ3QJBJcRmI9R-7M5aeHEVTA4sUVQzB4s,12011
52
55
  simopt/solvers/strong.py,sha256=isuRDqtYTM9u7XkEKR5tyECvr_lrzTjzN2H9bTsenBg,20897
53
56
  simopt/solvers/utils.py,sha256=SvPrGCGDF-7ll7YLpEKY1qr5LU89q8L51CyPru33EXI,10272
54
- simoptlib-1.2.0.dev0.dist-info/licenses/LICENSE,sha256=3WAn8U4vCLx6JSFLUuPlykqEb0oQOH9OY2uhRXLo4sE,1090
55
- simoptlib-1.2.0.dev0.dist-info/METADATA,sha256=bV9qHWM-NT1Ke62i0S_BhzPj-FAyqFGzsmEwRfVuFVY,25202
56
- simoptlib-1.2.0.dev0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
57
- simoptlib-1.2.0.dev0.dist-info/top_level.txt,sha256=1y-9SVlYOHUC1eF7Afr_7NbhF-SxKo7jDFKqzvUav0w,7
58
- simoptlib-1.2.0.dev0.dist-info/RECORD,,
57
+ simoptlib-1.2.0.post2.dist-info/licenses/LICENSE,sha256=3WAn8U4vCLx6JSFLUuPlykqEb0oQOH9OY2uhRXLo4sE,1090
58
+ simoptlib-1.2.0.post2.dist-info/METADATA,sha256=A4VueQVrgPiuZtmlZHL6CKI9GWjqxIGLWiTXA2OFak4,25264
59
+ simoptlib-1.2.0.post2.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
60
+ simoptlib-1.2.0.post2.dist-info/top_level.txt,sha256=1y-9SVlYOHUC1eF7Afr_7NbhF-SxKo7jDFKqzvUav0w,7
61
+ simoptlib-1.2.0.post2.dist-info/RECORD,,