simworld.utils package

Submodules

simworld.utils.bbox_utils module

Utility module for bounding box calculations and operations.

This module provides functionality for checking intersections between rotated bounding boxes and other geometric operations without external dependencies.

class simworld.utils.bbox_utils.BboxUtils

Bases: object

Utility class for bounding box operations.

Provides static methods for geometric operations on bounding boxes, particularly for detecting collisions between rotated rectangles.

static bbox_overlap(a: Bounds, b: Bounds) bool

Check if two rotated bounding boxes overlap without using shapely.

Args:

a: First bounding box. b: Second bounding box.

Returns:

True if the bounding boxes overlap, False otherwise.

simworld.utils.data_exporter module

Module for exporting city data to various file formats.

This module provides functionality to export city data including roads, buildings, and elements to JSON files for visualization and integration with external tools.

class simworld.utils.data_exporter.DataExporter(city_generator)

Bases: object

Manages the export of city data to various file formats.

This class provides methods to export roads, buildings, and other city elements to structured data formats for external use.

convert_layout_to_world(output_dir: str, buildings_data, roads_data, elements_data)

Convert the city layout to a world format compatible with the simulation engine.

Args:

output_dir: Directory path where the world JSON file will be written. buildings_data: Dictionary containing building data. roads_data: Dictionary containing road data. elements_data: Dictionary containing element data.

export_building_data() Dict

Export all building data.

Returns:

Dictionary containing building data.

export_element_data() Dict

Export all element data.

Returns:

Dictionary containing element data.

export_road_data() Dict

Export all road data.

Returns:

Dictionary containing road segment data.

export_routes_data() Dict

Export all route data.

Returns:

Dictionary containing route data.

export_to_json(output_dir: str)

Export all data to JSON files.

Args:

output_dir: Directory path where the JSON files will be written.

simworld.utils.data_importer module

This module imports the city data and reconstruct the city generator.

class simworld.utils.data_importer.DataImporter(config: Config)

Bases: object

The DataImporter class imports city data based on the configuration.

import_city_data(input_dir: str | None = None)

Rebuild the city_generator with the provided json file and print the result.

Returns:

city_generator: The city generator object containing city data.

import_from_file(filepath: str)

Rebuild the city_generator with the provided json file.

Args:

filepath: The json file that contain the city data.

simworld.utils.get_bbox module

Get the bounding box of the selected actor and save it to a JSON file.

simworld.utils.get_bbox.main(file_path='<path to your bounding_boxes.json>')

Capture bounding boxes for selected actors and write them to JSON.

simworld.utils.load_json module

This module provides functions to load JSON files from a default location or a specific path.

simworld.utils.load_json.load_default_json(file_name: str, default_package: str = 'simworld.data')

Load a JSON file from the default location.

Args:

file_name: The name of the JSON file to load. default_package: The package to load the JSON file from.

Returns:

The JSON data from the file.

simworld.utils.load_json.load_json(file_path: str)

Load a JSON file from a specific path or the default location.

Args:

file_path: The path to the JSON file to load.

Returns:

The JSON data from the file.

simworld.utils.logger module

Logger utility module for logging messages with configurable logging levels and handlers.

class simworld.utils.logger.Logger

Bases: object

Singleton logger class for the simulation application.

This class provides a centralized logging mechanism with configurable options for enabling/disabling logging and console output.

classmethod configure(logging_enabled=True, log_to_console=True, log_to_file=False)

Configure global logging settings.

Args:

logging_enabled: Whether logging is enabled globally. log_to_console: Whether to output logs to console. log_to_file: Whether to output logs to file.

static get_logger(name=None)

Get a logger instance, optionally as a child logger with the specified name.

Args:

name: Optional name for child logger.

Returns:

A configured logger instance.

property logger

Delay creating logger instance.

simworld.utils.math_utils module

Mathematical utility functions for vector and geometric operations.

class simworld.utils.math_utils.MathUtils

Bases: object

Collection of mathematical utility functions for geometric operations.

static add_points(p1: Point, p2: Point) Point

Add two points together (vector addition).

Args:

p1: First point. p2: Second point.

Returns:

A new Point representing p1 + p2.

static angle_between(a: Point, b: Point) float

Calculate the angle between two vectors in degrees.

Args:

a: First vector. b: Second vector.

Returns:

The angle between vectors a and b in degrees.

static angle_difference(angle1: float, angle2: float) float

Calculate the smallest angle difference between two angles.

Args:

angle1: First angle in degrees. angle2: Second angle in degrees.

Returns:

The smallest angle difference between angle1 and angle2 (0-180).

static cross_product(a: Point, b: Point) float

Calculate the 2D cross product of two points.

Args:

a: First point. b: Second point.

Returns:

The cross product a × b.

static do_line_segments_intersect(a: Point, b: Point, p: Point, d: Point, buffer: float = 0.001) Tuple[Point, float] | None

Determine if two line segments intersect and find the intersection point.

