simoptlib 1.2.1__tar.gz → 1.2.2.post0__tar.gz

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.
Files changed (85) hide show
  1. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/PKG-INFO +3 -1
  2. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/pyproject.toml +7 -1
  3. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/GUI.py +1 -0
  4. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/experiment_base.py +16 -6
  5. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/gui/main_menu.py +1 -1
  6. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/gui/new_experiment_window.py +8 -1
  7. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/input_models.py +3 -3
  8. simoptlib-1.2.2.post0/simopt/models/_ext.py +56 -0
  9. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/models/amusementpark.py +6 -1
  10. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/models/chessmm.py +2 -2
  11. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/models/cntnv.py +2 -2
  12. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/models/dualsourcing.py +2 -2
  13. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/models/dynamnews.py +2 -2
  14. simoptlib-1.2.2.post0/simopt/models/ermexample.py +203 -0
  15. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/models/facilitysizing.py +2 -2
  16. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/models/hotel.py +1 -1
  17. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/models/ironore.py +2 -2
  18. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/models/network.py +2 -2
  19. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/models/rmitd.py +1 -1
  20. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/models/tableallocation.py +7 -4
  21. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/solvers/fcsa.py +7 -3
  22. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simoptlib.egg-info/PKG-INFO +3 -1
  23. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simoptlib.egg-info/SOURCES.txt +2 -0
  24. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simoptlib.egg-info/requires.txt +3 -0
  25. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/LICENSE +0 -0
  26. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/README.md +0 -0
  27. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/setup.cfg +0 -0
  28. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/__init__.py +0 -0
  29. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/__main__.py +0 -0
  30. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/base.py +0 -0
  31. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/bootstrap.py +0 -0
  32. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/curve.py +0 -0
  33. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/curve_utils.py +0 -0
  34. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/data_farming/data_farming_core.py +0 -0
  35. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/data_farming/nolhs.py +0 -0
  36. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/data_farming/nolhs_design_table.npz +0 -0
  37. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/data_farming_base.py +0 -0
  38. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/directory.py +0 -0
  39. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/experiment/__init__.py +0 -0
  40. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/experiment/multiple.py +0 -0
  41. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/experiment/post_normalize.py +0 -0
  42. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/experiment/single.py +0 -0
  43. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/experimental.py +0 -0
  44. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/feasibility.py +0 -0
  45. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/gui/data_farming_window.py +0 -0
  46. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/gui/df_object.py +0 -0
  47. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/gui/plot_window.py +0 -0
  48. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/gui/toplevel_custom.py +0 -0
  49. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/model.py +0 -0
  50. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/models/__init__.py +0 -0
  51. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/models/contam.py +0 -0
  52. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/models/example.py +0 -0
  53. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/models/fixedsan.py +0 -0
  54. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/models/mm1queue.py +0 -0
  55. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/models/paramesti.py +0 -0
  56. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/models/san.py +0 -0
  57. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/models/sscont.py +0 -0
  58. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/plot_type.py +0 -0
  59. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/plots/__init__.py +0 -0
  60. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/plots/area_scatterplot.py +0 -0
  61. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/plots/feasibility_progress.py +0 -0
  62. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/plots/progress_curve.py +0 -0
  63. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/plots/solvability_cdf.py +0 -0
  64. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/plots/solvability_profile.py +0 -0
  65. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/plots/terminal_feasibility.py +0 -0
  66. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/plots/terminal_progress.py +0 -0
  67. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/plots/terminal_scatterplot.py +0 -0
  68. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/plots/utils.py +0 -0
  69. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/problem.py +0 -0
  70. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/problem_types.py +0 -0
  71. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/solver.py +0 -0
  72. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/solvers/__init__.py +0 -0
  73. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/solvers/adam.py +0 -0
  74. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/solvers/aloe.py +0 -0
  75. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/solvers/astrodf.py +0 -0
  76. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/solvers/neldmd.py +0 -0
  77. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/solvers/randomsearch.py +0 -0
  78. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/solvers/spsa.py +0 -0
  79. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/solvers/strong.py +0 -0
  80. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/solvers/utils.py +0 -0
  81. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/utils.py +0 -0
  82. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simopt/utils.pyi +0 -0
  83. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simoptlib.egg-info/dependency_links.txt +0 -0
  84. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/simoptlib.egg-info/top_level.txt +0 -0
  85. {simoptlib-1.2.1 → simoptlib-1.2.2.post0}/test/test_experiments.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: simoptlib
