Function bodies 210 total
SimulatedUser.__repr__ method · python · L189-L196 (8 LOC)src/agent_sim_bridge/staging/simulated_users.py
def __repr__(self) -> str:
return (
f"SimulatedUser("
f"name={self._profile.name!r}, "
f"persona={self._profile.persona!r}, "
f"cursor={self._cursor}/{len(self._profile.messages)}"
f")"
)CalibrationProfile.__post_init__ method · python · L56-L69 (14 LOC)src/agent_sim_bridge/transfer/bridge.py
def __post_init__(self) -> None:
if len(self.scale_factors) != len(self.offsets):
raise ValueError(
f"scale_factors length ({len(self.scale_factors)}) must equal "
f"offsets length ({len(self.offsets)})."
)
if not self.scale_factors:
raise ValueError("CalibrationProfile must have at least one dimension.")
for i, scale in enumerate(self.scale_factors):
if scale == 0.0:
raise ValueError(
f"scale_factors[{i}] is zero, which would make the inverse "
"transform undefined."
)TransferBridge.sim_to_real method · python · L112-L139 (28 LOC)src/agent_sim_bridge/transfer/bridge.py
def sim_to_real(self, sim_values: list[float]) -> list[float]:
"""Transform simulation values to their real-world equivalents.
Applies ``real[i] = sim[i] * scale[i] + offset[i]`` element-wise.
Parameters
----------
sim_values:
Per-dimension values in simulation units. Length must equal
:attr:`CalibrationProfile.n_dims`.
Returns
-------
list[float]
Values transformed to real-world units.
Raises
------
ValueError
If ``sim_values`` length does not match the profile.
"""
self._check_length(sim_values)
return [
value * scale + offset
for value, scale, offset in zip(
sim_values, self._profile.scale_factors, self._profile.offsets
)
]TransferBridge.real_to_sim method · python · L141-L168 (28 LOC)src/agent_sim_bridge/transfer/bridge.py
def real_to_sim(self, real_values: list[float]) -> list[float]:
"""Transform real-world values back to simulation units.
Applies ``sim[i] = (real[i] - offset[i]) / scale[i]`` element-wise.
Parameters
----------
real_values:
Per-dimension values in real-world units. Length must equal
:attr:`CalibrationProfile.n_dims`.
Returns
-------
list[float]
Values in simulation units.
Raises
------
ValueError
If ``real_values`` length does not match the profile.
"""
self._check_length(real_values)
return [
(value - offset) / scale
for value, scale, offset in zip(
real_values, self._profile.scale_factors, self._profile.offsets
)
]_ols_slope_intercept function · python · L25-L74 (50 LOC)src/agent_sim_bridge/transfer/calibration.py
def _ols_slope_intercept(
x_values: list[float],
y_values: list[float],
) -> tuple[float, float]:
"""Return (slope, intercept) from ordinary least squares.
Solves::
slope = (n * sum(x*y) - sum(x) * sum(y)) /
(n * sum(x^2) - sum(x)^2)
intercept = (sum(y) - slope * sum(x)) / n
Falls back to slope=1, intercept=0 if the system is singular (e.g., all
x values identical).
Parameters
----------
x_values:
Predictor values (simulation observations for one dimension).
y_values:
Target values (real-world observations for the same dimension).
Returns
-------
tuple[float, float]
``(slope, intercept)`` of the fitted line.
"""
n = len(x_values)
if n == 0:
return 1.0, 0.0
sum_x = sum(x_values)
sum_y = sum(y_values)
sum_xy = sum(xi * yi for xi, yi in zip(x_values, y_values))
sum_xx = sum(xi * xi for xi in x_values)
denominator = n * sum_xx - sum_x * Calibrator.calibrate method · python · L105-L176 (72 LOC)src/agent_sim_bridge/transfer/calibration.py
def calibrate(
self,
sim_obs: list[list[float]],
real_obs: list[list[float]],
) -> CalibrationProfile:
"""Fit a :class:`~agent_sim_bridge.transfer.bridge.CalibrationProfile` from paired samples.
Uses per-dimension ordinary least squares: for each dimension ``i``
it fits ``real[i] = sim[i] * scale[i] + offset[i]``.
Parameters
----------
sim_obs:
List of simulation observation vectors. Each inner list must
have the same length (number of dimensions).
real_obs:
List of real-world observation vectors, paired with ``sim_obs``.
Must have the same outer and inner lengths as ``sim_obs``.
Returns
-------
CalibrationProfile
Fitted profile with ``scale_factors`` and ``offsets``.
Raises
------
ValueError
If ``sim_obs`` and ``real_obs`` have different lengths, or if
any observaCalibrator.evaluate_calibration method · python · L178-L236 (59 LOC)src/agent_sim_bridge/transfer/calibration.py
def evaluate_calibration(
self,
sim_obs: list[list[float]],
real_obs: list[list[float]],
profile: CalibrationProfile | None = None,
) -> float:
"""Compute mean absolute error between real observations and predicted values.
Uses the provided ``profile`` (or the last fitted profile if
``profile`` is ``None``) to transform ``sim_obs`` and compares the
result to ``real_obs`` element-wise.
Parameters
----------
sim_obs:
Simulation observation vectors.
real_obs:
Corresponding real-world observation vectors.
profile:
Profile to evaluate. Defaults to the most recently fitted
profile from :meth:`calibrate`.
Returns
-------
float
Mean absolute error across all samples and dimensions.
Raises
------
RuntimeError
If no profile is available (neither passed nor previoRepobility · code-quality intelligence · https://repobility.com
RandomizationConfig.sample method · python · L66-L100 (35 LOC)src/agent_sim_bridge/transfer/domain_randomization.py
def sample(self) -> float:
"""Draw one sample from this configuration's distribution.
Returns
-------
float
Sampled parameter value, clipped to ``[clip_low, clip_high]``
if those bounds are set.
"""
if self.distribution == DistributionType.CONSTANT:
value = self.low
elif self.distribution == DistributionType.UNIFORM:
value = random.uniform(self.low, self.high)
elif self.distribution == DistributionType.GAUSSIAN:
# low = mean, high = std_dev
value = random.gauss(self.low, self.high)
elif self.distribution == DistributionType.LOG_UNIFORM:
import math
if self.low <= 0 or self.high <= 0:
raise ValueError(
"LOG_UNIFORM requires low > 0 and high > 0, "
f"got low={self.low}, high={self.high}."
)
log_low = math.log(self.low)
logDomainRandomizer.randomize method · python · L129-L160 (32 LOC)src/agent_sim_bridge/transfer/domain_randomization.py
def randomize(self, configs: list[RandomizationConfig]) -> dict[str, float]:
"""Sample one value for each configuration.
Parameters
----------
configs:
List of parameter specifications. May be empty (returns ``{}``).
Returns
-------
dict[str, float]
Mapping of ``parameter_name`` to sampled value.
"""
original_state = random.getstate()
try:
# Use the internal Random instance for reproducibility.
result: dict[str, float] = {}
for config in configs:
# Temporarily swap stdlib RNG state to our seeded instance.
random.setstate(self._rng.getstate())
value = config.sample()
self._rng.setstate(random.getstate())
result[config.parameter_name] = value
logger.debug(
"Randomized %r -> %.6f (%s)",
config.parameter_name,
DomainRandomizer.apply_randomization method · python · L162-L199 (38 LOC)src/agent_sim_bridge/transfer/domain_randomization.py
def apply_randomization(
self,
env: object,
configs: list[RandomizationConfig],
) -> dict[str, float]:
"""Sample parameters and apply them to ``env`` via attribute assignment.
The method traverses dot-path names in each config's
``parameter_name`` and sets the final attribute on the resolved
object. For example, a ``parameter_name`` of ``"physics.gravity"``
calls ``setattr(env.physics, "gravity", value)``.
Parameters
----------
env:
The environment object to modify in place.
configs:
Randomization configurations to apply.
Returns
-------
dict[str, float]
The parameter values that were applied (same as :meth:`randomize`).
Raises
------
AttributeError
If a path segment does not exist on the target object.
"""
sampled = self.randomize(configs)
for parameter_name, ‹ prevpage 5 / 5