Args:

a: First point of first segment. b: Second point of first segment. p: First point of second segment. d: Second point of second segment. buffer: Small buffer to avoid detecting intersections too close to endpoints.

Returns:

If segments intersect, returns (intersection_point, parameter_value). If segments don’t intersect, returns None.

static dot_product(a: Point, b: Point) float

Calculate the dot product of two points.

Args:

a: First point. b: Second point.

Returns:

The dot product a · b.

static get_direction_description_for_points(point_a: Point, point_b: Point) str

Get the relative direction description for two points.

point_a is the pivot point, point_b is the target point.

Args:

point_a: The reference (pivot) point. point_b: The target point.

Returns:

A string describing the direction (‘North’, ‘SouthEast’, etc.).

static interpolate_point(start: Point, end: Point, t: float) Point

Interpolate a point between two points.

Args:

start: Starting point. end: Ending point. t: Interpolation parameter (0-1).

Returns:

A new Point representing the interpolated position.

static length(a: Point, b: Point) float

Calculate the Euclidean distance between two points.

Args:

a: First point. b: Second point.

Returns:

The distance between points a and b.

static length_v(a: Point) float

Calculate the magnitude (length) of a vector.

Args:

a: The point (vector) to calculate magnitude for.

Returns:

The magnitude of the vector.

static min_degree_difference(val1: float, val2: float) float

Calculate the minimum difference between two angles in degrees.

Args:

val1: First angle in degrees. val2: Second angle in degrees.

Returns:

The minimum difference between the angles (always < 180).

static point_segment_distance(point: Point, segment: Segment) float

Calculate the minimum distance from a point to a line segment.

Args:

point: The point to calculate distance from. segment: The line segment to calculate distance to.

Returns:

The minimum distance from the point to the segment.

static rotate_point(center: Point, point: Point, angle: float) Point

Rotate a point around a center by a given angle in degrees.

Args:

center: The center point to rotate around. point: The point to rotate. angle: The rotation angle in degrees.

Returns:

A new Point representing the rotated point.

static subtract_points(p1: Point, p2: Point) Point

Subtract p2 from p1 (vector subtraction).

Args:

p1: First point. p2: Second point to subtract.

Returns:

A new Point representing p1 - p2.

simworld.utils.priority_queue module

Priority queue implementation for managing segments.

This module provides a priority queue implementation specifically designed for managing segments in the simulation. It supports basic queue operations with priority-based dequeuing.

class simworld.utils.priority_queue.PriorityQueue

Bases: object

A priority queue implementation for managing segments.

This class implements a priority queue where segments are ordered based on their t value. It provides standard queue operations with priority-based dequeuing.

dequeue() Segment | None

Get the segment with the minimum t value.

Returns:

The segment with the minimum t value, or None if the queue is empty.

empty() bool

Check if the queue is empty.

Returns:

True if the queue is empty, False otherwise.

enqueue(segment: Segment)

Add a segment to the queue.

Args:

segment: The segment to add to the queue.

property size

Get the number of elements in the queue.

Returns:

The number of elements in the queue.

simworld.utils.quadtree module

Quadtree implementation for efficient spatial partitioning and querying.

class simworld.utils.quadtree.QuadTree(bounds: Bounds, max_objects=10, max_levels=4, level=0)

Bases: Generic[T]

Quadtree data structure for efficient spatial partitioning and querying.

A quadtree recursively divides space into four quadrants to efficiently store and query spatial data.

Attributes:

bounds: The spatial bounds of this quadtree node. max_objects: Maximum number of objects before splitting. max_levels: Maximum depth of the quadtree. level: Current depth level of this node. objects: List of object bounds in this node. items: List of items corresponding to the bounds. nodes: Child nodes of this quadtree.

clear()

Clear the quadtree, removing all items and resetting to initial state.

get_relevant_nodes(rect: Bounds) List[QuadTree[T]]

Get the child nodes that intersect with the given rectangle.

Args:

rect: The bounding rectangle to test intersection with.

Returns:

List of child nodes that intersect with the rectangle.

insert(rect: Bounds, item: T)

Insert an item with its bounds into the quadtree.

Args:

rect: The bounding rectangle of the item. item: The item to insert.

remove(bounds: Bounds, item: T) bool

Remove an item and its bounds from the quadtree.

Args:

bounds: The bounding rectangle of the item. item: The item to remove.

Returns:

True if item was found and removed, False otherwise.

retrieve(rect: Bounds) List[T]

Retrieve all items that might intersect with the given rectangle.

Args:

rect: The bounding rectangle to query.

Returns:

List of items that might intersect with the rectangle.

retrieve_exact(query_rect: Bounds) List[T]

Retrieve all items that have an exact intersection with the given rectangle.

Args:

query_rect: The bounding rectangle to query.

Returns:

List of items that intersect with the rectangle.

split()

Split this node into four child nodes.

Divides the current node into four equal quadrants and redistributes the contained objects among them.