3
- Version: 1.2.1
3
+ Version: 1.2.2.post0
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 <williamgrochocinski@gmail.com>
6
6
  License: MIT License
@@ -56,6 +56,8 @@ Requires-Dist: sphinx-autoapi>=3.6.1; extra == "docs"
56
56
  Requires-Dist: sphinx-rtd-theme>=3.0.2; extra == "docs"
57
57
  Provides-Extra: notebooks
58
58
  Requires-Dist: ipykernel>=7.1.0; extra == "notebooks"
59
+ Provides-Extra: ext
60
+ Requires-Dist: simopt-extensions; extra == "ext"
59
61
  Dynamic: license-file
60
62
 
61
63
  ![SimOpt Logo](https://raw.githubusercontent.com/simopt-admin/simopt/master/.github/resources/logo_full_magnifying_glass.png)
@@ -11,9 +11,12 @@ exclude = ["build*"]
11
11
  [tool.setuptools.package-data]
12
12
  "simopt.data_farming" = ["*.npz"]
13
13
 
14
+ [tool.uv.sources]
15
+ simopt-extensions = { git = "https://github.com/cenwangumass/simopt-extensions", rev = "b40a9c8" }
16
+
14
17
  [project]
15
18
  name = "simoptlib"
16
- version = "1.2.1"
19
+ version = "1.2.2.post0"
17
20
  authors = [
18
21
  { name = "David Eckman", email = "eckman@tamu.edu" },
19
22
  { name = "Shane Henderson", email = "sgh9@cornell.edu" },
@@ -53,6 +56,9 @@ dev = [
53
56
  ]
54
57
  docs = ["sphinx>=8.2.3", "sphinx-autoapi>=3.6.1", "sphinx-rtd-theme>=3.0.2"]
55
58
  notebooks = ["ipykernel>=7.1.0"]
59
+ ext = [
60
+ "simopt-extensions",
61
+ ]
56
62
 
57
63
  [project.urls]
58
64
  "Homepage" = "https://github.com/simopt-admin/simopt"
@@ -24,6 +24,7 @@ def main() -> None:
24
24
  root = GUIMaster()
25
25
  root.title("SimOpt Library Graphical User Interface")
26
26
  root.pack_propagate(False)
27
+ root.tk.call("tk", "scaling", 1.0)
27
28
 
28
29
  # Parse command line
29
30
  log_level = logging.INFO
@@ -202,12 +202,22 @@ def create_design_list_from_table(design_table: DataFrame) -> list[dict[str, Any
202
202
  # Creates dictonary of table to convert values to proper datatypes.
203
203
  dp_dict = design_table.to_dict(orient="list")
204
204
 
205
- # NOTE: the str cast for the factor name shouldn't be necessary, but it tells the
206
- # typing system that the dict keys are definitely strings and not just hashable.
207
- return [
208
- {str(factor): literal_eval(str(dp_dict[factor][dp])) for factor in dp_dict}
209
- for dp in range(len(design_table))
210
- ]
205
+ # TODO: this is a hack to get the data type of the factors back.
206
+ design_list = []
207
+ for dp in range(len(design_table)):
208
+ config = {}
209
+ for factor in dp_dict:
210
+ key = str(factor)
211
+ raw_value = str(dp_dict[factor][dp])
212
+ try:
213
+ value = literal_eval(raw_value)
214
+ except ValueError:
215
+ # This exception handles the case where the value is a string.
216
+ value = raw_value
217
+ config[key] = value
218
+ design_list.append(config)
219
+
220
+ return design_list
211
221
 
212
222
 
213
223
  def create_design(
@@ -9,7 +9,7 @@ from simopt.gui.data_farming_window import DataFarmingWindow
9
9
  from simopt.gui.new_experiment_window import NewExperimentWindow
10
10
  from simopt.gui.toplevel_custom import Toplevel
11
11
 
12
- FONT_SCALE: Final[float] = 1.5
12
+ FONT_SCALE: Final[float] = 1
13
13
 
14
14
 
15
15
  class MainMenuWindow(Toplevel):
@@ -1647,6 +1647,13 @@ class NewExperimentWindow(Toplevel):
1647
1647
  for factor in model_specifications:
1648
1648
  specifications[factor] = model_specifications[factor]
1649
1649
  # Convert the specifications to a dictionary of DFFactor objects
1650
+
1651
+ # TODO: This is a hack to remove the step_type and search_direction factors
1652
+ # because str type is not currently supported in the GUI.
1653
+ if isinstance(base_object, Solver) and base_object.class_name_abbr == "FCSA":
1654
+ del specifications["step_type"]
1655
+ del specifications["search_direction"]
1656
+
1650
1657
  self.factor_dict = spec_dict_to_df_dict(specifications)
1651
1658
 
1652
1659
  # Add all the column headers
@@ -2355,7 +2362,7 @@ class NewExperimentWindow(Toplevel):
2355
2362
  self.__update_experiment_label(experiment_name, "Logging")
2356
2363
  # Try to log the experiment
2357
2364
  try:
2358
- self.post_normalize(experiment_name)
2365
+ self.log_results(experiment_name)
2359
2366
  # If successful, update the label and button
2360
2367
  self.__update_experiment_label(experiment_name, "Logged")
2361
2368
  self.__update_action_button(experiment_name, "All Steps\nComplete")
@@ -3,9 +3,9 @@
3
3
  import bisect
4
4
  import itertools
5
5
  import math
6
- import random
7
6
  from abc import abstractmethod
8
7
  from collections.abc import Sequence
8
+ from random import Random
9
9
  from typing import ParamSpec, Protocol, TypeVar
10
10
 
11
11
  P = ParamSpec("P")
@@ -15,9 +15,9 @@ R = TypeVar("R", covariant=True)
15
15
  class InputModel(Protocol[P, R]):
16
16
  """Abstract base for input models used by simulations."""
17
17
 
18
- rng: random.Random | None = None
18
+ rng: Random | None = None
19
19
 
20
- def set_rng(self, rng: random.Random) -> None:
20
+ def set_rng(self, rng: Random) -> None:
21
21
  """Attach a Python RNG to the input model.
22
22
 
23
23
  Args:
@@ -0,0 +1,56 @@
1
+ import importlib
2
+ import os
3
+ from collections.abc import Callable
4
+ from types import ModuleType
5
+
6
+ from simopt.model import Model
7
+
8
+
9
+ def find_model_patches(module: ModuleType) -> list[Callable]:
10
+ patches: list[Callable] = []
11
+ for attr in dir(module):
12
+ if not attr.startswith("patch_model"):
13
+ continue
14
+ candidate = getattr(module, attr)
15
+ if callable(candidate):
16
+ patches.append(candidate)
17
+ return patches
18
+
19
+
20
+ def patch(model_class: type[Model], patch_function: Callable) -> None:
21
+ # Ask the extension what class to patch and with what method
22
+ class_name, method = patch_function()
23
+ # Patch the method into the model_class if it matches
24
+ full_name = model_class.__module__ + "." + model_class.__qualname__
25
+ if full_name == class_name:
26
+ model_class.replicate = method
27
+
28
+
29
+ def load_module(module_name: str, model_class: type[Model]) -> None:
30
+ # Import the specified library
31
+ try:
32
+ module = importlib.import_module(module_name)
33
+ except ImportError as e:
34
+ raise ImportError(f"SimOpt failed to load extension '{module_name}'") from e
35
+
36
+ # Find all patch_model* functions in the library
37
+ patches = find_model_patches(module)
38
+ if not patches:
39
+ raise ImportError(f"'{module_name}' does not have any 'patch_model*' functions")
40
+
41
+ # Apply each patch to the model_class
42
+ for p in patches:
43
+ patch(model_class, p)
44
+
45
+
46
+ def patch_model(model_class: type[Model]) -> None:
47
+ env_var = os.environ.get("SIMOPT_EXT")
48
+ if not env_var:
49
+ return
50
+
51
+ # Assume that the user has specified a comma-separated list of libraries to import.
52
+ # For example, SIMOPT_EXT="simopt_extension_a,simopt_extension_b"
53
+ for part in env_var.split(","):
54
+ module_name = part.strip()
55
+ if module_name:
56
+ load_module(module_name, model_class)
@@ -17,6 +17,7 @@ from simopt.base import (
17
17
  VariableType,
18
18
  )
19
19
  from simopt.input_models import Exp, Gamma, WeightedChoice
20
+ from simopt.models._ext import patch_model
20
21
 
21
22
  INF = float("inf")
22
23
 
@@ -478,9 +479,10 @@ class AmusementPark(Model):
478
479
  cumulative_util = [cumulative_util[i] / time_open for i in attraction_range]
479
480
 
480
481
  # Calculate responses from simulation data.
482
+ percent_departed = total_departed / total_visitors if total_visitors else 0
481
483
  responses = {
482
484
  "total_departed": total_departed,
483
- "percent_departed": total_departed / total_visitors,
485
+ "percent_departed": percent_departed,
484
486
  "average_number_in_system": time_average / time_open,
485
487
  "attraction_utilization_percentages": cumulative_util,
486
488
  }
@@ -543,3 +545,6 @@ class AmusementParkMinDepart(Problem):
543
545
  n_elements=num_elements, summation=summation, with_zero=False
544
546
  )
545
547
  return tuple(vector)
548
+
549
+
550
+ patch_model(AmusementPark)
@@ -2,7 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- import random
5
+ from random import Random
6
6
  from typing import Annotated, ClassVar, Final
7
7
 
8
8
  import numpy as np
@@ -111,7 +111,7 @@ class ChessAvgDifferenceConfig(BaseModel):
111
111
  class EloInputModel(InputModel):
112
112
  """Input model for player Elo ratings."""
113
113
 
114
- rng: random.Random | None = None
114
+ rng: Random | None = None
115
115
 
116
116
  def random(
117
117
  self, mean: float, std: float, min_rating: float, max_rating: float
@@ -2,7 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- import random
5
+ from random import Random
6
6
  from typing import Annotated, ClassVar, Self
7
7
 
8
8
  import numpy as np
@@ -128,7 +128,7 @@ class CntNVMaxProfitConfig(BaseModel):
128
128
  class DemandInputModel(InputModel):
129
129
  """Input model for Burr Type XII demand."""
130
130
 
131
- rng: random.Random | None = None
131
+ rng: Random | None = None
132
132
 
133
133
  def random(self, burr_c: float, burr_k: float) -> float: # noqa: D102
134
134
  # Generate random demand according to Burr Type XII distribution.
@@ -2,7 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- import random
5
+ from random import Random
6
6
  from typing import Annotated, ClassVar, Self
7
7
 
8
8
  import numpy as np
@@ -166,7 +166,7 @@ class DualSourcingMinCostConfig(BaseModel):
166
166
  class DemandInputModel(InputModel):
167
167
  """Input model for daily demand."""
168
168
 
169
- rng: random.Random | None = None
169
+ rng: Random | None = None
170
170
 
171
171
  def random(self, mu: float, sigma: float) -> int: # noqa: D102
172
172
  def round_and_clamp_non_neg(x: float | int) -> int:
@@ -3,7 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import math
6
- import random
6
+ from random import Random
7
7
  from typing import Annotated, ClassVar, Final, Self
8
8
 
9
9
  import numpy as np
@@ -155,7 +155,7 @@ class DynamNewsMaxProfitConfig(BaseModel):
155
155
  class Utility(InputModel):
156
156
  """Input model for customer utility sampling."""
157
157
 
158
- rng: random.Random | None = None
158
+ rng: Random | None = None
159
159
 
160
160
  def _gumbelvariate(self, mu: float, beta: float) -> float:
161
161
  assert self.rng is not None
@@ -0,0 +1,203 @@
1
+ """Example problem of deterministic function with noise.
2
+
3
+ Simulate a synthetic problem with a deterministic objective function
4
+ evaluated with noise.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Annotated, ClassVar
10
+
11
+ import numpy as np
12
+ from pydantic import BaseModel, Field
13
+
14
+ from mrg32k3a.mrg32k3a import MRG32k3a
15
+ from simopt.base import (
16
+ ConstraintType,
17
+ Model,
18
+ Objective,
19
+ Problem,
20
+ RepResult,
21
+ VariableType,
22
+ )
23
+ from simopt.input_models import InputModel
24
+
25
+
26
+ class ERMExampleModelConfig(BaseModel):
27
+ """Configuration model for ERMExample simulation.
28
+
29
+ An empirical risk minimization model for linear regression.
30
+ """
31
+
32
+ beta: Annotated[
33
+ tuple[float, ...],
34
+ Field(
35
+ default=(0.0, 0.0),
36
+ description="(intercept, slope) coefficients",
37
+ ),
38
+ ]
39
+
40
+
41
+ class ERMExampleProblemConfig(BaseModel):
42
+ """Configuration model for ERMExample Problem.
43
+
44
+ Base class to implement simulation-optimization problems.
45
+ """
46
+
47
+ initial_solution: Annotated[
48
+ tuple[float, ...],
49
+ Field(
50
+ default=(0.0, 0.0),
51
+ description="initial solution",
52
+ ),
53
+ ]
54
+ budget: Annotated[
55
+ int,
56
+ Field(
57
+ default=1000,
58
+ description="max # of replications for a solver to take",
59
+ gt=0,
60
+ json_schema_extra={"isDatafarmable": False},
61
+ ),
62
+ ]
63
+
64
+
65
+ class FileInputModel(InputModel):
66
+ def __init__(self, filename):
67
+ self.data = np.load(filename)
68
+
69
+ def set_rng(self, rng: random.Random) -> None:
70
+ self.rng = rng
71
+
72
+ def unset_rng(self) -> None:
73
+ self.rng = None
74
+
75
+ def random(self) -> float:
76
+ n_rows = np.shape(self.data)[0]
77
+ resample_idx = np.random.choice(n_rows, size=1, replace=True)
78
+ resample_x = self.data[resample_idx, 0].item()
79
+ resample_y = self.data[resample_idx, 1].item()
80
+ return resample_x, resample_y
81
+
82
+
83
+ class ERMExampleModel(Model):
84
+ """A model that for the empirical risk of a linear regression model."""
85
+
86
+ class_name_abbr: ClassVar[str] = "ERMEXAMPLE"
87
+ class_name: ClassVar[str] = "Linear Regression ERM"
88
+ config_class: ClassVar[type[BaseModel]] = ERMExampleModelConfig
89
+ n_rngs: ClassVar[int] = 1
90
+ n_responses: ClassVar[int] = 1
91
+
92
+ def __init__(self, fixed_factors: dict | None = None) -> None:
93
+ """Initialize the model.
94
+
95
+ Args:
96
+ fixed_factors (dict | None): fixed factors of the model.
97
+ If None, use default values.
98
+ """
99
+ # Let the base class handle default arguments.
100
+ super().__init__(fixed_factors)
101
+ self.resample_model = FileInputModel("workshop/erm_data.npy")
102
+
103
+ def before_replicate(self, rng_list: list[MRG32k3a]) -> None: # noqa: D102
104
+ self.resample_model.set_rng(rng_list[0])
105
+
106
+ def replicate(self) -> tuple[dict, dict]:
107
+ """Evaluate the squared error loss of a single observation.
108
+
109
+ Returns:
110
+ tuple[dict, dict]: A tuple containing:
111
+ - responses (dict): Performance measures of interest, including:
112
+ - "sq_error_loss": Squared error loss of a single observation.
113
+ - gradients (dict): A dictionary of gradient estimates for
114
+ each response.
115
+ """
116
+ beta0, beta1 = self.factors["beta"]
117
+ x, y = self.resample_model.random()
118
+ sq_error_loss = (y - beta0 - beta1 * x) ** 2
119
+ error_loss = y - beta0 - beta1 * x
120
+ # gradients wrt beta0 and beta1
121
+ grad_sq_error_loss = (-2 * error_loss, -2 * x * error_loss)
122
+
123
+ # Compose responses and gradients.
124
+ responses = {"sq_error_loss": sq_error_loss}
125
+ gradients = {"sq_error_loss": {"beta": grad_sq_error_loss}}
126
+ return responses, gradients
127
+
128
+
129
+ class ERMExampleProblem(Problem):
130
+ """Base class to implement simulation-optimization problems."""
131
+
132
+ class_name_abbr: ClassVar[str] = "ERM-EXAMPLE-1"
133
+ class_name: ClassVar[str] = "Min Empirical Risk"
134
+ config_class: ClassVar[type[BaseModel]] = ERMExampleProblemConfig
135
+ model_class: ClassVar[type[Model]] = ERMExampleModel
136
+ n_objectives: ClassVar[int] = 1
137
+ n_stochastic_constraints: ClassVar[int] = 0
138
+ minmax: ClassVar[tuple[int, ...]] = (-1,)
139
+ constraint_type: ClassVar[ConstraintType] = ConstraintType.UNCONSTRAINED
140
+ variable_type: ClassVar[VariableType] = VariableType.CONTINUOUS
141
+ gradient_available: ClassVar[bool] = True
142
+ model_default_factors: ClassVar[dict] = {}
143
+ model_decision_factors: ClassVar[set[str]] = {"beta"}
144
+
145
+ @property
146
+ def optimal_value(self) -> float | None: # noqa: D102
147
+ # Compute optimal beta0 and beta1
148
+ all_data = np.load("workshop/erm_data.npy")
149
+ x = all_data[:, 0]
150
+ y = all_data[:, 1]
151
+ optbeta1, optbeta0 = np.polyfit(x, y, 1)
152
+ opttrainingmse = np.mean(
153
+ [(yy - optbeta0 - optbeta1 * xx) ** 2 for (xx, yy) in zip(x, y)]
154
+ )
155
+ return opttrainingmse
156
+
157
+ @property
158
+ def optimal_solution(self) -> tuple | None: # noqa: D102
159
+ # Compute optimal beta0 and beta1
160
+ all_data = np.load("workshop/erm_data.npy")
161
+ x = all_data[:, 0]
162
+ y = all_data[:, 1]
163
+ optbeta1, optbeta0 = np.polyfit(x, y, 1)
164
+ return (optbeta0, optbeta1)
165
+
166
+ @property
167
+ def dim(self) -> int: # noqa: D102
168
+ return 2
169
+
170
+ @property
171
+ def lower_bounds(self) -> tuple: # noqa: D102
172
+ return (-np.inf,) * self.dim
173
+
174
+ @property
175
+ def upper_bounds(self) -> tuple: # noqa: D102
176
+ return (np.inf,) * self.dim
177
+
178
+ def vector_to_factor_dict(self, vector: tuple) -> dict: # noqa: D102
179
+ return {"beta": vector[:]}
180
+
181
+ def factor_dict_to_vector(self, factor_dict: dict) -> tuple: # noqa: D102
182
+ return tuple(factor_dict["beta"])
183
+
184
+ def replicate(self, _x: tuple) -> RepResult: # noqa: D102
185
+ responses, gradients = self.model.replicate()
186
+ objectives = [
187
+ Objective(
188
+ stochastic=responses["sq_error_loss"],
189
+ stochastic_gradients=gradients["sq_error_loss"]["beta"],
190
+ )
191
+ ]
192
+ return RepResult(objectives=objectives)
193
+
194
+ def get_random_solution(self, rand_sol_rng: MRG32k3a) -> tuple: # noqa: D102
195
+ # beta = tuple([rand_sol_rng.uniform(-2, 2) for _ in range(self.dim)])
196
+ beta = tuple(
197
+ rand_sol_rng.mvnormalvariate(
198
+ mean_vec=[1.0] * self.dim,
199
+ cov=np.eye(self.dim).tolist(),
200
+ factorized=False,
201
+ )
202
+ )
203
+ return beta
@@ -2,7 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- import random
5
+ from random import Random
6
6
  from typing import Annotated, ClassVar, Final, Self
7
7
 
8
8
  import numpy as np
@@ -204,7 +204,7 @@ class FacilitySizingTotalCostConfig(BaseModel):
204
204
  class DemandInputModel(InputModel):
205
205
  """Input model for multivariate normal demand at facilities."""
206
206
 
207
- rng: random.Random | None = None
207
+ rng: Random | None = None
208
208
 
209
209
  def _mvnormalvariate(
210
210
  self,
@@ -307,7 +307,7 @@ class Hotel(Model):
307
307
  total_revenue = 0
308
308
 
309
309
  # Generate interarrival times
310
- arr_bound = 10 * round(168 * np.sum(f_lambda))
310
+ arr_bound = 10 * round(168 * sum(f_lambda))
311
311
  arr_time = np.array(
312
312
  [
313
313
  [self.arrival_model.random(f_lambda[i]) for _ in range(arr_bound)]
@@ -6,8 +6,8 @@
6
6
 
7
7
  from __future__ import annotations
8
8
 
9
- import random
10
9
  from math import copysign, sqrt
10
+ from random import Random
11
11
  from typing import Annotated, ClassVar, Self
12
12
 
13
13
  import numpy as np
@@ -202,7 +202,7 @@ class IronOreMaxRevConfig(BaseModel):
202
202
  class MovementInputModel(InputModel):
203
203
  """Input model for mining movement and price shocks."""
204
204
 
205
- rng: random.Random | None = None
205
+ rng: Random | None = None
206
206
 
207
207
  def random(self, mean: float, std: float) -> float: # noqa: D102
208
208
  assert self.rng is not None
@@ -2,8 +2,8 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- import random
6
5
  from enum import IntEnum
6
+ from random import Random
7
7
  from typing import Annotated, ClassVar, Final, Self
8
8
 
9
9
  import numpy as np
@@ -215,7 +215,7 @@ class NetworkMinTotalCostConfig(BaseModel):
215
215
  class RouteInputModel(InputModel):
216
216
  """Input model for routing choices in the network."""
217
217
 
218
- rng: random.Random | None = None
218
+ rng: Random | None = None
219
219
 
220
220
  def random(self, choices: list[int], weights: list[float], k: int) -> list[int]: # noqa: D102
221
221
  assert self.rng is not None
@@ -165,7 +165,7 @@ class DemandInputModel(InputModel):
165
165
  x_rng: MRG32k3a | None = None
166
166
  y_rng: MRG32k3a | None = None
167
167
 
168
- def set_rng(self, rng: list[MRG32k3a] | tuple[MRG32k3a, MRG32k3a]) -> None: # noqa: D102 # pyrefly: ignore
168
+ def set_rng(self, rng: list[MRG32k3a] | tuple[MRG32k3a, MRG32k3a]) -> None: # noqa: D102 # type: ignore
169
169
  self.x_rng = rng[0]
170
170
  self.y_rng = rng[1]
171
171
 
@@ -5,7 +5,7 @@ from __future__ import annotations
5
5
  import bisect
6
6
  import itertools
7
7
  from collections.abc import Sequence
8
- from typing import Annotated, ClassVar, Self
8
+ from typing import Annotated, ClassVar, Self, cast
9
9
 
10
10
  import numpy as np
11
11
  from pydantic import BaseModel, Field, model_validator
@@ -256,9 +256,12 @@ class TableAllocation(Model):
256
256
  # Pass through all arrivals of groups to the restaurants.
257
257
  for n in range(n_arrivals):
258
258
  # Determine group size.
259
- group_size = self.group_size_model.random(
260
- population=group_size_options,
261
- weights=f_lambda,
259
+ group_size = cast(
260
+ int,
261
+ self.group_size_model.random(
262
+ population=group_size_options,
263
+ weights=f_lambda,
264
+ ),
262
265
  )
263
266
 
264
267
  # Find smallest table size to start search.
@@ -5,7 +5,7 @@ Stochastically Constrained Simulation Optimization Problems' by Felice, N.,
5
5
  D. J. Eckman, S. G. Henderson, and S. Shashaani
6
6
  """
7
7
 
8
- from typing import Annotated, ClassVar, Literal
8
+ from typing import Annotated, ClassVar
9
9
 
10
10
  import cvxpy as cp
11
11
  import numpy as np
@@ -44,7 +44,9 @@ class FCSAConfig(SolverConfig):
44
44
  ),
45
45
  ]
46
46
  step_type: Annotated[
47
- Literal["const", "decay"],
47
+ # TODO: change back when the old GUI is removed
48
+ # Literal["const", "decay"],
49
+ str,
48
50
  Field(default="const", description="constant or decaying step size?"),
49
51
  ]
50
52
  step_mult: Annotated[
@@ -60,7 +62,9 @@ class FCSAConfig(SolverConfig):
60
62
  Field(default=0.01, ge=0, description="tolerance function"),
61
63
  ]
62
64
  search_direction: Annotated[
63
- Literal["FCSA", "CSA-N", "CSA"],
65
+ # TODO: change back when the old GUI is removed
66
+ # Literal["FCSA", "CSA-N", "CSA"],
67
+ str,
64
68
  Field(
65
69
  default="FCSA",
66
70
  description=(
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: simoptlib
3
- Version: 1.2.1
3
+ Version: 1.2.2.post0
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 <williamgrochocinski@gmail.com>
6
6
  License: MIT License
@@ -56,6 +56,8 @@ Requires-Dist: sphinx-autoapi>=3.6.1; extra == "docs"
56
56
  Requires-Dist: sphinx-rtd-theme>=3.0.2; extra == "docs"
57
57
  Provides-Extra: notebooks
58
58
  Requires-Dist: ipykernel>=7.1.0; extra == "notebooks"
59
+ Provides-Extra: ext
60
+ Requires-Dist: simopt-extensions; extra == "ext"
59
61
  Dynamic: license-file
60
62
 
61
63
  ![SimOpt Logo](https://raw.githubusercontent.com/simopt-admin/simopt/master/.github/resources/logo_full_magnifying_glass.png)
@@ -35,12 +35,14 @@ simopt/gui/new_experiment_window.py
35
35
  simopt/gui/plot_window.py
36
36
  simopt/gui/toplevel_custom.py
37
37
  simopt/models/__init__.py
38
+ simopt/models/_ext.py
38
39
  simopt/models/amusementpark.py
39
40
  simopt/models/chessmm.py
40
41
  simopt/models/cntnv.py
41
42
  simopt/models/contam.py
42
43
  simopt/models/dualsourcing.py
43
44
  simopt/models/dynamnews.py
45
+ simopt/models/ermexample.py
44
46
  simopt/models/example.py
45
47
  simopt/models/facilitysizing.py
46
48
  simopt/models/fixedsan.py
@@ -22,5 +22,8 @@ sphinx>=8.2.3
22
22
  sphinx-autoapi>=3.6.1
23
23
  sphinx-rtd-theme>=3.0.2
24
24
 
25
+ [ext]
26
+ simopt-extensions
27
+
25
28
  [notebooks]
26
29
  ipykernel>=7.1.0
File without changes
File without changes
File without changes