tactics2d.map
Map module.
tactics2d.map.element
Element module.
Node
This class implements the map element Node.
The add operation of the node is defined as the addition of the coordinates of the node.
The subtract operation of the node is defined as the subtraction of the coordinates of the node.
Attributes:
-
id_(str) –The id of the node.
-
x(float) –The x coordinate of the node.
-
y(float) –The y coordinate of the node.
-
location(Point) –The location of the node expressed in geometry format. This attribute is read-only.
__init__(id_, x, y)
Initialize an instance of this class.
Parameters:
-
id_(str) –The id of the node.
-
x(float) –The x coordinate of the node.
-
y(float) –The y coordinate of the node.
RoadLine
This class implements the map element LineString.
Attributes:
-
id_(str) –The unique identifier of the roadline.
-
geometry(LineString) –The geometry information of the roadline.
-
type_(str) –The type of the roadline. Defaults to "virtual".
-
subtype(str) –The subtype of the line. Defaults to None.
-
color(Any) –The color of the line. If not specified, the color will be assigned based on the rendering template later. Defaults to None.
-
width(float) –The width of the line in metres. Defaults to None.
-
height(float) –The height of line in metres. Defaults to None.
-
lane_change(Tuple[bool, bool]) –Whether a vehicle can cross the line from left to right and from right to left. Defaults to None.
-
temporary(bool) –Whether the roadline is temporary. Defaults to False.
-
custom_tags(dict) –Custom tags of the roadline. Defaults to None.
-
head(Point) –The head point of the roadline. Read-only.
-
end(Point) –The end point of the roadline. Read-only.
-
shape(list) –The shape of the roadline. Read-only.
__init__(id_, geometry, type_='virtual', subtype=None, color=None, width=None, height=None, lane_change=None, temporary=False, custom_tags=None)
Initialize an instance of RoadLine.
Parameters:
-
id_(str) –The unique identifier of the roadline.
-
geometry(LineString) –The shape of the line expressed in geometry format.
-
type_(str, default:'virtual') –The type of the roadline.
-
subtype(str, default:None) –The subtype of the line.
-
color(tuple, default:None) –The color of the line. If not specified, the color will be assigned based on the rendering template later.
-
width(float, default:None) –The width of the line in metres.
-
height(float, default:None) –The height of the line in metres.
-
lane_change(Tuple[bool, bool], default:None) –Whether a vehicle can cross from left to right and from right to left.
-
temporary(bool, default:False) –Whether the roadline is temporary.
-
custom_tags(dict, default:None) –Custom tags of the roadline.
Lane
This class implements the map element Lane
Reference
Attributes:
-
id_(str) –The unique identifier of the lane.
-
left_side(LineString) –The left side of the lane.
-
right_side(LineString) –The right side of the lane.
-
line_ids(dict) –The ids of the roadline components. The dictionary has two keys:
leftandright. Defaults to dict(left=[], right=[]). -
regulatory_ids(set) –The ids of the regulations that apply to the lane. Defaults to set().
-
type_(str) –The type of the lane. The default value is
"lanelet". -
subtype(str) –The subtype of the lane. Defaults to None.
-
color(Any) –The color of the area. If not specified, the color will be assigned based on the rendering template later. Defaults to None.
-
location(str) –The location of the lane (urban, nonurban, etc.). Defaults to None.
-
inferred_participants(list) –he allowing type of traffic participants that can pass the area. If not specified, the area is not restricted to any type of traffic participants. Defaults to None.
-
speed_limit(float) –The speed limit in this area The unit is
m/s. Defaults to None. -
speed_limit_mandatory(bool) –Whether the speed limit is mandatory or not. Defaults to True.
-
custom_tags(dict) –The custom tags of the area. Defaults to None.
-
custom_tags(dict) –The custom tags of the lane. Defaults to None.
-
predecessors(set) –The ids of the available lanes before entering the current lane.
-
successors(set) –The ids of the available lanes after exiting the current lane.
-
left_neighbors(set) –The ids of the lanes that is adjacent to the left side of the current lane and in the same direction.
-
right_neighbors(set) –The ids of the lanes that is adjacent to the right side of the current lane and in the same direction.
-
starts(list) –The start points of the lane.
-
ends(list) –The end points of the lane.
-
geometry(LinearRing) –The geometry representation of the lane. This attribute will be automatically obtained during the initialization if there is no None in left_side and right_side.
-
shape(list) –The shape of the lane. This attribute is read-only.
__init__(id_, left_side=None, right_side=None, geometry=None, line_ids=dict(left=[], right=[]), regulatory_ids=set(), type_='lanelet', subtype=None, color=None, location=None, inferred_participants=None, speed_limit=None, speed_limit_unit='km/h', speed_limit_mandatory=True, custom_tags=None)
Initialize an instance of this class.
Parameters:
-
id_(str) –The unique identifier of the lane.
-
left_side(LineString, default:None) –The left side of the lane. Defaults to None.
-
right_side(LineString, default:None) –The right side of the lane. Defaults to None.
-
geometry(LinearRing, default:None) –The geometry of the lane. This parameter only takes effect when the
left_sideorright_sideis None. Defaults to None. -
line_ids(set, default:dict(left=[], right=[])) –The ids of the lines that make up the lane.
-
regulatory_ids(set, default:set()) –The ids of the regulations that apply to the lane.
-
type_(str, default:'lanelet') –The type of the lane.
-
subtype(str, default:None) –The subtype of the lane. Defaults to None.
-
color(Any, default:None) –The color of the lane. If not specified, the color will be assigned based on the rendering template later. Defaults to None.
-
location(str, default:None) –The location of the lane (urban, nonurban, etc.). Defaults to None.
-
inferred_participants(list, default:None) –The allowing type of traffic participants that can pass the lane. If not specified, the lane is not restricted to any type of traffic participants. Defaults to None.
-
speed_limit(float, default:None) –The speed limit in this lane. Defaults to None.
-
speed_limit_unit(str, default:'km/h') –The unit of speed limit in this lane. The valid units are
km/h,mi/h, andm/s. Defaults to "km/h". The speed limit will be automatically converted tom/swhen initializing the instance. If the unit is invalid, the speed limit will be set to None. -
speed_limit_mandatory(bool, default:True) –Whether the speed limit is mandatory or not.
-
custom_tags(dict, default:None) –The custom tags of the lane. Defaults to None.
add_related_lane(id_, relationship)
Add a related lane's id to the corresponding list
Parameters:
-
id_(str) –The related lane's id
-
relationship(LaneRelationship) –The relationship of the lanes. The possible values are 1/
PREDECESSOR, 2/SUCCESSOR, 3/LEFT_NEIGHBOR, and 4/RIGHT_NEIGHBOR.
centerline()
Return the lane centerline if it can be obtained.
get_width(samples=5, default=None)
Estimate lane width by sampling distances between left and right boundaries.
is_related(id_)
Check if a given lane is related to the lane
Parameters:
-
id_(str) –The given lane's id.
project_point(point)
Project a point onto the lane centerline.
Returns:
-
LaneProjection(Optional[LaneProjection]) –sis the distance along the centerline,dis -
Optional[LaneProjection]–the signed lateral offset, and
distanceisabs(d).
Area
This class implements the Area
Reference
Attributes:
-
id_(str) –The unique identifier of the area.
-
geometry(Polygon) –The geometry information of the area.
-
line_ids(dict) –The ids of the lines that circle this area. Defaults to dict(inner=[], outer=[]).
-
regulatory_ids(set) –The ids of the regulations that apply to the area. Defaults to set().
-
type_(str) –The type of the area. The default value is "multipolygon".
-
subtype(str) –The subtype of the area. Defaults to None.
-
color(Any) –The color of the area. If not specified, the color will be assigned based on the rendering template later. Defaults to None.
-
location(str) –The location of the area (urban, nonurban, etc.). Defaults to None.
-
inferred_participants(list) –The allowing type of traffic participants that can pass the area. If not specified, the area is not restricted to any type of traffic participants. Defaults to None.
-
speed_limit(float) –The speed limit in this area The unit is
m/s. Defaults to None. -
speed_limit_mandatory(bool) –Whether the speed limit is mandatory or not. Defaults to True.
-
custom_tags(dict) –The custom tags of the lane. Defaults to None.
-
shape(List[list, list]) –The shape of the area. The first list contains the outer shape, and the second list contains the inner shapes. Defaults to None. This attribute is read-only.
__init__(id_, geometry, line_ids=dict(inner=[], outer=[]), regulatory_ids=set(), type_='multipolygon', subtype=None, color=None, location=None, inferred_participants=None, speed_limit=None, speed_limit_unit='km/h', speed_limit_mandatory=True, custom_tags=None)
Initialize an instance of this class.
Parameters:
-
id_(str) –The unique identifier of the area.
-
geometry(Polygon) –The geometry shape of the area.
-
line_ids(dict, default:dict(inner=[], outer=[])) –The ids of the lines that circle this area.
-
regulatory_ids(set, default:set()) –The ids of the regulations that apply to the area.
-
type_(str, default:'multipolygon') –The type of the area.
-
subtype(str, default:None) –The subtype of the area.
-
color(Any, default:None) –The color of the area. If not specified, the color will be assigned based on the rendering template later.
-
location(str, default:None) –The location of the area (urban, nonurban, etc.).
-
inferred_participants(list, default:None) –The allowing type of traffic participants that can pass the area. If not specified, the area is not restricted to any type of traffic participants.
-
speed_limit(float, default:None) –The speed limit in this area.
-
speed_limit_unit(str, default:'km/h') –The unit of speed limit in this area. The valid units are
km/h,mi/h, andm/s. Defaults to "km/h". The speed limit will be automatically converted tom/swhen initializing the instance. If the unit is invalid, the speed limit will be set to None. -
speed_limit_mandatory(bool, default:True) –Whether the speed limit is mandatory or not.
-
custom_tags(dict, default:None) –The custom tags of the area.
Regulatory
This class implements the lanelet2-style map element RegulatoryElement.
Note
This class is still under development. It is supposed to support the detection of traffic events in the future.
Attributes:
-
id_(str) –The id of the regulatory element.
-
relations(dict) –A dictionary of the relations that the regulatory element belongs to. The key is the id of the relation, and the value is the role of the relation. Defaults to an empty dictionary.
-
ways(dict) –A dictionary of the ways that the regulatory element belongs to. The key is the id of the way, and the value is the role of the way. Defaults to an empty dictionary.
-
nodes(dict) –A dictionary of the nodes that the regulatory element belongs to. The key is the id of the node, and the value is the role of the node. Defaults to an empty dictionary.
-
type_(str) –The type of the regulatory element. Defaults to "regulatory_element".
-
subtype(str) –The subtype of the regulatory element.
-
position(str) –The position of the regulatory element. Defaults to None.
-
location(str) –The location of the regulatory element. Defaults to None.
-
dynamic(bool) –Whether the regulatory element is dynamic. Defaults to False.
-
fallback(bool) –Whether the regulatory element is a fallback. Defaults to False.
-
custom_tags(dict) –The custom tags of the regulatory element. Defaults to None.
__init__(id_, relations=dict(), ways=dict(), nodes=dict(), type_='regulatory_element', subtype=None, position=None, location=None, dynamic=False, fallback=False, custom_tags=None)
Initialize the attributes in the class.
Parameters:
-
id_(str) –The id of the regulatory element.
-
relations(dict, default:dict()) –A dictionary of the relations that the regulatory element belongs to. The key is the id of the relation, and the value is the role of the relation.
-
ways(dict, default:dict()) –A dictionary of the ways that the regulatory element belongs to. The key is the id of the way, and the value is the role of the way.
-
nodes(dict, default:dict()) –A dictionary of the nodes that the regulatory element belongs to. The key is the id of the node, and the value is the role of the node.
-
type_(str, default:'regulatory_element') –The type of the regulatory element.
-
subtype(str, default:None) –The subtype of the regulatory element.
-
position(str, default:None) –The position of the regulatory element.
-
location(str, default:None) –The location of the regulatory element.
-
dynamic(bool, default:False) –Whether the regulatory element is dynamic.
-
fallback(bool, default:False) –Whether the regulatory element is a fallback.
-
custom_tags(dict, default:None) –The custom tags of the regulatory element.
applies_to_lane(lane_id)
Return whether this regulatory element is bound to a lane.
is_stop_sign()
Return whether this regulatory element is a stop sign.
is_traffic_light()
Return whether this regulatory element is a traffic light.
state_at(time_ms=None)
Return the nearest dynamic state record, if one is available.
stop_point_at(time_ms=None)
Return the stop point from the dynamic state or static position.
Map
This class implements a map to manage the road elements. The elements in the map include nodes, lanes, areas, roadlines, and regulations. The map is used to store the road elements and provide the interface to access the elements. Every element in the map should have a unique id.
Attributes:
-
name(str) –The name of the map. Defaults to None.
-
scenario_type(str) –The scenario type of the map. Defaults to None.
-
country(str) –The country that the map is located in. Defaults to None.
-
ids(set) –The identifier of the elements in the map. All elements in the map should have a unique id. A conflict in ids will raise a KeyError.
-
nodes(dict) –The nodes in the map. Defaults to an empty dictionary. This attribute needs to be set manually by trigger the add_node method.
-
lanes(dict) –The lanes in the map. Defaults to an empty dictionary. This attribute needs to be set manually by trigger the add_lane method.
-
areas(dict) –The areas in the map. Defaults to an empty dictionary. This attribute needs to be set manually by trigger the add_area method.
-
roadlines(dict) –The roadlines in the map. Defaults to an empty dictionary. This attribute needs to be set manually by trigger the add_roadline method.
-
regulations(dict) –The regulations in the map. Defaults to an empty dictionary. This attribute needs to be set manually by trigger the add_regulatory method.
-
boundary(tuple) –The boundary of the map expressed in the form of (min_x, max_x, min_y, max_y). This attribute is read-only.
__init__(name=None, scenario_type=None, country=None)
Initialize the attributes in the class.
Parameters:
-
name(str, default:None) –The name of the map. Defaults to None.
-
scenario_type(str, default:None) –The scenario type of the map. Defaults to None.
-
country(str, default:None) –The country that the map is located in. Defaults to None.
add_area(area)
This function adds an area to the map.
Parameters:
-
area(Area) –The area to be added to the map.
Raises:
-
KeyError–If the id of the area is used by any other road element.
add_junction(junction)
This function adds a junction to the map.
Parameters:
-
junction(Junction) –The junction to be added to the map.
add_lane(lane)
This function adds a lane to the map.
Parameters:
-
lane(Lane) –The lane to be added to the map.
Raises:
-
KeyError–If the id of the lane is used by any other road element.
add_node(node)
This function adds a node to the map.
Parameters:
-
node(Node) –The node to be added to the map.
Raises:
-
KeyError–If the id of the node is used by any other road element.
add_regulatory(regulatory)
This function adds a traffic regulation to the map.
Parameters:
-
regulatory(Regulatory) –The regulatory to be added to the map.
Raises:
-
KeyError–If the id of the regulatory is used by any other road element.
add_roadline(roadline)
This function adds a roadline to the map.
Parameters:
-
roadline(RoadLine) –The roadline to be added to the map.
Raises:
-
KeyError–If the id of the roadline is used by any other road element.
get_by_id(id_)
This function returns the road element with the given id.
Parameters:
-
id_(str) –The id of the road element.
get_speed_limit(lane_id, default=None)
Return the speed limit of a lane.
Parameters:
-
lane_id(str) –The id of the lane.
-
default–The value returned when the lane has no speed limit.
query_bbox(bbox)
Query elements within a bounding box.
Parameters:
-
bbox–Tuple (min_x, max_x, min_y, max_y)
Returns:
-
–
List of element IDs within the bounding box
query_point(point, buffer=1.0)
Query elements near a point within given buffer distance.
Parameters:
-
point–Tuple (x, y) or shapely Point
-
buffer–Buffer distance in meters
Returns:
-
–
List of element IDs near the point
reset()
This function resets the map by clearing all the road elements.
set_boundary(boundary)
This function sets the boundary of the map.
Parameters:
-
boundary(tuple) –The boundary of the map expressed in the form of (min_x, max_x, min_y, max_y).
tactics2d.map.converter
Map format converter module.
Net2OsmConverter
Converts a SUMO (.net.xml) file to a Lanelet2-annotated OSM (.osm) file.
Each SUMO lane becomes one Lanelet2 lanelet relation. Boundaries are taken
directly from the parsed Lane.left_side and Lane.right_side so
geometry is consistent with the rest of Tactics2D.
Example:
from tactics2d.map.converter import Net2OsmConverter
converter = Net2OsmConverter()
converter.convert("map.net.xml", "map.osm")
convert(input_path, output_path)
Convert a SUMO net.xml file to a Lanelet2 OSM file.
Parameters:
-
input_path(str) –Path to the input .net.xml file.
-
output_path(str) –Path to the output .osm file.
Returns:
-
str(str) –The output file path.
Net2XodrConverter
Converts a SUMO (.net.xml) map to OpenDRIVE (.xodr) format.
Reads a SUMO net.xml file using NetXMLParser, then writes the parsed
map into OpenDRIVE xodr format via XodrWriter. Each Tactics2D Lane
becomes an OpenDRIVE road with a single driving lane. The road name
is taken from the SUMO edge id stored in lane.custom_tags["sumo_id"].
Example:
from tactics2d.map.converter import Net2XodrConverter
converter = Net2XodrConverter()
converter.convert("path/to/map.net.xml", "path/to/output.xodr")
convert(input_path, output_path)
Convert a SUMO net.xml file to an OpenDRIVE xodr file.
Parameters:
-
input_path(str) –Path to the input .net.xml file.
-
output_path(str) –Path to the output .xodr file.
Returns:
-
str(str) –The output file path.
Osm2NetConverter
Converts a Lanelet2-annotated OSM (.osm) file to a SUMO (.net.xml) file.
Example:
python
from tactics2d.map.converter import Osm2NetConverter
converter = Osm2NetConverter()
converter.convert("map.osm", "map.net.xml")
convert(input_path, output_path)
Convert a Lanelet2 OSM file to a SUMO net.xml file.
Parameters:
-
input_path(str) –Path to the input .osm file.
-
output_path(str) –Path to the output .net.xml file.
Returns:
-
str(str) –The output file path.
Osm2XodrConverter
Converts a Lanelet2-annotated OSM file to OpenDRIVE (.xodr) format.
Each Tactics2D Lane becomes an OpenDRIVE road. Predecessor/successor topology and junction areas are derived from lane endpoint proximity. Lane boundary subtypes are mapped to xodr roadMark types. Speed limits are converted from m/s to km/h.
Example:
from tactics2d.map.converter import Osm2XodrConverter
converter = Osm2XodrConverter()
converter.convert("map.osm", "map.xodr")
convert(input_path, output_path)
Convert a Lanelet2 OSM file to an OpenDRIVE xodr file.
Parameters:
-
input_path(str) –Path to the input Lanelet2 .osm file.
-
output_path(str) –Path to the output .xodr file.
Returns:
-
str(str) –The output file path.
Xodr2NetConverter
Converts an OpenDRIVE (.xodr) file to a SUMO (.net.xml) file.
Reads the OpenDRIVE file with XODRParser, then serialises the resulting Tactics2D Map to SUMO net.xml format via SumoWriter.
Example:
from tactics2d.map.converter import Xodr2NetConverter
converter = Xodr2NetConverter()
converter.convert("path/to/map.xodr", "path/to/output.net.xml")
convert(input_path, output_path)
Convert an OpenDRIVE xodr file to a SUMO net.xml file.
Parameters:
-
input_path(str) –Path to the input .xodr file.
-
output_path(str) –Path to the output .net.xml file.
Returns:
-
str(str) –The output file path.
Xodr2OsmConverter
Converts an OpenDRIVE (.xodr) file to a Lanelet2-annotated OSM (.osm) file.
The converter first parses the xodr input into a Tactics2D Map via
XODRParser, then serialises the Map to OSM XML via OsmWriter.
Every xodr lane becomes one Lanelet2 lanelet relation; boundaries are
taken directly from the parsed Lane.left_side / Lane.right_side
so geometry is consistent with the rest of Tactics2D.
Example:
from tactics2d.map.converter import Xodr2OsmConverter
converter = Xodr2OsmConverter()
converter.convert("map.xodr", "map.osm")
convert(input_path, output_path)
Convert an OpenDRIVE xodr file to a Lanelet2 OSM file.
Parameters:
-
input_path(str) –Path to the input .xodr file.
-
output_path(str) –Path to the output .osm file.
Returns:
-
str–The output file path.
tactics2d.map.generator
Generator module.
EntranceRamp
Bases: _RampBase
Entrance ramp generator where traffic merges onto the main road.
See :class:_RampBase for all shared attributes.
build(main_in, main_out, ramp_in, *, lane_width=None, main_speed_limit=None, ramp_speed_limit=None, id_offset=0)
Build an entrance ramp from the given port sockets.
Parameters:
-
main_in(RoadPort) –Upstream main-road socket.
-
main_out(RoadPort) –Downstream main-road socket.
-
ramp_in(RoadPort) –Upstream ramp socket where entering traffic arrives.
-
lane_width(float | None, default:None) –Lane width in metres. Defaults to
main_in.lane_width. -
main_speed_limit(float | None, default:None) –Main-road speed limit in km/h. Defaults to
main_in.speed_limit. -
ramp_speed_limit(float | None, default:None) –Ramp speed limit in km/h. Defaults to
ramp_in.speed_limit. -
id_offset(int, default:0) –First element id.
Returns:
-
RoadModuleResult–class:
RoadModuleResultwith ports"main_in","main_out", -
RoadModuleResult–and
"ramp"(plus"backward_in"/"backward_out"for urban).
ExitRamp
Bases: _RampBase
Exit ramp generator where traffic peels off from the main road.
See :class:_RampBase for all shared attributes.
build(main_in, main_out, ramp_out, *, lane_width=None, main_speed_limit=None, ramp_speed_limit=None, id_offset=0)
Build an exit ramp from the given port sockets.
Parameters:
-
main_in(RoadPort) –Upstream main-road socket.
-
main_out(RoadPort) –Downstream main-road socket.
-
ramp_out(RoadPort) –Downstream ramp socket where exiting traffic departs.
-
lane_width(float | None, default:None) –Lane width in metres. Defaults to
main_in.lane_width. -
main_speed_limit(float | None, default:None) –Main-road speed limit in km/h. Defaults to
main_in.speed_limit. -
ramp_speed_limit(float | None, default:None) –Ramp speed limit in km/h. Defaults to
ramp_out.speed_limit. -
id_offset(int, default:0) –First element id.
Returns:
-
RoadModuleResult–class:
RoadModuleResultwith ports"main_in","main_out", -
RoadModuleResult–and
"ramp"(plus"backward_in"/"backward_out"for urban).
Fork
Bases: RoadSegment
One-way lane-level fork generator where traffic diverges from the main road.
The branch geometry is computed by intersecting offset boundary polylines
with the main road's outer edge, producing a nose point (where the branch
inside boundary meets the main outer boundary) and a junction point (where
the branch outside boundary meets the main outer boundary). The main road's
outer boundary is split around the opening; the branch lane runs from the
junction anchor to branch_out.
Attributes:
-
fork_side–Side of the main road where the branch leaves.
-
taper_length–Minimum longitudinal distance reserved for the fork opening in metres.
-
branch_length–Nominal branch length used for diverge-point inference in metres.
-
step_size–Reference-line sampling interval in metres.
__init__(fork_side='right', taper_length=65.0, branch_length=85.0, step_size=0.1)
Initialise the generator.
Parameters:
-
fork_side(str, default:'right') –Side where the branch leaves. Must be
"left"or"right". -
taper_length(float, default:65.0) –Minimum longitudinal distance reserved for the fork opening.
-
branch_length(float, default:85.0) –Nominal branch length for diverge-point inference.
-
step_size(float, default:0.1) –Reference-line sampling interval in metres.
Raises:
-
ValueError–If
fork_sideis not"left"or"right", or any length/interval parameter is non-positive.
build(main_in, main_out, branch_out, *, main_lane_num=None, branch_lane_num=None, lane_width=None, speed_limit=None, diverge_s_ratio=None, id_offset=0)
Build a fork module from the given port sockets.
Parameters:
-
main_in(RoadPort) –Upstream main-road socket.
-
main_out(RoadPort) –Downstream main-road socket.
-
branch_out(RoadPort) –Downstream branch socket.
-
main_lane_num(int | None, default:None) –Number of main-road lanes. Defaults to
main_in.lane_num. -
branch_lane_num(int | None, default:None) –Number of branch lanes. Defaults to
branch_out.lane_num. -
lane_width(float | None, default:None) –Lane width in metres. Defaults to
main_in.lane_width. -
speed_limit(float | None, default:None) –Main-road speed limit in km/h. Defaults to
main_in.speed_limit. -
diverge_s_ratio(float | None, default:None) –Optional normalised diverge position on the main reference line. When omitted, inferred from
branch_out. -
id_offset(int, default:0) –First element id.
Returns:
-
RoadModuleResult–class:
RoadModuleResultwith ports"main_in","main_out", -
RoadModuleResult–and
"branch_out".
Raises:
-
ValueError–If
branch_lane_numexceedsmain_lane_num, or any lane count or width parameter is invalid.
Intersection
Bases: RoadSegment
T-junction or cross-junction generator.
Attributes:
-
lane_width–Default lane width in metres for arm dicts that omit it.
-
radius–Default arm boundary radius in metres for arm dicts that omit it.
-
speed_limit–Default speed limit in km/h.
-
step_size–Arc sampling interval in metres.
__init__(lane_width=3.5, radius=8.0, speed_limit=30.0, step_size=0.1)
Initialise the generator.
Parameters:
-
lane_width(float, default:3.5) –Default lane width in metres.
-
radius(float, default:8.0) –Default arm boundary radius in metres.
-
speed_limit(float, default:30.0) –Default speed limit in km/h.
-
step_size(float, default:0.1) –Arc sampling interval in metres.
Raises:
-
ValueError–If
step_size <= 0,lane_width <= 0, orradius <= 0.
build(center, arms, *, id_offset=0)
Build a T-junction or cross-junction.
Parameters:
-
center(ndarray) –Junction centre point as a 2-D world coordinate.
-
arms(list[dict[str, Any] | RoadPort]) –List of arm descriptors. Each element is either a :class:
RoadPortor a plaindictwith keys"heading","lane_num", and optionally"radius","curvature","lane_width","speed_limit". -
id_offset(int, default:0) –First element id.
Returns:
-
RoadModuleResult–class:
RoadModuleResultwith ports"arm_{i}_in"and -
RoadModuleResult–"arm_{i}_out"for each arm index and a single junction.
Raises:
-
ValueError–If
armsdoes not contain exactly 3 or 4 elements, or any arm haslane_num < 1orlane_width <= 0.
LaneAdapter
Bases: RoadSegment
Same-direction lane-count adapter generator.
Smoothly transitions between two road sections with different lane counts (difference of at most one). The lane that is added or dropped tapers from zero width at one end to full width at the other via smoothstep interpolation.
Attributes:
-
change_side–Side where the lane is added or dropped.
"right"means the rightmost lane changes;"left"means the leftmost lane changes. -
step_size–Reference-line sampling interval in metres.
__init__(change_side='right', step_size=0.1)
Initialise the generator.
Parameters:
-
change_side(str, default:'right') –Side where the lane count changes. Must be
"left"or"right". -
step_size(float, default:0.1) –Reference-line sampling interval in metres.
Raises:
-
ValueError–If
change_sideis not"left"or"right", orstep_size <= 0.
build(start_port, end_port, *, start_lane_num=None, end_lane_num=None, lane_width=None, speed_limit=None, id_offset=0)
Build a lane-count adapter between two ports.
Parameters:
-
start_port(RoadPort) –Upstream socket.
-
end_port(RoadPort) –Downstream socket.
-
start_lane_num(int | None, default:None) –Number of lanes at the entry. Defaults to
start_port.lane_num. -
end_lane_num(int | None, default:None) –Number of lanes at the exit. Defaults to
end_port.lane_num. -
lane_width(float | None, default:None) –Lane width in metres. Defaults to
start_port.lane_width. -
speed_limit(float | None, default:None) –Speed limit in km/h. Defaults to
start_port.speed_limit. -
id_offset(int, default:0) –First element id.
Returns:
-
RoadModuleResult–class:
RoadModuleResultwith ports"entry"(kind="adapter_in") -
RoadModuleResult–and
"exit"(kind="adapter_out").
Raises:
-
ValueError–If either lane count is less than 1,
lane_width <= 0, or the lane count difference exceeds 1.
Merge
Bases: RoadSegment
One-way lane-level merge generator where traffic converges onto the main road.
The branch geometry mirrors :class:Fork: branch boundaries are intersected
with the main outer edge to find the nose and junction points, the main
outer boundary is split, and the branch lane runs from branch_in to the
junction anchor.
Attributes:
-
merge_side–Side of the main road where the branch enters.
-
taper_length–Minimum longitudinal distance reserved for the merge opening in metres.
-
branch_length–Nominal branch length used for merge-point inference in metres.
-
step_size–Reference-line sampling interval in metres.
__init__(merge_side='right', taper_length=65.0, branch_length=85.0, step_size=0.1)
Initialise the generator.
Parameters:
-
merge_side(str, default:'right') –Side where the branch enters. Must be
"left"or"right". -
taper_length(float, default:65.0) –Minimum longitudinal distance reserved for the merge opening.
-
branch_length(float, default:85.0) –Nominal branch length for merge-point inference.
-
step_size(float, default:0.1) –Reference-line sampling interval in metres.
Raises:
-
ValueError–If
merge_sideis not"left"or"right", or any length/interval parameter is non-positive.
build(main_in, branch_in, main_out, *, main_lane_num=None, branch_lane_num=None, lane_width=None, speed_limit=None, merge_s_ratio=None, id_offset=0)
Build a merge module from the given port sockets.
Parameters:
-
main_in(RoadPort) –Upstream main-road socket.
-
branch_in(RoadPort) –Upstream branch socket.
-
main_out(RoadPort) –Downstream main-road socket.
-
main_lane_num(int | None, default:None) –Number of main-road lanes. Defaults to
main_in.lane_num. -
branch_lane_num(int | None, default:None) –Number of branch lanes. Defaults to
branch_in.lane_num. -
lane_width(float | None, default:None) –Lane width in metres. Defaults to
main_in.lane_width. -
speed_limit(float | None, default:None) –Main-road speed limit in km/h. Defaults to
main_in.speed_limit. -
merge_s_ratio(float | None, default:None) –Optional normalised merge position on the main reference line. When omitted, inferred from
branch_in. -
id_offset(int, default:0) –First element id.
Returns:
-
RoadModuleResult–class:
RoadModuleResultwith ports"main_in","branch_in", -
RoadModuleResult–and
"main_out".
Raises:
-
ValueError–If
branch_lane_numexceedsmain_lane_num, or any lane count or width parameter is invalid.
OneWay
Bases: RoadSegment
Single-direction road segment generator that builds N parallel lanes.
All lanes share the same travel direction and are generated from a Hermite
cubic reference line between the entry and exit sockets. Lane markings
follow the active standard (MUTCD or GB) configured via
:func:~tactics2d.map.generator.rules.lane_marking_rules.set_standard.
Attributes:
-
step_size–Reference-line sampling interval in metres.
__init__(step_size=0.1)
Initialise the generator.
Parameters:
-
step_size(float, default:0.1) –Reference-line sampling interval in metres.
build(start_port, end_port, *, lane_num=None, lane_width=None, speed_limit=None, id_offset=0)
Build a one-way road between two ports.
Parameters:
-
start_port(RoadPort) –Entry socket.
-
end_port(RoadPort) –Exit socket.
-
lane_num(int | None, default:None) –Lane count. Defaults to
start_port.lane_num. -
lane_width(float | None, default:None) –Lane width in metres. Defaults to
start_port.lane_width. -
speed_limit(float | None, default:None) –Speed limit in km/h. Defaults to
start_port.speed_limit. -
id_offset(int, default:0) –First element id.
Returns:
-
RoadModuleResult–class:
RoadModuleResultwith ports"entry"and"exit".
Raises:
-
ValueError–If
lane_num < 1orlane_width <= 0.
ParkingLotGenerator
Generate a random bay parking lot scenario with determined start and destination.
Attributes:
-
vehicle_size(Tuple[float, float]) –The size of the vehicle. The first element is the length and the second element is the width. This value is used to generate the target parking space. Defaults to (5.3, 2.5).
-
type_proportion(float) –The proportion of "bay" parking scenario in all generated scenarios. It should be in the range of [0, 1]. If the input is out of the range, it will be clipped to the range. When it is 0, the generator only generates "parallel" parking scenarios. Defaults to 0.5.
-
mode(str) –The type of the parking scenario. It can be "bay" or "parallel". Defaults to None.
__init__(vehicle_size=(5.3, 2.5), type_proportion=0.5)
Initialize the attributes in the class.
Parameters:
-
vehicle_size(Tuple[float, float], default:(5.3, 2.5)) –he size of the vehicle. The first element is the length and the second element is the width. This value is used to generate the target parking space.
-
type_proportion(float, default:0.5) –The proportion of "bay" parking scenario in all generated scenarios. It should be in the range of [0, 1]. If the input is out of the range, it will be clipped to the range. When it is 0, the generator only generates "parallel" parking scenarios. When it is 1, the generator only generates "bay" parking scenarios.
generate(map_)
Generate a random parking scenario.
Parameters:
-
map_(Map) –The map instance to store the generated parking scenario.
Returns:
RacingTrackGenerator
This class generates random racing tracks.
The generating process can be described as follows:
- Generate a circle with a radius = 800 m. Ideally, the time needed for a vehicle to make a full turn in this circle is around 3 minutes if it drives at a speed of 100 km/h.
- Generate some checkpoints that are deviated from the circle.
- Generate the center line by interpolating the checkpoints with Bezier curves.
- Check if the center line has extremely sharp turns. If so, adjust the checkpoints.
- Iterate until the center line is valid.
- Generate the tiles by interpolating the center line.
- Generate the road bounds by adding the track width to the left and right of the center line.
Attributes:
-
bezier_order(int) –The order of the Bezier curve. Defaults to 2.
-
bezier_interpolation(int) –The number of interpolation points for each Bezier curve. Defaults to 50.
__init__(bezier_order=2, bezier_interpolation=50)
Initialize the attributes in the class.
generate(map_)
This method generates a racing scenario and stores it in the given map instance.
Parameters:
-
map_(Map) –The map instance to store the generated racing scenario.
RoadModuleResult
dataclass
Generated road module result.
Attributes:
-
lanes(list[Lane]) –Generated Lane objects.
-
roadlines(list[RoadLine]) –Generated RoadLine objects.
-
ports(dict[str, RoadPort]) –Named RoadPort dictionary, keyed by logical port name.
-
id_counter(int) –Next available element id. Pass as
id_offsetto the next generator to prevent id collisions across modules. -
junctions(list[Junction]) –Generated Junction objects, e.g. intersection pavement polygons and roundabout rings.
-
areas(list[Area]) –Generated Area objects, e.g. gore islands and surface fill polygons.
RoadPort
dataclass
Connection socket of a road module.
Ports describe where one road module connects to another. Generators
consume input ports and produce output ports; assemblers match output ports
to input ports by comparing point and heading.
Attributes:
-
point(ndarray) –Socket position in world coordinates, shape
(2,). -
heading(float) –Travel direction at the socket in radians, measured from the positive x-axis counter-clockwise.
-
lane_num(int) –Number of lanes exposed by this port.
-
lane_width(float) –Width of each lane in metres.
-
speed_limit(float) –Speed limit at the socket in km/h.
-
kind(PortKind) –Semantic port type used by assemblers to validate connections.
-
name(str) –Human-readable label for logging and debugging.
-
lane_ids(tuple[str, ...]) –Ids of the lanes associated with this socket, ordered left to right relative to the travel direction.
-
metadata(dict[str, Any]) –Arbitrary key-value payload for generator-specific bookkeeping (e.g. module name, branch side). Not interpreted by the assembler.
__post_init__()
Normalise scalar and collection fields to canonical Python types.
RoadSegment
Bases: ABC
Abstract base for all road segment generators.
Each concrete subclass encapsulates structural configuration in __init__
(lane side, taper geometry, sampling interval, etc.) and exposes a single
build method that receives the runtime connection sockets and returns a
:class:~tactics2d.map.generator.rules.module_types.RoadModuleResult.
Typical usage::
seg = Fork(fork_side="right", taper_length=65.0)
result = seg.build(main_in, main_out, branch_out, id_offset=0)
next_result = seg.build(p1, p2, p3, id_offset=result.id_counter)
build(*args, id_offset=0, **kwargs)
abstractmethod
Build the road segment from the given port sockets.
Parameters:
-
*args(RoadPort, default:()) –Positional :class:
RoadPortsockets. The exact sequence and semantics depend on the concrete subclass. -
id_offset(int, default:0) –First element id assigned by the generator. Pass the previous result's
id_counterto chain calls without id collisions. -
**kwargs–Per-call overrides such as lane counts or speed limits; each subclass documents which keys are accepted.
Returns:
-
A(RoadModuleResult) –class:
RoadModuleResultcontaining lanes, roadlines, junctions, -
RoadModuleResult–named ports, and the next available id counter.
Note
Centre-based generators (:class:~tactics2d.map.generator.road_segment.Intersection
and :class:~tactics2d.map.generator.road_segment.Roundabout) override this
signature with (center, arms, *, id_offset) because their primary
inputs are a world-space centre point and a list of arm descriptors rather
than a flat sequence of :class:RoadPort sockets.
Roundabout
Bases: RoadSegment
Roundabout generator with a circulating ring road.
Each arm socket is placed on the circular outer boundary of the ring road.
Connect TwoWay or OneWay segments to the returned arm ports to
produce curved approach roads.
Attributes:
-
ring_radius–Radius of the inner edge of the ring road in metres.
-
ring_lane_num–Number of circulating lanes in the ring.
-
lane_width–Lane width in metres (uniform for ring and arm stubs).
-
speed_limit–Speed limit in km/h (applied to ring and arm stubs).
-
step_size–Arc sampling interval in metres.
__init__(ring_radius=15.0, ring_lane_num=1, lane_width=3.5, speed_limit=20.0, step_size=0.1)
Initialise the generator.
Parameters:
-
ring_radius(float, default:15.0) –Radius of the inner edge of the ring road in metres.
-
ring_lane_num(int, default:1) –Number of circulating lanes in the ring.
-
lane_width(float, default:3.5) –Lane width in metres.
-
speed_limit(float, default:20.0) –Speed limit in km/h.
-
step_size(float, default:0.1) –Arc sampling interval in metres.
Raises:
-
ValueError–If
ring_lane_num < 1,lane_width <= 0,ring_radius <= 0, orstep_size <= 0.
build(center, arms, *, id_offset=0)
Build a roundabout from the given centre and arm descriptors.
Parameters:
-
center(ndarray) –2-D world coordinate of the roundabout centre.
-
arms(list[dict[str, Any] | RoadPort]) –List of arm descriptors. Each element is either a :class:
RoadPortor a plaindictwith keys"heading","lane_num", and optionally"lane_width","speed_limit". -
id_offset(int, default:0) –First element id.
Returns:
-
RoadModuleResult–class:
RoadModuleResultcontaining ring-road lanes, arm-stub -
RoadModuleResult–lanes, roadlines, a junction polygon, and one named port per arm
-
RoadModuleResult–keyed as
"arm_0","arm_1", ….
Raises:
-
ValueError–If fewer than 2 arms are supplied, or any arm has invalid
lane_numorlane_width.
TwoWay
Bases: RoadSegment
Bidirectional road segment generator with separate forward and backward lanes.
Forward and backward lanes share a common centreline reference but are offset symmetrically. A double solid or dashed yellow centre line separates the two directions; outer edges and interior dividers follow the active standard (MUTCD or GB).
Attributes:
-
step_size–Reference-line sampling interval in metres.
__init__(step_size=0.1)
Initialise the generator.
Parameters:
-
step_size(float, default:0.1) –Reference-line sampling interval in metres.
build(start_port, end_port, *, forward_lane_num=None, backward_lane_num=None, lane_width=None, speed_limit=None, id_offset=0)
Build a two-way road between two ports.
Parameters:
-
start_port(RoadPort) –Forward-direction start socket.
-
end_port(RoadPort) –Forward-direction end socket.
-
forward_lane_num(int | None, default:None) –Forward lane count. Defaults to
start_port.lane_num. -
backward_lane_num(int | None, default:None) –Backward lane count. Defaults to
start_port.lane_num. -
lane_width(float | None, default:None) –Lane width in metres. Defaults to
start_port.lane_width. -
speed_limit(float | None, default:None) –Speed limit in km/h. Defaults to
start_port.speed_limit. -
id_offset(int, default:0) –First element id.
Returns:
-
RoadModuleResult–class:
RoadModuleResultwith ports"forward_in","forward_out", -
RoadModuleResult–"backward_in", and"backward_out".
Raises:
-
ValueError–If any lane count is less than 1 or
lane_width <= 0.
get_standard()
Return the active lane marking standard.
make_port(base_port, *, kind=None, name=None, lane_ids=None, metadata=None)
Create a derived RoadPort from a base port with updated semantic fields.
Geometry (point, heading, lane_num, lane_width,
speed_limit) is copied verbatim. metadata is merged: entries from
base_port.metadata are overlaid with entries from metadata, with
the latter taking priority.
Parameters:
-
base_port(RoadPort) –Source port whose geometry and lane attributes are copied.
-
kind(str | None, default:None) –Override for
RoadPort.kind. Defaults tobase_port.kind. -
name(str | None, default:None) –Override for
RoadPort.name. Defaults tobase_port.name. -
lane_ids(tuple[str, ...] | list[str] | None, default:None) –Override for
RoadPort.lane_ids. Defaults tobase_port.lane_ids. -
metadata(dict[str, Any] | None, default:None) –Additional metadata merged on top of
base_port.metadata. Keys present in both take the value from this argument.
Returns:
set_standard(standard)
Set the active lane marking standard globally.
Parameters:
-
standard(Standard) –Target standard. Must be
"MUTCD"(US) or"GB"(Chinese GB 5768).
Raises:
-
ValueError–If
standardis not"MUTCD"or"GB".
tactics2d.map.parser
Parser module.
GISParser
summary
parse(file_path, projector=None)
summary
Parameters:
-
file_path(str) –The absolute path of a
.shpfile or a list of.shpfiles.
NetXMLParser
Parser for the SUMO network format (.net.xml) map.
Reads a SUMO road-network file and converts it into a Tactics2D Map object containing lanes, road-mark lines, junctions, and connections. The parser operates directly on the XML without any external SUMO dependency.
Lanes are constructed from the centre-line shape attribute: left and right boundaries are generated by applying a constant-width normal offset to each vertex, guaranteeing that both boundaries share the same point order and orientation. Internal edges (function="internal") are included so that junction connector geometry is preserved.
Reference
https://sumo.dlr.de/docs/Networks/SUMO_Road_Networks.html
get_lane_subtype(edge_type)
Map a SUMO edge type string to a Tactics2D lane subtype.
Parameters:
-
edge_type(str) –The SUMO edge type attribute string.
Returns:
-
str–The corresponding Tactics2D lane subtype. Defaults to 'road'.
offset_line(coords, half_width)
staticmethod
Create left and right boundary polylines by offsetting a centre-line.
For each vertex the normal vector pointing to the left (when travelling from start to end) is computed, and both the left and right offset points are calculated.
Parameters:
-
coords(list[tuple[float, float]]) –Centre-line coordinates [(x0, y0), (x1, y1), ...].
-
half_width(float) –Half of the lane width in metres.
Returns:
-
list[tuple[float, float]]–A tuple (left_coords, right_coords), each a list of (x, y) tuples
-
list[tuple[float, float]]–with the same number of points as the centre-line.
parse(file_path)
parse_shape(shape_str)
staticmethod
Parse a SUMO shape string into a list of (x, y) coordinate tuples.
Parameters:
-
shape_str(str) –Space-separated coordinate pairs, e.g. "0.00,1.00 2.00,3.00".
Returns:
-
list[tuple[float, float]]–List of (x, y) tuples parsed from the shape string.
OSMParser
This class implements a parser for the original OpenStreetMap format map. The parser is tested with data generated by the official OpenStreetMap website and the JOSM software application.
Example
parser = OSMParser() map_ = parser.parse("/path/to/map.osm") parser_l2 = OSMParser(lanelet2=True) map_l2 = parser_l2.parse("/path/to/map_lanelet2.osm")
__init__(lanelet2=False)
Initialize the parser.
Parameters:
-
lanelet2(bool, default:False) –Whether the
.osmfile is annotated in Lanelet2 format. Defaults to False.
parse(file_path, configs=None)
Parse an OpenStreetMap file into a Tactics2D Map.
Parameters:
-
file_path(str) –The absolute path of the
.osmfile. -
configs(dict, default:None) –Optional configuration dictionary with keys: project_rule (dict): Projection parameters passed to pyproj.Proj. gps_origin (tuple): GPS origin coordinates for projection. name (str): Map name. scenario_type (str): Scenario type. country (str): Country code.
Returns:
-
Map(Map) –A Tactics2D Map populated with all elements parsed from the OSM file.
XODRParser
Parser for the OpenDRIVE (.xodr) map format.
Converts an OpenDRIVE file into a Tactics2D Map object containing lanes, road-mark lines, junctions, and optional area objects (crosswalks, etc.).
The parser follows the canonical offset-curve approach used by libopendrive and esmini:
P_border(s, t) = P_ref(s) + t * n_ref(s)
where s is the arc-length along the reference line, t is the signed lateral distance, and n_ref(s) is the unit left-pointing normal. Lane widths are accumulated outward from the centre lane so that all boundaries share the same s-sample array. Analytic curvature is computed directly from geometry coefficients (paramPoly3, arc, spiral, poly3) and passed to the offset builder, eliminating the numerical noise introduced by finite-difference curvature estimation on sampled polylines.
Example:
from tactics2d.map.parser import XODRParser
parser = XODRParser()
map_ = parser.parse("path/to/map.xodr")
load_header(node)
Parse the <header> element of an OpenDRIVE file.
Parameters:
-
node(Element) –The
<header>XML element.
Returns:
-
tuple(tuple) –info (dict): Header attributes including name, version, date, and geographic bounding box. projector (CRS or None): A pyproj CRS object parsed from the
<geoReference>child element, or None if absent.
load_junction(junction_node)
Parse a <junction> element and return a Junction object.
Parameters:
-
junction_node(Element) –The
<junction>XML element to parse.
Returns:
-
Junction(Junction) –A Junction populated with all
<connection>child elements.
Example:
import xml.etree.ElementTree as ET
from tactics2d.map.parser import XODRParser
parser = XODRParser()
tree = ET.parse("path/to/map.xodr")
junction_node = tree.getroot().find("junction")
junction = parser.load_junction(junction_node)
load_road(road_node)
Parse a
Parameters:
-
road_node(Element) –The
<road>XML element to parse.
Returns:
-
tuple(tuple) –lanes (list[Lane]): List of parsed Lane objects. roadlines (list[RoadLine]): List of parsed RoadLine objects. objects (list[Area]): List of parsed Area objects.
parse(file_path)
Parse an OpenDRIVE file and return a Tactics2D Map object.
Parameters:
-
file_path(str) –Absolute or relative path to the .xodr file.
Returns:
-
Map(Map) –A Tactics2D Map populated with lanes, roadlines, junctions, and area objects parsed from the OpenDRIVE file.