code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def create_default_sensor_config(
entity_id: str, area: Union[str, None] = None, sensor_type: str = "other"
) -> Dict[str, Any]:
"""Create a default dictionary for a sensor entry."""
config = {
"entity_id": entity_id,
"enabled": True,
"name": entity_id.split(".")[-1].replace("_", " "... | Create a default dictionary for a sensor entry. | create_default_sensor_config | python | nielsfaber/alarmo | tests/helpers.py | https://github.com/nielsfaber/alarmo/blob/master/tests/helpers.py | Apache-2.0 |
def patch_alarmo_integration_dependencies(mock_storage_instance: Any):
"""Patches common dependencies for setting up the Alarmo integration in tests."""
async def mock_async_get_registry_for_patch(_: Any):
return mock_storage_instance
patches = [
patch(
"custom_components.alarm... | Patches common dependencies for setting up the Alarmo integration in tests. | patch_alarmo_integration_dependencies | python | nielsfaber/alarmo | tests/helpers.py | https://github.com/nielsfaber/alarmo/blob/master/tests/helpers.py | Apache-2.0 |
def make_alarmo_entry(
entry_id: str = "test_entry",
version: int = 1,
options: Optional[Dict[str, Any]] = None,
) -> MockConfigEntry:
"""Create a MockConfigEntry for Alarmo with common defaults."""
return MockConfigEntry(
domain="alarmo",
data={"title": "Alarmo"},
options=op... | Create a MockConfigEntry for Alarmo with common defaults. | make_alarmo_entry | python | nielsfaber/alarmo | tests/helpers.py | https://github.com/nielsfaber/alarmo/blob/master/tests/helpers.py | Apache-2.0 |
def assert_alarm_state(hass: Any, entity_id: str, expected_state: str) -> None:
"""Assert the state of an alarm entity."""
state = hass.states.get(entity_id)
assert state is not None, f"Entity {entity_id} not found in hass.states"
assert (
state.state == expected_state
), f"Expected {entity_... | Assert the state of an alarm entity. | assert_alarm_state | python | nielsfaber/alarmo | tests/helpers.py | https://github.com/nielsfaber/alarmo/blob/master/tests/helpers.py | Apache-2.0 |
async def advance_time(hass: Any, seconds: int) -> None:
"""Advance Home Assistant time by a given number of seconds and block till done."""
now = utcnow()
future = now + datetime.timedelta(seconds=seconds)
from .common import async_fire_time_changed
async_fire_time_changed(hass, future)
await ... | Advance Home Assistant time by a given number of seconds and block till done. | advance_time | python | nielsfaber/alarmo | tests/helpers.py | https://github.com/nielsfaber/alarmo/blob/master/tests/helpers.py | Apache-2.0 |
async def cleanup_timers(hass: Any) -> None:
"""Advance time by a long duration to ensure all timers are cleared."""
await advance_time(hass, 300) # 5 minutes | Advance time by a long duration to ensure all timers are cleared. | cleanup_timers | python | nielsfaber/alarmo | tests/helpers.py | https://github.com/nielsfaber/alarmo/blob/master/tests/helpers.py | Apache-2.0 |
def setup_alarmo_entry(
hass: Any,
areas: List[Dict[str, Any]],
sensors: List[Dict[str, Any]],
entry_id: str,
sensor_groups: Optional[List[Dict[str, Any]]] = None,
users: Optional[Dict[str, Dict[str, Any]]] = None,
master_enabled: bool = False,
):
"""Create storage and entry, add entry t... | Create storage and entry, add entry to hass, and return (storage, entry). | setup_alarmo_entry | python | nielsfaber/alarmo | tests/helpers.py | https://github.com/nielsfaber/alarmo/blob/master/tests/helpers.py | Apache-2.0 |
async def test_alarm_master_state_mirroring(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test that alarm master mirrors area states according to priority rules."""
area1 = AreaFactory.create_area(
area_id="area_1",
name="Test Area 1",
modes=["armed_away", "armed_home"],... | Test that alarm master mirrors area states according to priority rules. | test_alarm_master_state_mirroring | python | nielsfaber/alarmo | tests/test_alarm_master.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_alarm_master.py | Apache-2.0 |
async def test_alarm_master_propagates_commands(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test that arming/disarming master propagates to all areas."""
# Create two areas
area1 = AreaFactory.create_area(
area_id="area_1",
name="Test Area 1 Propagation",
modes=["ar... | Test that arming/disarming master propagates to all areas. | test_alarm_master_propagates_commands | python | nielsfaber/alarmo | tests/test_alarm_master.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_alarm_master.py | Apache-2.0 |
async def test_alarm_master_priority_states(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test master alarm state priority: triggered > pending > arming > armed > disarmed."""
# Create areas with immediate arming
area1 = AreaFactory.create_area(
area_id="area_1",
name="Test ... | Test master alarm state priority: triggered > pending > arming > armed > disarmed. | test_alarm_master_priority_states | python | nielsfaber/alarmo | tests/test_alarm_master.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_alarm_master.py | Apache-2.0 |
async def test_arm_on_close_behavior(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test that arming proceeds if a door is opened and closed during exit delay."""
alarm_entity = "alarm_control_panel.test_area_1"
sensor = "binary_sensor.generic_area_1_door_sensor"
area = AreaFactory.create... | Test that arming proceeds if a door is opened and closed during exit delay. | test_arm_on_close_behavior | python | nielsfaber/alarmo | tests/test_arm_on_close.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_arm_on_close.py | Apache-2.0 |
async def test_arm_on_close_timeout(hass: Any, enable_custom_integrations: Any) -> None:
"""Test that arming fails if a door with arm_on_close=True remains open after the exit delay expires."""
alarm_entity = "alarm_control_panel.test_area_1"
sensor = "binary_sensor.generic_area_1_door_sensor"
area = Ar... | Test that arming fails if a door with arm_on_close=True remains open after the exit delay expires. | test_arm_on_close_timeout | python | nielsfaber/alarmo | tests/test_arm_on_close.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_arm_on_close.py | Apache-2.0 |
async def test_arm_immediate_arms_right_away_with_allow_open(
hass: Any, enable_custom_integrations: Any
):
"""Test that alarm arms immediately if area exit_time=0"""
sensor = "binary_sensor.generic_area_1_door_sensor"
alarm_entity = "alarm_control_panel.test_area_1"
armed_away_exit_time = 0
ar... | Test that alarm arms immediately if area exit_time=0 | test_arm_immediate_arms_right_away_with_allow_open | python | nielsfaber/alarmo | tests/test_basic_features.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_basic_features.py | Apache-2.0 |
def get_area_mode_time(area_id: str, mode: str, key: str) -> int:
"""Get the time value for a given area, mode, and key (exit_time, entry_time, trigger_time)."""
if area_id == "area_1":
area_config = AreaFactory.create_area()
elif area_id == "area_2":
area_config = AreaFactory.create_area_2... | Get the time value for a given area, mode, and key (exit_time, entry_time, trigger_time). | get_area_mode_time | python | nielsfaber/alarmo | tests/test_basic_features.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_basic_features.py | Apache-2.0 |
async def test_arm_home_from_disarmed(hass: Any, enable_custom_integrations: Any):
"""Test arm home from disarmed with immediate arming (no exit delay)"""
sensor = get_generic_sensor()
armed_home_exit_time = 0
area = AreaFactory.create_area(
area_id="area_1",
modes=["armed_home"],
... | Test arm home from disarmed with immediate arming (no exit delay) | test_arm_home_from_disarmed | python | nielsfaber/alarmo | tests/test_basic_features.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_basic_features.py | Apache-2.0 |
async def test_armed_away_entry_delay_and_trigger(
hass: Any, enable_custom_integrations: Any
):
"""Test entry delay and triggering in armed_away mode (no exit delay)."""
sensor = get_generic_sensor()
armed_away_exit_time = 0
armed_away_entry_time = get_area_mode_time("area_1", "armed_away", "entry_... | Test entry delay and triggering in armed_away mode (no exit delay). | test_armed_away_entry_delay_and_trigger | python | nielsfaber/alarmo | tests/test_basic_features.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_basic_features.py | Apache-2.0 |
async def test_arm_with_exit_delay_and_allow_open(
hass: Any, enable_custom_integrations: Any
):
"""Test arming with a sensor that has use_exit_delay=True and allow_open=True"""
sensor = get_generic_sensor()
armed_away_exit_time = 20
area = AreaFactory.create_area(
area_id="area_1",
... | Test arming with a sensor that has use_exit_delay=True and allow_open=True | test_arm_with_exit_delay_and_allow_open | python | nielsfaber/alarmo | tests/test_basic_features.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_basic_features.py | Apache-2.0 |
async def test_sensor_always_on_triggers_when_disarmed(
hass: Any, enable_custom_integrations: Any
):
"""Test that a sensor with always_on: True triggers the alarm even when disarmed."""
sensor = get_generic_sensor()
# For always_on, specific mode times (like armed_away_trigger_time) are used.
# Are... | Test that a sensor with always_on: True triggers the alarm even when disarmed. | test_sensor_always_on_triggers_when_disarmed | python | nielsfaber/alarmo | tests/test_basic_features.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_basic_features.py | Apache-2.0 |
async def test_arm_away_with_exit_delay(hass: Any, enable_custom_integrations: Any):
"""Test arm away with exit delay"""
sensor = get_generic_sensor()
armed_away_exit_time = 30
area = AreaFactory.create_area(
area_id="area_1",
modes=["armed_away"],
armed_away_exit_time=armed_awa... | Test arm away with exit delay | test_arm_away_with_exit_delay | python | nielsfaber/alarmo | tests/test_basic_features.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_basic_features.py | Apache-2.0 |
async def test_arm_blocked_with_triggered_sensor_and_no_allow_open(
hass: Any, enable_custom_integrations: Any
):
"""Test arm blocked with triggered sensor and no allow open"""
sensor = get_generic_sensor()
armed_away_exit_time = 30
area = AreaFactory.create_area(
area_id="area_1",
... | Test arm blocked with triggered sensor and no allow open | test_arm_blocked_with_triggered_sensor_and_no_allow_open | python | nielsfaber/alarmo | tests/test_basic_features.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_basic_features.py | Apache-2.0 |
async def test_sensor_trigger_unavailable(hass: Any, enable_custom_integrations: Any):
"""Test that a sensor with trigger_unavailable, True triggers the alarm when unavailable."""
sensor = get_generic_sensor()
armed_away_exit_time = 0
area = AreaFactory.create_area(
area_id="area_1",
mo... | Test that a sensor with trigger_unavailable, True triggers the alarm when unavailable. | test_sensor_trigger_unavailable | python | nielsfaber/alarmo | tests/test_basic_features.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_basic_features.py | Apache-2.0 |
async def test_auto_bypass_true_integration(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test that a sensor with auto_bypass true and correct mode is bypassed and alarm arms."""
alarm_entity = "alarm_control_panel.test_area_1"
bypass_sensor = "binary_sensor.generic_area_1_door_sensor"
b... | Test that a sensor with auto_bypass true and correct mode is bypassed and alarm arms. | test_auto_bypass_true_integration | python | nielsfaber/alarmo | tests/test_bypass_mode.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_bypass_mode.py | Apache-2.0 |
async def test_auto_bypass_false_single_sensor(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test that a single sensor with auto_bypass false blocks arming if open (area_1 only)."""
alarm_entity = "alarm_control_panel.test_area_1"
bypass_sensor = "binary_sensor.generic_area_1_door_sensor"
... | Test that a single sensor with auto_bypass false blocks arming if open (area_1 only). | test_auto_bypass_false_single_sensor | python | nielsfaber/alarmo | tests/test_bypass_mode.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_bypass_mode.py | Apache-2.0 |
async def test_auto_bypass_false_multiple_areas_exit_delay(
hass: Any, enable_custom_integrations: Any
) -> None:
"""
Test that arming both areas with open, non-bypassable sensors, results
in both areas being disarmed after exit delay.
"""
alarm_entity_1 = "alarm_control_panel.test_area_1"
a... |
Test that arming both areas with open, non-bypassable sensors, results
in both areas being disarmed after exit delay.
| test_auto_bypass_false_multiple_areas_exit_delay | python | nielsfaber/alarmo | tests/test_bypass_mode.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_bypass_mode.py | Apache-2.0 |
async def test_auto_bypass_modes_not_matched(
hass: Any, enable_custom_integrations: Any
) -> None:
"""
Test that a sensor with auto_bypass=True but arming in a mode NOT in auto_bypass_modes
doesn't get bypassed.
"""
alarm_entity = "alarm_control_panel.test_area_1"
bypass_sensor = "binary_se... |
Test that a sensor with auto_bypass=True but arming in a mode NOT in auto_bypass_modes
doesn't get bypassed.
| test_auto_bypass_modes_not_matched | python | nielsfaber/alarmo | tests/test_bypass_mode.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_bypass_mode.py | Apache-2.0 |
async def test_auto_bypass_multiple_modes(
hass: Any, enable_custom_integrations: Any
) -> None:
"""
Test that a sensor with multiple modes in auto_bypass_modes
gets bypassed in each specified mode.
"""
alarm_entity = "alarm_control_panel.test_area_1"
bypass_sensor = "binary_sensor.generic_... |
Test that a sensor with multiple modes in auto_bypass_modes
gets bypassed in each specified mode.
| test_auto_bypass_multiple_modes | python | nielsfaber/alarmo | tests/test_bypass_mode.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_bypass_mode.py | Apache-2.0 |
async def test_auto_bypass_empty_modes(
hass: Any, enable_custom_integrations: Any
) -> None:
"""
Test for a sensor with auto_bypass=True but empty auto_bypass_modes.
This scenario is restricted in the UI and the sensor config service but
it should not fail in unexpected ways
Verify the sensor i... |
Test for a sensor with auto_bypass=True but empty auto_bypass_modes.
This scenario is restricted in the UI and the sensor config service but
it should not fail in unexpected ways
Verify the sensor is not bypassed
| test_auto_bypass_empty_modes | python | nielsfaber/alarmo | tests/test_bypass_mode.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_bypass_mode.py | Apache-2.0 |
def get_environmental_sensors() -> list[dict[str, Any]]:
"""Get all environmental sensors that should trigger the alarm."""
return [
SensorFactory.create_sensor(
entity_id=SMOKE_SENSOR,
name="Smoke Detector",
area="area_1",
modes=["armed_away", "armed_home... | Get all environmental sensors that should trigger the alarm. | get_environmental_sensors | python | nielsfaber/alarmo | tests/test_environmental_sensors.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_environmental_sensors.py | Apache-2.0 |
async def test_environmental_sensor_disarmed_state(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test that environmental sensors trigger alarm when system is disarmed."""
area = AreaFactory.create_area(area_id="area_1", name="Test Area 1")
sensors = get_environmental_sensors()
storage, e... | Test that environmental sensors trigger alarm when system is disarmed. | test_environmental_sensor_disarmed_state | python | nielsfaber/alarmo | tests/test_environmental_sensors.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_environmental_sensors.py | Apache-2.0 |
async def test_environmental_sensor_armed_state(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test that environmental sensors trigger alarm when system is armed."""
area = AreaFactory.create_area(area_id="area_1", name="Test Area 1")
sensors = get_environmental_sensors()
storage, entry =... | Test that environmental sensors trigger alarm when system is armed. | test_environmental_sensor_armed_state | python | nielsfaber/alarmo | tests/test_environmental_sensors.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_environmental_sensors.py | Apache-2.0 |
async def test_all_environmental_sensors(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test all types of environmental sensors to verify they all trigger the alarm."""
area = AreaFactory.create_area(area_id="area_1", name="Test Area 1")
sensors = get_environmental_sensors()
storage, entr... | Test all types of environmental sensors to verify they all trigger the alarm. | test_all_environmental_sensors | python | nielsfaber/alarmo | tests/test_environmental_sensors.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_environmental_sensors.py | Apache-2.0 |
async def test_environmental_sensor_multiple_arm_modes(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test environmental sensors trigger in all arm modes."""
area = AreaFactory.create_area(area_id="area_1", name="Test Area 1")
sensors = get_environmental_sensors()
storage, entry = setup_a... | Test environmental sensors trigger in all arm modes. | test_environmental_sensor_multiple_arm_modes | python | nielsfaber/alarmo | tests/test_environmental_sensors.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_environmental_sensors.py | Apache-2.0 |
async def test_failed_to_arm_event_fired_when_sensor_blocks_arming(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test that alarmo_failed_to_arm event is fired when a sensor blocks arming."""
# Set up event capture
events: list[Event] = []
exit_delay = LONG_EXIT_DELAY
def capture_ev... | Test that alarmo_failed_to_arm event is fired when a sensor blocks arming. | test_failed_to_arm_event_fired_when_sensor_blocks_arming | python | nielsfaber/alarmo | tests/test_events.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_events.py | Apache-2.0 |
async def test_failed_to_arm_event_with_multiple_blocking_sensors(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test that alarmo_failed_to_arm event includes all blocking sensors."""
events: list[Event] = []
def capture_event(event: Event) -> None:
"""Capture the alarmo_failed_to_a... | Test that alarmo_failed_to_arm event includes all blocking sensors. | test_failed_to_arm_event_with_multiple_blocking_sensors | python | nielsfaber/alarmo | tests/test_events.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_events.py | Apache-2.0 |
async def test_no_failed_to_arm_event_when_arming_succeeds(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test that no alarmo_failed_to_arm event is fired when arming succeeds."""
events: list[Event] = []
exit_delay = SHORT_EXIT_DELAY
def capture_event(event: Event) -> None:
"""... | Test that no alarmo_failed_to_arm event is fired when arming succeeds. | test_no_failed_to_arm_event_when_arming_succeeds | python | nielsfaber/alarmo | tests/test_events.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_events.py | Apache-2.0 |
async def test_backend_arm_event_dispatched_on_arming(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test that backend ARM event is dispatched during arming process."""
backend_events: list[dict[str, Any]] = []
exit_delay = SHORT_EXIT_DELAY
def capture_backend_event(event_type: str, are... | Test that backend ARM event is dispatched during arming process. | test_backend_arm_event_dispatched_on_arming | python | nielsfaber/alarmo | tests/test_events.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_events.py | Apache-2.0 |
async def test_backend_disarm_event_dispatched_on_disarming(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test that backend DISARM event is dispatched during disarming process."""
backend_events: list[dict[str, Any]] = []
def capture_backend_event(event_type: str, area_id: str, args: dict[... | Test that backend DISARM event is dispatched during disarming process. | test_backend_disarm_event_dispatched_on_disarming | python | nielsfaber/alarmo | tests/test_events.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_events.py | Apache-2.0 |
async def test_backend_trigger_event_dispatched_on_triggering(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test that backend TRIGGER event is dispatched when alarm is triggered."""
backend_events: list[dict[str, Any]] = []
default_entry_delay = 30 # Default entry delay in seconds
def... | Test that backend TRIGGER event is dispatched when alarm is triggered. | test_backend_trigger_event_dispatched_on_triggering | python | nielsfaber/alarmo | tests/test_events.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_events.py | Apache-2.0 |
async def test_ready_to_arm_modes_changed_event_on_sensor_state_change(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test that ready_to_arm_modes_changed events are fired when sensor states affect available arm modes."""
backend_events: list[dict[str, Any]] = []
def capture_backend_event(
... | Test that ready_to_arm_modes_changed events are fired when sensor states affect available arm modes. | test_ready_to_arm_modes_changed_event_on_sensor_state_change | python | nielsfaber/alarmo | tests/test_ready_to_arm_events.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_ready_to_arm_events.py | Apache-2.0 |
async def test_ready_to_arm_modes_changed_event_with_door_sensor_multiple_modes(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test ready_to_arm_modes_changed event with door sensor affecting multiple modes."""
backend_events: list[dict[str, Any]] = []
def capture_backend_event(
eve... | Test ready_to_arm_modes_changed event with door sensor affecting multiple modes. | test_ready_to_arm_modes_changed_event_with_door_sensor_multiple_modes | python | nielsfaber/alarmo | tests/test_ready_to_arm_events.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_ready_to_arm_events.py | Apache-2.0 |
async def test_motion_sensor_not_monitored_when_disarmed(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test that motion sensors are NOT monitored when alarm is disarmed (by design)."""
backend_events: list[dict[str, Any]] = []
def capture_backend_event(
event_type: str, area_id: st... | Test that motion sensors are NOT monitored when alarm is disarmed (by design). | test_motion_sensor_not_monitored_when_disarmed | python | nielsfaber/alarmo | tests/test_ready_to_arm_events.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_ready_to_arm_events.py | Apache-2.0 |
async def test_ready_to_arm_with_multiple_sensors_same_mode(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test ready-to-arm events with multiple sensors affecting the same mode."""
backend_events: list[dict[str, Any]] = []
def capture_backend_event(
event_type: str, area_id: str, a... | Test ready-to-arm events with multiple sensors affecting the same mode. | test_ready_to_arm_with_multiple_sensors_same_mode | python | nielsfaber/alarmo | tests/test_ready_to_arm_events.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_ready_to_arm_events.py | Apache-2.0 |
async def test_ready_to_arm_with_bypass_sensors(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test ready-to-arm with auto-bypass sensors."""
backend_events: list[dict[str, Any]] = []
def capture_backend_event(
event_type: str, area_id: str, args: dict[str, Any]
) -> None:
... | Test ready-to-arm with auto-bypass sensors. | test_ready_to_arm_with_bypass_sensors | python | nielsfaber/alarmo | tests/test_ready_to_arm_events.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_ready_to_arm_events.py | Apache-2.0 |
async def test_ready_to_arm_with_allow_open_sensors(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test ready-to-arm with allow_open sensors."""
backend_events: list[dict[str, Any]] = []
def capture_backend_event(
event_type: str, area_id: str, args: dict[str, Any]
) -> None:
... | Test ready-to-arm with allow_open sensors. | test_ready_to_arm_with_allow_open_sensors | python | nielsfaber/alarmo | tests/test_ready_to_arm_events.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_ready_to_arm_events.py | Apache-2.0 |
async def test_ready_to_arm_with_always_on_sensors(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test ready-to-arm with always_on sensors."""
backend_events: list[dict[str, Any]] = []
def capture_backend_event(
event_type: str, area_id: str, args: dict[str, Any]
) -> None:
... | Test ready-to-arm with always_on sensors. | test_ready_to_arm_with_always_on_sensors | python | nielsfaber/alarmo | tests/test_ready_to_arm_events.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_ready_to_arm_events.py | Apache-2.0 |
async def test_ready_to_arm_cross_area_independence(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test that ready-to-arm events are independent between areas."""
backend_events: list[dict[str, Any]] = []
def capture_backend_event(
event_type: str, area_id: str, args: dict[str, Any]... | Test that ready-to-arm events are independent between areas. | test_ready_to_arm_cross_area_independence | python | nielsfaber/alarmo | tests/test_ready_to_arm_events.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_ready_to_arm_events.py | Apache-2.0 |
async def test_ready_to_arm_multiple_modes_different_sensors(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test ready-to-arm with different sensors affecting different modes."""
backend_events: list[dict[str, Any]] = []
def capture_backend_event(
event_type: str, area_id: str, args... | Test ready-to-arm with different sensors affecting different modes. | test_ready_to_arm_multiple_modes_different_sensors | python | nielsfaber/alarmo | tests/test_ready_to_arm_events.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_ready_to_arm_events.py | Apache-2.0 |
async def test_home_assistant_event_bus_ready_to_arm_event(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test that alarmo_ready_to_arm_modes_updated events are fired on the Home Assistant event bus.
This tests the case described in the documentation where users create template entities
that... | Test that alarmo_ready_to_arm_modes_updated events are fired on the Home Assistant event bus.
This tests the case described in the documentation where users create template entities
that listen to the HA event bus for 'alarmo_ready_to_arm_modes_updated' events.
| test_home_assistant_event_bus_ready_to_arm_event | python | nielsfaber/alarmo | tests/test_ready_to_arm_events.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_ready_to_arm_events.py | Apache-2.0 |
def capture_ha_event(event) -> None:
"""Capture Home Assistant event bus events."""
ha_events.append(
{
"event_type": event.event_type,
"data": event.data,
"origin": event.origin,
"time_fired": event.time_fired,
}
... | Capture Home Assistant event bus events. | capture_ha_event | python | nielsfaber/alarmo | tests/test_ready_to_arm_events.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_ready_to_arm_events.py | Apache-2.0 |
async def test_single_sensor_in_group_does_not_trigger(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test that a single sensor in a group doesn't trigger the alarm."""
area = AreaFactory.create_area(area_id="area_1", name="Test Area 1")
sensors = [
SensorFactory.create_door_sensor(
... | Test that a single sensor in a group doesn't trigger the alarm. | test_single_sensor_in_group_does_not_trigger | python | nielsfaber/alarmo | tests/test_sensor_groups.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_sensor_groups.py | Apache-2.0 |
async def test_two_sensors_in_group_trigger_within_timeout_triggers_alarm(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test that two sensors in a group triggering within timeout trigger the alarm."""
area = AreaFactory.create_area(area_id="area_1", name="Test Area 1")
sensors = [
Se... | Test that two sensors in a group triggering within timeout trigger the alarm. | test_two_sensors_in_group_trigger_within_timeout_triggers_alarm | python | nielsfaber/alarmo | tests/test_sensor_groups.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_sensor_groups.py | Apache-2.0 |
async def test_two_sensors_in_group_trigger_outside_timeout_does_not_trigger(
hass: Any, enable_custom_integrations: Any
) -> None:
"""Test that two sensors in a group triggering outside timeout don't trigger the alarm."""
area = AreaFactory.create_area(area_id="area_1", name="Test Area 1")
sensors = [
... | Test that two sensors in a group triggering outside timeout don't trigger the alarm. | test_two_sensors_in_group_trigger_outside_timeout_does_not_trigger | python | nielsfaber/alarmo | tests/test_sensor_groups.py | https://github.com/nielsfaber/alarmo/blob/master/tests/test_sensor_groups.py | Apache-2.0 |
def __init__(
self,
env: CMDP | None = None,
actor: Actor | None = None,
actor_critic: ConstraintActorCritic | ConstraintActorQCritic | None = None,
dynamics: EnsembleDynamicsModel | None = None,
planner: (
CEMPlanner | ARCPlanner | SafeARCPlanner | CCEPlanner... | Initialize an instance of :class:`Evaluator`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/evaluator.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/evaluator.py | Apache-2.0 |
def __set_render_mode(self, render_mode: str) -> None:
"""Set the render mode.
Args:
render_mode (str, optional): The render mode. Defaults to 'rgb_array'.
Raises:
NotImplementedError: If the render mode is not implemented.
"""
# set the render mode
... | Set the render mode.
Args:
render_mode (str, optional): The render mode. Defaults to 'rgb_array'.
Raises:
NotImplementedError: If the render mode is not implemented.
| __set_render_mode | python | PKU-Alignment/omnisafe | omnisafe/evaluator.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/evaluator.py | Apache-2.0 |
def __load_cfgs(self, save_dir: str) -> None:
"""Load the config from the save directory.
Args:
save_dir (str): Directory where the model is saved.
Raises:
FileNotFoundError: If the config file is not found.
"""
cfg_path = os.path.join(save_dir, 'config.... | Load the config from the save directory.
Args:
save_dir (str): Directory where the model is saved.
Raises:
FileNotFoundError: If the config file is not found.
| __load_cfgs | python | PKU-Alignment/omnisafe | omnisafe/evaluator.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/evaluator.py | Apache-2.0 |
def __load_model_and_env(
self,
save_dir: str,
model_name: str,
env_kwargs: dict[str, Any],
) -> None:
"""Load the model from the save directory.
Args:
save_dir (str): Directory where the model is saved.
model_name (str): Name of the model.
... | Load the model from the save directory.
Args:
save_dir (str): Directory where the model is saved.
model_name (str): Name of the model.
env_kwargs (dict[str, Any]): Keyword arguments for the environment.
Raises:
FileNotFoundError: If the model is not foun... | __load_model_and_env | python | PKU-Alignment/omnisafe | omnisafe/evaluator.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/evaluator.py | Apache-2.0 |
def load_saved(
self,
save_dir: str,
model_name: str,
render_mode: str = 'rgb_array',
camera_name: str | None = None,
camera_id: int | None = None,
width: int = 256,
height: int = 256,
) -> None:
"""Load a saved model.
Args:
... | Load a saved model.
Args:
save_dir (str): The directory where the model is saved.
model_name (str): The name of the model.
render_mode (str, optional): The render mode, ranging from 'human', 'rgb_array',
'rgb_array_list'. Defaults to 'rgb_array'.
... | load_saved | python | PKU-Alignment/omnisafe | omnisafe/evaluator.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/evaluator.py | Apache-2.0 |
def evaluate(
self,
num_episodes: int = 10,
cost_criteria: float = 1.0,
) -> tuple[list[float], list[float]]:
"""Evaluate the agent for num_episodes episodes.
Args:
num_episodes (int, optional): The number of episodes to evaluate. Defaults to 10.
cost... | Evaluate the agent for num_episodes episodes.
Args:
num_episodes (int, optional): The number of episodes to evaluate. Defaults to 10.
cost_criteria (float, optional): The cost criteria. Defaults to 1.0.
Returns:
(episode_rewards, episode_costs): The episode rewards ... | evaluate | python | PKU-Alignment/omnisafe | omnisafe/evaluator.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/evaluator.py | Apache-2.0 |
def fps(self) -> int:
"""The fps of the environment.
Raises:
AssertionError: If the environment is not provided or created.
AtrributeError: If the fps is not found.
"""
assert (
self._env is not None
), 'The environment must be provided or cre... | The fps of the environment.
Raises:
AssertionError: If the environment is not provided or created.
AtrributeError: If the fps is not found.
| fps | python | PKU-Alignment/omnisafe | omnisafe/evaluator.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/evaluator.py | Apache-2.0 |
def render( # pylint: disable=too-many-locals,too-many-arguments,too-many-branches,too-many-statements
self,
num_episodes: int = 1,
save_replay_path: str | None = None,
max_render_steps: int = 2000,
cost_criteria: float = 1.0,
) -> None: # pragma: no cover
"""Render... | Render the environment for one episode.
Args:
num_episodes (int, optional): The number of episodes to render. Defaults to 1.
save_replay_path (str or None, optional): The path to save the replay video. Defaults to
None.
max_render_steps (int, optional): The m... | render | python | PKU-Alignment/omnisafe | omnisafe/evaluator.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/evaluator.py | Apache-2.0 |
def eval_policy( # pylint: disable=too-many-locals
self,
episode: int,
agent: ConstraintActorQCritic | MeanPolicy,
logger: Logger,
) -> None:
"""Rollout the environment with deterministic agent action.
Args:
episode (int): Number of episodes.
... | Rollout the environment with deterministic agent action.
Args:
episode (int): Number of episodes.
agent (ConstraintActorQCritic): Agent.
logger (Logger): Logger, to log ``EpRet``, ``EpCost``, ``EpLen``.
| eval_policy | python | PKU-Alignment/omnisafe | omnisafe/adapter/crabs_adapter.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/adapter/crabs_adapter.py | Apache-2.0 |
def rollout( # pylint: disable=too-many-locals
self,
rollout_step: int,
agent: ConstraintActorQCritic,
buffer: VectorOffPolicyBuffer,
logger: Logger,
use_rand_action: bool,
) -> None:
"""Rollout the environment and store the data in the buffer.
.. wa... | Rollout the environment and store the data in the buffer.
.. warning::
As OmniSafe uses :class:`AutoReset` wrapper, the environment will be reset automatically,
so the final observation will be stored in ``info['final_observation']``.
Args:
rollout_step (int): Numbe... | rollout | python | PKU-Alignment/omnisafe | omnisafe/adapter/crabs_adapter.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/adapter/crabs_adapter.py | Apache-2.0 |
def __init__(self, env_id: str, num_envs: int, seed: int, cfgs: Config) -> None:
"""Initialize an instance of :class:`EarlyTerminatedAdapter`."""
assert num_envs == 1, 'EarlyTerminatedAdapter only supports num_envs=1.'
super().__init__(env_id, num_envs, seed, cfgs)
self._cost_limit: fl... | Initialize an instance of :class:`EarlyTerminatedAdapter`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/adapter/early_terminated_adapter.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/adapter/early_terminated_adapter.py | Apache-2.0 |
def get_cost_from_obs_tensor(self, obs: torch.Tensor) -> torch.Tensor:
"""Get cost from tensor observation.
Args:
obs (torch.Tensor): The tensor version of observation.
"""
return (
self._env.get_cost_from_obs_tensor(obs)
if hasattr(self._env, 'get_co... | Get cost from tensor observation.
Args:
obs (torch.Tensor): The tensor version of observation.
| get_cost_from_obs_tensor | python | PKU-Alignment/omnisafe | omnisafe/adapter/modelbased_adapter.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/adapter/modelbased_adapter.py | Apache-2.0 |
def get_lidar_from_coordinate(self, obs: np.ndarray) -> torch.Tensor | None:
"""Get lidar from numpy coordinate.
Args:
obs (np.ndarray): The observation.
"""
return (
self._env.get_lidar_from_coordinate(obs)
if hasattr(self._env, 'get_lidar_from_coord... | Get lidar from numpy coordinate.
Args:
obs (np.ndarray): The observation.
| get_lidar_from_coordinate | python | PKU-Alignment/omnisafe | omnisafe/adapter/modelbased_adapter.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/adapter/modelbased_adapter.py | Apache-2.0 |
def rollout( # pylint: disable=too-many-arguments,too-many-locals
self,
current_step: int,
rollout_step: int,
use_actor_critic: bool,
act_func: Callable[[int, torch.Tensor], torch.Tensor],
store_data_func: Callable[
[
torch.Tensor,
... | Roll out the environment and store the data in the buffer.
Args:
current_step (int): Current training step.
rollout_step (int): Number of steps to roll out.
use_actor_critic (bool): Whether to use actor-critic.
act_func (Callable[[int, torch.Tensor], torch.Tensor... | rollout | python | PKU-Alignment/omnisafe | omnisafe/adapter/modelbased_adapter.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/adapter/modelbased_adapter.py | Apache-2.0 |
def _log_value(
self,
reward: torch.Tensor,
cost: torch.Tensor,
info: dict[str, Any],
) -> None:
"""Log value.
.. note::
OmniSafe uses :class:`RewardNormalizer` wrapper, so the original reward and cost will
be stored in ``info['original_reward... | Log value.
.. note::
OmniSafe uses :class:`RewardNormalizer` wrapper, so the original reward and cost will
be stored in ``info['original_reward']`` and ``info['original_cost']``.
Args:
reward (torch.Tensor): The immediate step reward.
cost (torch.Tensor)... | _log_value | python | PKU-Alignment/omnisafe | omnisafe/adapter/modelbased_adapter.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/adapter/modelbased_adapter.py | Apache-2.0 |
def _log_metrics(self, logger: Logger) -> None:
"""Log metrics.
Args:
logger (Logger): Logger, to log ``EpRet``, ``EpCost``, ``EpLen``.
"""
self._first_log = True
logger.store(
{
'Metrics/EpRet': self._ep_ret,
'Metrics/EpCo... | Log metrics.
Args:
logger (Logger): Logger, to log ``EpRet``, ``EpCost``, ``EpLen``.
| _log_metrics | python | PKU-Alignment/omnisafe | omnisafe/adapter/modelbased_adapter.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/adapter/modelbased_adapter.py | Apache-2.0 |
def reset(
self,
seed: int | None = None,
options: dict[str, Any] | None = None,
) -> tuple[torch.Tensor, dict[str, Any]]:
"""Reset the environment and returns an initial observation.
Args:
seed (int, optional): The random seed. Defaults to None.
opti... | Reset the environment and returns an initial observation.
Args:
seed (int, optional): The random seed. Defaults to None.
options (dict[str, Any], optional): The options for the environment. Defaults to None.
Returns:
observation: The initial observation of the space... | reset | python | PKU-Alignment/omnisafe | omnisafe/adapter/offline_adapter.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/adapter/offline_adapter.py | Apache-2.0 |
def evaluate(
self,
evaluate_epoisodes: int,
agent: Actor,
logger: Logger,
) -> None:
"""Evaluate the agent in the environment.
Args:
evaluate_epoisodes (int): the number of episodes for evaluation.
agent (Actor): the agent to be evaluated.
... | Evaluate the agent in the environment.
Args:
evaluate_epoisodes (int): the number of episodes for evaluation.
agent (Actor): the agent to be evaluated.
logger (Logger): the logger for logging the evaluation results.
| evaluate | python | PKU-Alignment/omnisafe | omnisafe/adapter/offline_adapter.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/adapter/offline_adapter.py | Apache-2.0 |
def eval_policy( # pylint: disable=too-many-locals
self,
episode: int,
agent: ConstraintActorQCritic,
logger: Logger,
) -> None:
"""Rollout the environment with deterministic agent action.
Args:
episode (int): Number of episodes.
agent (Const... | Rollout the environment with deterministic agent action.
Args:
episode (int): Number of episodes.
agent (ConstraintActorCritic): Agent.
logger (Logger): Logger, to log ``EpRet``, ``EpCost``, ``EpLen``.
| eval_policy | python | PKU-Alignment/omnisafe | omnisafe/adapter/offpolicy_adapter.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/adapter/offpolicy_adapter.py | Apache-2.0 |
def rollout( # pylint: disable=too-many-locals
self,
rollout_step: int,
agent: ConstraintActorQCritic,
buffer: VectorOffPolicyBuffer,
logger: Logger,
use_rand_action: bool,
) -> None:
"""Rollout the environment and store the data in the buffer.
.. wa... | Rollout the environment and store the data in the buffer.
.. warning::
As OmniSafe uses :class:`AutoReset` wrapper, the environment will be reset automatically,
so the final observation will be stored in ``info['final_observation']``.
Args:
rollout_step (int): Numbe... | rollout | python | PKU-Alignment/omnisafe | omnisafe/adapter/offpolicy_adapter.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/adapter/offpolicy_adapter.py | Apache-2.0 |
def _log_metrics(self, logger: Logger, idx: int) -> None:
"""Log metrics, including ``EpRet``, ``EpCost``, ``EpLen``.
Args:
logger (Logger): Logger, to log ``EpRet``, ``EpCost``, ``EpLen``.
idx (int): The index of the environment.
"""
if hasattr(self._env, 'spec_... | Log metrics, including ``EpRet``, ``EpCost``, ``EpLen``.
Args:
logger (Logger): Logger, to log ``EpRet``, ``EpCost``, ``EpLen``.
idx (int): The index of the environment.
| _log_metrics | python | PKU-Alignment/omnisafe | omnisafe/adapter/offpolicy_adapter.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/adapter/offpolicy_adapter.py | Apache-2.0 |
def _reset_log(self, idx: int | None = None) -> None:
"""Reset the episode return, episode cost and episode length.
Args:
idx (int or None, optional): The index of the environment. Defaults to None
(single environment).
"""
if idx is None:
self._e... | Reset the episode return, episode cost and episode length.
Args:
idx (int or None, optional): The index of the environment. Defaults to None
(single environment).
| _reset_log | python | PKU-Alignment/omnisafe | omnisafe/adapter/offpolicy_adapter.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/adapter/offpolicy_adapter.py | Apache-2.0 |
def __init__( # pylint: disable=too-many-arguments
self,
env_id: str,
num_envs: int,
seed: int,
cfgs: Config,
) -> None:
"""Initialize an instance of :class:`OnlineAdapter`."""
assert env_id in support_envs(), f'Env {env_id} is not supported.'
self._... | Initialize an instance of :class:`OnlineAdapter`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/adapter/online_adapter.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/adapter/online_adapter.py | Apache-2.0 |
def _wrapper_eval(
self,
obs_normalize: bool = True,
) -> None:
"""Wrapper the environment for evaluation.
Args:
obs_normalize (bool, optional): Whether to normalize the observation. Defaults to True.
reward_normalize (bool, optional): Whether to normalize th... | Wrapper the environment for evaluation.
Args:
obs_normalize (bool, optional): Whether to normalize the observation. Defaults to True.
reward_normalize (bool, optional): Whether to normalize the reward. Defaults to True.
cost_normalize (bool, optional): Whether to normalize t... | _wrapper_eval | python | PKU-Alignment/omnisafe | omnisafe/adapter/online_adapter.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/adapter/online_adapter.py | Apache-2.0 |
def __init__( # pylint: disable=too-many-arguments
self,
env_id: str,
num_envs: int,
seed: int,
cfgs: Config,
) -> None:
"""Initialize an instance of :class:`OnPolicyAdapter`."""
super().__init__(env_id, num_envs, seed, cfgs)
self._reset_log() | Initialize an instance of :class:`OnPolicyAdapter`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/adapter/onpolicy_adapter.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/adapter/onpolicy_adapter.py | Apache-2.0 |
def rollout( # pylint: disable=too-many-locals
self,
steps_per_epoch: int,
agent: ConstraintActorCritic,
buffer: VectorOnPolicyBuffer,
logger: Logger,
) -> None:
"""Rollout the environment and store the data in the buffer.
.. warning::
As OmniSaf... | Rollout the environment and store the data in the buffer.
.. warning::
As OmniSafe uses :class:`AutoReset` wrapper, the environment will be reset automatically,
so the final observation will be stored in ``info['final_observation']``.
Args:
steps_per_epoch (int): Nu... | rollout | python | PKU-Alignment/omnisafe | omnisafe/adapter/onpolicy_adapter.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/adapter/onpolicy_adapter.py | Apache-2.0 |
def __init__(self, env_id: str, num_envs: int, seed: int, cfgs: Config) -> None:
"""Initialize an instance of :class:`SauteAdapter`."""
super().__init__(env_id, num_envs, seed, cfgs)
self._safety_budget: torch.Tensor = (
self._cfgs.algo_cfgs.safety_budget
* (1 - self._cf... | Initialize an instance of :class:`SauteAdapter`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/adapter/saute_adapter.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/adapter/saute_adapter.py | Apache-2.0 |
def _wrapper(
self,
obs_normalize: bool = True,
reward_normalize: bool = False,
cost_normalize: bool = False,
) -> None:
"""Wrapper the environment.
.. warning::
The reward or cost normalization is not supported in Saute Adapter.
Args:
... | Wrapper the environment.
.. warning::
The reward or cost normalization is not supported in Saute Adapter.
Args:
obs_normalize (bool, optional): Whether to normalize the observation. Defaults to True.
reward_normalize (bool, optional): Whether to normalize the reward... | _wrapper | python | PKU-Alignment/omnisafe | omnisafe/adapter/saute_adapter.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/adapter/saute_adapter.py | Apache-2.0 |
def reset(
self,
seed: int | None = None,
options: dict[str, Any] | None = None,
) -> tuple[torch.Tensor, dict[str, Any]]:
"""Reset the environment and returns an initial observation.
.. note::
Additionally, the safety observation will be reset.
Args:
... | Reset the environment and returns an initial observation.
.. note::
Additionally, the safety observation will be reset.
Args:
seed (int, optional): The random seed. Defaults to None.
options (dict[str, Any], optional): The options for the environment. Defaults to No... | reset | python | PKU-Alignment/omnisafe | omnisafe/adapter/saute_adapter.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/adapter/saute_adapter.py | Apache-2.0 |
def _safety_step(self, cost: torch.Tensor) -> None:
"""Update the safety observation.
Args:
cost (torch.Tensor): The cost of the current step.
"""
self._safety_obs -= cost.unsqueeze(-1) / self._safety_budget
self._safety_obs /= self._cfgs.algo_cfgs.saute_gamma | Update the safety observation.
Args:
cost (torch.Tensor): The cost of the current step.
| _safety_step | python | PKU-Alignment/omnisafe | omnisafe/adapter/saute_adapter.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/adapter/saute_adapter.py | Apache-2.0 |
def _safety_reward(self, reward: torch.Tensor) -> torch.Tensor:
"""Update the reward with the safety observation.
.. note::
If the safety observation is greater than 0, the reward will be the original reward.
Otherwise, the reward will be the unsafe reward.
Args:
... | Update the reward with the safety observation.
.. note::
If the safety observation is greater than 0, the reward will be the original reward.
Otherwise, the reward will be the unsafe reward.
Args:
reward (torch.Tensor): The reward of the current step.
Retur... | _safety_reward | python | PKU-Alignment/omnisafe | omnisafe/adapter/saute_adapter.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/adapter/saute_adapter.py | Apache-2.0 |
def _log_value(
self,
reward: torch.Tensor,
cost: torch.Tensor,
info: dict[str, Any],
) -> None:
"""Log value.
.. note::
Additionally, the safety observation will be updated and logged.
Args:
reward (torch.Tensor): The immediate step ... | Log value.
.. note::
Additionally, the safety observation will be updated and logged.
Args:
reward (torch.Tensor): The immediate step reward.
cost (torch.Tensor): The immediate step cost.
info (dict[str, Any]): Some information logged by the environment.... | _log_value | python | PKU-Alignment/omnisafe | omnisafe/adapter/saute_adapter.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/adapter/saute_adapter.py | Apache-2.0 |
def _reset_log(self, idx: int | None = None) -> None:
"""Reset the episode return, episode cost, episode length and episode budget.
Args:
idx (int or None, optional): The index of the environment. Defaults to None
(single environment).
"""
super()._reset_log(... | Reset the episode return, episode cost, episode length and episode budget.
Args:
idx (int or None, optional): The index of the environment. Defaults to None
(single environment).
| _reset_log | python | PKU-Alignment/omnisafe | omnisafe/adapter/saute_adapter.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/adapter/saute_adapter.py | Apache-2.0 |
def __init__(self, env_id: str, num_envs: int, seed: int, cfgs: Config) -> None:
"""Initialize an instance of :class:`SimmerAdapter`."""
super(OnPolicyAdapter, self).__init__(env_id, num_envs, seed, cfgs)
self._num_envs: int = num_envs
self._safety_budget: torch.Tensor = (
s... | Initialize an instance of :class:`SimmerAdapter`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/adapter/simmer_adapter.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/adapter/simmer_adapter.py | Apache-2.0 |
def reset(
self,
seed: int | None = None,
options: dict[str, Any] | None = None,
) -> tuple[torch.Tensor, dict[str, Any]]:
"""Reset the environment and returns an initial observation.
.. note::
Additionally, the safety observation will be reset. And the safety bu... | Reset the environment and returns an initial observation.
.. note::
Additionally, the safety observation will be reset. And the safety budget will be reset
to the value of current ``rel_safety_budget``.
Args:
seed (int, optional): The random seed. Defaults to None.
... | reset | python | PKU-Alignment/omnisafe | omnisafe/adapter/simmer_adapter.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/adapter/simmer_adapter.py | Apache-2.0 |
def control_budget(self, ep_costs: torch.Tensor) -> None:
"""Control the safety budget.
Args:
ep_costs (torch.Tensor): The episode costs.
"""
ep_costs = (
ep_costs
* (1 - self._cfgs.algo_cfgs.saute_gamma**self._cfgs.algo_cfgs.max_ep_len)
/... | Control the safety budget.
Args:
ep_costs (torch.Tensor): The episode costs.
| control_budget | python | PKU-Alignment/omnisafe | omnisafe/adapter/simmer_adapter.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/adapter/simmer_adapter.py | Apache-2.0 |
def __init__(
self,
algo: str,
env_id: str,
train_terminal_cfgs: dict[str, Any] | None = None,
custom_cfgs: dict[str, Any] | None = None,
) -> None:
"""Initialize an instance of :class:`AlgoWrapper`."""
self.algo: str = algo
self.env_id: str = env_id
... | Initialize an instance of :class:`AlgoWrapper`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/algorithms/algo_wrapper.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/algo_wrapper.py | Apache-2.0 |
def _init_config(self) -> Config:
"""Initialize config.
Initialize the configurations for the algorithm, following the order of default
configurations, custom configurations, and terminal configurations.
Returns:
The configurations for the algorithm.
Raises:
... | Initialize config.
Initialize the configurations for the algorithm, following the order of default
configurations, custom configurations, and terminal configurations.
Returns:
The configurations for the algorithm.
Raises:
AssertionError: If the algorithm name i... | _init_config | python | PKU-Alignment/omnisafe | omnisafe/algorithms/algo_wrapper.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/algo_wrapper.py | Apache-2.0 |
def learn(self) -> tuple[float, float, float]:
"""Agent learning.
Returns:
ep_ret: The episode return of the final episode.
ep_cost: The episode cost of the final episode.
ep_len: The episode length of the final episode.
"""
ep_ret, ep_cost, ep_len = ... | Agent learning.
Returns:
ep_ret: The episode return of the final episode.
ep_cost: The episode cost of the final episode.
ep_len: The episode length of the final episode.
| learn | python | PKU-Alignment/omnisafe | omnisafe/algorithms/algo_wrapper.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/algo_wrapper.py | Apache-2.0 |
def plot(self, smooth: int = 1) -> None:
"""Plot the training curve.
Args:
smooth (int, optional): window size, for smoothing the curve. Defaults to 1.
Raises:
AssertionError: If the :meth:`learn` method has not been called.
"""
assert self._plotter is n... | Plot the training curve.
Args:
smooth (int, optional): window size, for smoothing the curve. Defaults to 1.
Raises:
AssertionError: If the :meth:`learn` method has not been called.
| plot | python | PKU-Alignment/omnisafe | omnisafe/algorithms/algo_wrapper.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/algo_wrapper.py | Apache-2.0 |
def evaluate(self, num_episodes: int = 10, cost_criteria: float = 1.0) -> None:
"""Agent Evaluation.
Args:
num_episodes (int, optional): number of episodes to evaluate. Defaults to 10.
cost_criteria (float, optional): the cost criteria to evaluate. Defaults to 1.0.
Rais... | Agent Evaluation.
Args:
num_episodes (int, optional): number of episodes to evaluate. Defaults to 10.
cost_criteria (float, optional): the cost criteria to evaluate. Defaults to 1.0.
Raises:
AssertionError: If the :meth:`learn` method has not been called.
| evaluate | python | PKU-Alignment/omnisafe | omnisafe/algorithms/algo_wrapper.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/algo_wrapper.py | Apache-2.0 |
def render(
self,
num_episodes: int = 10,
render_mode: str = 'rgb_array',
camera_name: str = 'track',
width: int = 256,
height: int = 256,
) -> None:
"""Evaluate and render some episodes.
Args:
num_episodes (int, optional): The number of e... | Evaluate and render some episodes.
Args:
num_episodes (int, optional): The number of episodes to render. Defaults to 10.
render_mode (str, optional): The render mode, can be 'rgb_array', 'depth_array' or
'human'. Defaults to 'rgb_array'.
camera_name (str, opt... | render | python | PKU-Alignment/omnisafe | omnisafe/algorithms/algo_wrapper.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/algo_wrapper.py | Apache-2.0 |
def __init__(self, name: str) -> None:
"""Initialize an instance of :class:`Registry`."""
self._name: str = name
self._module_dict: dict[str, type] = {} | Initialize an instance of :class:`Registry`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/algorithms/registry.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/registry.py | Apache-2.0 |
def get(self, key: str) -> Any:
"""Get the class that has been registered under the given key."""
res = self._module_dict.get(key)
if res is None:
raise KeyError(f'{key} is not in the {self.name} registry')
return res | Get the class that has been registered under the given key. | get | python | PKU-Alignment/omnisafe | omnisafe/algorithms/registry.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/registry.py | Apache-2.0 |
def _register_module(self, module_class: type) -> None:
"""Register a module.
Args:
module_class (type): Module to be registered.
"""
if not inspect.isclass(module_class):
raise TypeError(f'module must be a class, but got {type(module_class)}')
module_nam... | Register a module.
Args:
module_class (type): Module to be registered.
| _register_module | python | PKU-Alignment/omnisafe | omnisafe/algorithms/registry.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/registry.py | Apache-2.0 |
def _init_model(self) -> None:
"""Initialize the dynamics model and the planner.
CAP uses following models:
- dynamics model: to predict the next state and the cost.
- lagrange multiplier: to trade off between the cost and the reward.
- planner: to generate the action.
... | Initialize the dynamics model and the planner.
CAP uses following models:
- dynamics model: to predict the next state and the cost.
- lagrange multiplier: to trade off between the cost and the reward.
- planner: to generate the action.
| _init_model | python | PKU-Alignment/omnisafe | omnisafe/algorithms/model_based/cap_pets.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/cap_pets.py | Apache-2.0 |
def _init_log(self) -> None:
"""Initialize the logger.
+----------------------------+-------------------------------+
| Things to log | Description |
+============================+===============================+
| Plan/feasible_num | The ... | Initialize the logger.
+----------------------------+-------------------------------+
| Things to log | Description |
+============================+===============================+
| Plan/feasible_num | The number of feasible plans. |
+---... | _init_log | python | PKU-Alignment/omnisafe | omnisafe/algorithms/model_based/cap_pets.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/cap_pets.py | Apache-2.0 |
def _init_model(self) -> None:
"""Initialize the dynamics model and the planner.
CCEPETS uses following models:
- dynamics model: to predict the next state and the cost.
- planner: to generate the action.
"""
self._dynamics_state_space: OmnisafeSpace = (
sel... | Initialize the dynamics model and the planner.
CCEPETS uses following models:
- dynamics model: to predict the next state and the cost.
- planner: to generate the action.
| _init_model | python | PKU-Alignment/omnisafe | omnisafe/algorithms/model_based/cce_pets.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/cce_pets.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.