simworld.utils.road_utils module

Road utilities module, providing functions for handling road segments and points.

class simworld.utils.road_utils.RoadUtils

Bases: object

Provide static utility methods for handling road networks.

static create_bounds_for_segment(segment: Segment) Bounds

Create bounds object for a segment (used for quadtree).

Args:

segment: The road segment to create bounds for

Returns:

A Bounds object representing the area around the segment

static find_nearby_endpoint(point: Point, segments: List[Segment], queue_elements: List[Segment], merge_distance: float) Point | None

Find existing road endpoint near the given point.

Args:

point: The point to check against segments: List of existing road segments queue_elements: Queue of segments being processed merge_distance: Maximum distance to consider for merging

Returns:

The closest endpoint if found within merge distance, None otherwise

static get_current_angles(segment: Segment, segments: List[Segment], queue_elements: List[Segment], merge_distance: float) List[float]

Get all current angles at the segment end point.

Args:

segment: The segment to check angles from segments: List of existing road segments queue_elements: Queue of segments being processed merge_distance: Maximum distance to consider for angle calculation

Returns:

List of angles in degrees from the segment end point

static merge_point_if_close(segment: Segment, point_type: str, segments: List[Segment], merge_distance: float) bool

Merge a segment’s endpoint with nearby existing points.

Args:

segment: The segment to check for merging point_type: ‘start’ or ‘end’ segments: List of existing road segments merge_distance: Maximum distance to consider for merging

Returns:

True if merged, False otherwise

simworld.utils.traffic_utils module

Utility functions for traffic simulation and route generation.

simworld.utils.traffic_utils.bezier(start: Vector, end: Vector, control_point: Vector, t: float) Vector

Calculate a point on a quadratic Bezier curve.

Args:

start: Starting point of the curve. end: Ending point of the curve. control_point: Control point that influences the curve shape. t: Parameter value between 0 and 1 representing position along the curve.

Returns:

A Vector representing the point on the Bezier curve at parameter t.

simworld.utils.traffic_utils.cal_waypoints(start: Vector, end: Vector, gap_between_waypoints: float) list[simworld.utils.vector.Vector]

Add waypoints between start and end at regular intervals.

Args:

start: Starting point. end: Ending point. gap_between_waypoints: Distance between consecutive waypoints.

Returns:

List of waypoints between start and end (including end point).

simworld.utils.traffic_utils.extend_control_point(start: Vector, end: Vector, intersection: Vector, extension_factor: float = 0.1) Vector

Extend the control point from the intersection for smoother curves.

Args:

start: Starting point of the curve. end: Ending point of the curve. intersection: Intersection point (typically junction center). extension_factor: Extension factor, larger values produce smoother curves.

Returns:

The extended control point as a Vector.

simworld.utils.traffic_utils.get_bezier_points(start: Vector, end: Vector, control_point: Vector, num_points: int) list[simworld.utils.vector.Vector]

Generate waypoints on a quadratic Bezier curve.

Args:

start: Starting point of the curve. end: Ending point of the curve. control_point: Control point that influences the curve shape. num_points: Number of points to sample along the curve.

Returns:

List of waypoints on the Bezier curve (excluding the start point).

simworld.utils.vector module

Two-dimensional vector utilities module, providing Vector class and related operations.

class simworld.utils.vector.Vector(x, y=None)

Bases: object

Two-dimensional vector class.

Used for representing and manipulating 2D vectors, providing basic vector operations.

Attributes:

x: X coordinate. y: Y coordinate.

cross(other: Vector) float

Calculate cross product with another vector.

Args:

other: Another vector.

Returns:

Cross product of the two vectors.

distance(other: Vector) float

Calculate distance to another vector.

Args:

other: Another vector.

Returns:

Euclidean distance between the two vectors.

dot(other: Vector) float

Calculate dot product with another vector.

Args:

other: Another vector.

Returns:

Dot product of the two vectors.

length() float

Calculate length of the vector.

Returns:

Length of the vector.

normalize() Vector

Normalize the vector.

Returns:

Normalized vector.

x: float
y: float

simworld.utils.video_recorder module

Utilities for recording simulation videos and logging metadata.

class simworld.utils.video_recorder.VideoRecorder(communicator, humanoid, output_dir='.', video_name='output.mp4', resolution=(1440, 720), fps=25.0, frame_num=500, move_pattern=None, camera_mode='lit')

Bases: object

Record frames from a humanoid-mounted camera and export video/CSV logs.

record()

Run the recording loop and persist video and CSV logs.

Returns

str

Path to the saved video file.

save_csv(camera_position, humanoid_actions)

Save camera pose timeline and humanoid actions into CSV files.

save_video(images)

Save frames to an MP4 file using OpenCV.

Module contents

Utility modules and helpers for the SimWorld package.

This package contains various utility functions for mathematical operations, vector manipulation, data export, and other common operations needed throughout the simulation.