API Reference

LRS Configuration

class linref.LRS(key_col: str | list[str] | None = None, chain_col: str | None = None, loc_col: str | None = None, beg_col: str | None = None, end_col: str | None = None, geom_col: str | None = None, geom_m_col: str | None = None, closed: str | None = None)[source]

Bases: object

property is_linear: bool

Return whether the LRS is linear (i.e., has begin and end columns defined). This does not check for presence of the columns in the DataFrame.

property is_point: bool

Return whether the LRS is point-based (i.e., has a location column but no begin or end columns defined). This does not check for presence of the columns in the DataFrame.

property is_located: bool

Return whether the LRS is located (i.e., has a location column defined). This does not check for presence of the column in the DataFrame.

property is_grouped: bool

Return whether the LRS is grouped (i.e., has one or more key columns defined). This does not check for presence of the columns in the DataFrame.

property is_spatial: bool

Return whether the LRS is spatial (i.e., has a geometry column defined). This does not check for presence of the column in the DataFrame.

property is_spatial_m: bool

Return whether the LRS is spatial with M-enabled geometries (i.e., has a geometry_m column defined). This does not check for presence of the column in the DataFrame.

property is_chained: bool

Return whether the LRS has a chain column defined. This does not check for presence of the column in the DataFrame.

property params: dict
copy(deep: bool = False) LRS[source]

Create an exact copy of the object instance.

Parameters:

deep (bool, default False) – Whether the created copy should be a deep copy.

set_closed(closed: str | None = None, inplace: bool = False) LRS | None[source]

Set LRS closure type.

Parameters:
  • closed ({'left', 'right', 'left_mod', 'right_mod', 'both', 'neither'}, optional) – The closure type to set. If None, sets to default closure type.

  • inplace (bool, default False) – Whether to apply changes to the LRS in place.

set_params(inplace: bool = False, **kwargs) LRS | None[source]

Set LRS parameters.

Parameters:
  • inplace (bool, default False) – Whether to apply changes to the LRS in place.

  • key_col (label or array-like, optional) – The key column or array-like of key columns to set.

  • loc_col (label, optional) – The location measure column to set.

  • beg_col (label, optional) – The begin measure column to set.

  • end_col (label, optional) – The end measure column to set.

  • geom_col (label, optional) – The geometry column to set.

  • geom_m_col (label, optional) – The geometry_m column to set.

  • closed ({'left', 'right', 'left_mod', 'right_mod', 'both', 'neither'}, optional) – The closure type to set.

add_key(key_col: str | list[str], inplace: bool = False) LRS | None[source]

Add one or more key columns to the LRS.

Parameters:
  • key_col (label or array-like) – The key column or array-like of key columns to add.

  • inplace (bool, default False) – Whether to apply changes to the LRS in place.

remove_key(key_col: str | list[str], errors: str = 'raise', inplace: bool = False) LRS | None[source]

Remove one or more key columns from the LRS.

Parameters:
  • key_col (label or array-like) – The key column or array-like of key columns to remove.

  • errors ({'ignore', 'raise'}, default 'raise') – Whether to raise an error or ignore missing keys.

  • inplace (bool, default False) – Whether to apply changes to the LRS in place.

study(df: DataFrame) dict[source]

Validate the dataframe for LRS compatibility.

Parameters:
  • df (DataFrame) – The DataFrame to validate.

  • how ({'raise', 'verbose', 'bool'}, default 'raise') – Whether to raise an error or return a boolean for validation failures.

LRS Accessor

class linref.LRS_Accessor(df)[source]

Bases: object

Accessor for working with linear referencing systems (LRS) in GeoDataFrames.

property df: DataFrame

Return the underlying DataFrame.

property event_cols: list[str]

Return a list of all event-defining columns in the dataframe, including key and measure columns as defined in the LRS.

property measure_cols: list[str]

Return a list of all measure columns in the dataframe as defined in the LRS (i.e., location, begin, and end columns).

property lrs_cols: list[str]

Return a list of all LRS-managed columns in the dataframe, including key, measure, and geometry columns as defined in the LRS.

property other_cols: list[str]

Return a list of all non-LRS-managed columns in the dataframe.

property geometry_sync: str

The geometry synchronization behavior for this DataFrame. State is stored in df.attrs for pandas >= 3.0 compatibility.

property lrs: LRS

The LRS object currently set for the DataFrame. State is stored in df.attrs for pandas >= 3.0 compatibility.

property is_lrs_set: bool

Whether an LRS object is currently set for the DataFrame.

property is_lrs_empty: bool

Whether the currently set LRS object is empty (i.e., has no key, measure, or geometry columns defined).

property key_col: list[str]

Return a list of all event key columns in the set LRS if defined, including the chain column when it exists in the DataFrame.

property base_key_col: list[str]

Return the base key columns from the LRS definition, excluding the chain column. Used for operations that need to group by route identifiers without chaining (e.g., computing chain indices).

property loc_col: str

Return the location measure column in the set LRS if defined.

property beg_col: str

Return the begin measure column in the set LRS if defined.

property end_col: str

Return the end measure column in the set LRS if defined.

property geom_col: str

Return the geometry column in the set LRS if defined.

property geom_m_col: str

Return the M-enabled geometry column in the set LRS if defined.

property closed: str

Return the closure type in the set LRS if defined.

property index: ndarray

Return the index values of the dataframe. Equivalent to self.df.index.values.

property keys: ndarray

Return the event keys from the dataframe as an array.

property locs: ndarray

Return the location measure values from the dataframe as an array. If no location column is defined in the LRS, returns None.

property begs: ndarray

Return the begin measure values from the dataframe as an array. If no begin column is defined in the LRS, returns None.

property ends: ndarray

Return the end measure values from the dataframe as an array. If no end column is defined in the LRS, returns None.

property event_lengths: ndarray

Return the event lengths from the dataframe as an array. If no begin and end columns are defined in the LRS, returns None.

property geoms: ndarray

Return the geometry values from the dataframe as an array. If no geometry column is defined in the LRS, returns None.

property geoms_m: ndarray

Return the M-enabled geometry values from the dataframe as an array. If no M-enabled geometry column is defined in the LRS, returns None.

property geoms_m_reduced: ndarray

Extract and return the shapely geometries from the M-enabled geometry column in the dataframe.

property is_grouped: bool

Return whether the active LRS is grouped and the key columns are present in the dataframe.

property missing_key_cols: list[str]

Return a list of key columns defined in the LRS but missing from the DataFrame. Returns an empty list if no keys are defined or all keys are present.

property is_linear: bool

Return whether the active LRS is linear and the begin and end columns are present in the dataframe.

property is_point: bool

Return whether the active LRS is point-based and the location column is present in the dataframe.

property is_located: bool

Return whether the active LRS is located and the location column is present in the dataframe.

property is_spatial: bool

Return whether the active LRS is spatial and the geometry column is present in the dataframe.

property is_spatial_m: bool

Return whether the active LRS is spatial and the geometry column is present in the dataframe.

property is_lrs_grouped: bool

Return whether the active LRS is grouped, regardless of presence of key columns in the dataframe.

property is_lrs_linear: bool

Return whether the active LRS is linear, regardless of presence of begin and end columns in the dataframe.

property is_lrs_point: bool

Return whether the active LRS is point-based, regardless of presence of location column in the dataframe.

property is_lrs_located: bool

Return whether the active LRS is located, regardless of presence of location column in the dataframe.

property is_lrs_spatial: bool

Return whether the active LRS is spatial, regardless of presence of geometry column in the dataframe.

property is_lrs_spatial_m: bool

Return whether the active LRS is spatial with M values, regardless of presence of geometry column in the dataframe.

property is_lrs_chained: bool

Return whether the active LRS has a chain column defined, regardless of presence of the chain column in the dataframe.

property is_chained: bool

Return whether the active LRS has a chain column defined and the chain column is present in the dataframe.

property is_geometrically_contiguous: bool

Return whether linear geometries in the dataframe when grouped by LRS keys are geometrically contiguous, producing single continuous geometries without gaps when dissolved and merged.

property is_contiguous: bool

Return whether linear geometries in the dataframe when grouped by LRS keys are contiguous, producing continuous geometries without disjoints such as overlaps or gaps.

property is_disjointed: bool

Return whether linear geometries in the dataframe when grouped by LRS keys contain disjointed segments (i.e., are not contiguous). Equivalent to not self.is_contiguous.

property valid_events: Series

Return a boolean Series indicating which events in the dataframe are valid according to the active LRS, e.g., have populated key columns and event measures.

property invalid_events: Series

Return a boolean Series indicating which events in the dataframe are invalid according to the active LRS, e.g., have missing key columns or event measures.

drop_invalid_events() DataFrame | None[source]

Drop invalid events from the dataframe according to the active LRS. Invalid events are those with missing data in key columns or event measures.

Returns:

df – A copy of the DataFrame with invalid events removed.

Return type:

DataFrame

study() dict[source]

Evaluate which LRS properties are satisfied by the dataframe.

property events: EventsData

Return the events object for the active LRS.

check_exact_geoms(if_missing: bool = True) ndarray[source]

Check if geometries in both the geometry and geometry_m columns are exactly the same, returning an array of boolean values.

Parameters:

if_missing (bool, default True) – The value to return for rows where either geometry column is missing.

get_keys(col=None, require=True) ndarray[source]

Return the event keys from the dataframe as an array.

Parameters:
  • col (str, optional) – The column name to use for extracting keys. If None, uses the default key columns in the LRS.

  • require (bool, default True) – Whether to raise an error if the key column is not found.

Returns:

An array of event keys.

Return type:

np.ndarray

get_events(key_col=None, require=True, allow_undefined_events=False) EventsData[source]

Return the events object for the active LRS.

Parameters:
  • key_col (str, optional) – The column name to use for extracting keys. If None, uses the default key columns in the LRS.

  • require (bool, default True) – Whether to raise an error if the key column is not found.

  • allow_undefined_events (bool, default False) – Whether to allow undefined events when creating the EventsData object. If False, will raise an error if undefined events are present. Undefined events are those with no defined location, begin, or end values.

copy(deep: bool = False) LRS_Accessor[source]

Create an exact copy of the object instance.

Parameters:

deep (bool, default False) – Whether the created copy should be a deep copy.

copy_df() DataFrame[source]

Create a copy of the underlying DataFrame, preserving LRS settings.

lrs_like(other: DataFrame | LRS_Accessor, inplace: bool = False) DataFrame | None[source]

Assign the LRS settings of another DataFrame to the current DataFrame.

Parameters:
  • other (DataFrame or LRS_Accessor) – The DataFrame or LRS_Accessor to copy LRS settings from.

  • inplace (bool, default False) – Whether to apply changes to the DataFrame in place.

Returns:

df – A copy of the current DataFrame with LRS settings copied from the input DataFrame.

Return type:

DataFrame

set_lrs(lrs: LRS | None = None, inplace: bool = False, **kwargs) DataFrame | None[source]

Set the LRS object for the DataFrame.

Parameters:
  • lrs (LRS , default None) – The LRS object to set for the DataFrame.

  • inplace (bool, default False) – Whether to apply changes to the DataFrame in place.

  • **kwargs – Additional parameters to set for the LRS object if lrs is None.

modify_lrs(inplace: bool = False, **kwargs) DataFrame | None[source]

Modify the parameters of the existing LRS object in the DataFrame.

Parameters:
  • **kwargs – The LRS parameters from an LRS object to modify.

  • inplace (bool, default False) – Whether to apply changes to the DataFrame in place. Note, this does not modify the existing LRS object in place, but creates a modified copy of the existing LRS object and sets it to the DataFrame. To modify the LRS object itself, access the LRS object directly via df.lr.lrs.

add_key(key_col: str | list[str], inplace: bool = False) DataFrame | None[source]

Add one or more key columns to an existing LRS object in the DataFrame.

Parameters:
  • key_col (label or array-like) – The key column or array-like of key columns to add.

  • inplace (bool, default False) – Whether to apply changes to the DataFrame in place.

remove_key(key_col: str | list[str], errors: str = 'raise', inplace: bool = False) None[source]

Remove one or more key columns from an existing LRS object in the DataFrame.

Parameters:
  • key_col (label or array-like) – The key column or array-like of key columns to remove.

  • errors ({'ignore', 'raise'}, default 'raise') – Whether to raise an error or ignore missing keys.

  • inplace (bool, default False) – Whether to apply changes to the DataFrame in place.

clear_lrs(inplace: bool = False) None[source]

Clear the LRS object from the DataFrame. Applies a new empty LRS object equivalent to LRS().

Parameters:

inplace (bool, default False) – Whether to apply changes to the DataFrame in place.

set_monotonic(*args, **kwargs)
build_geom_m() ndarray[source]

Build a list of geometry_m objects based on the begin and end locations of the LRS.

Returns:

geoms_m – An array of geometry_m objects.

Return type:

np.ndarray

add_geom_m(name: str = 'geometry_m', inplace: bool = False) DataFrame | None[source]

Add an M-enabled geometry column to the DataFrame based on the begin and end values of the LRS.

Parameters:
  • name (str, default 'geometry_m') – The name of the geometry column to return.

  • inplace (bool, default False) – Whether to apply changes to the dataframe in place.

iter_groups(*args, **kwargs)
group_counts(*args, **kwargs)
sort_standard(return_index: bool = False, inplace: bool = False) DataFrame | tuple[DataFrame, ndarray] | None[source]

Sort the dataframe by the LRS columns in the standard order of ‘groups’, ‘begs’, ‘ends’ for linear events and ‘groups’, ‘locs’ for point events.

Parameters:
  • return_index (bool, default False) – Whether to return an array of the indices which represent the performed sort in addition to the sorted events.

  • inplace (bool, default False) – Whether to perform the operation in place, returning None.

get_group(*args, **kwargs)
get_chains(*args, **kwargs)
add_chaining(*args, **kwargs)
point_to_linear(*args, **kwargs)
generate_linear_events(*args, **kwargs)
extend(*args, **kwargs)
shift(*args, **kwargs)
round(*args, **kwargs)
impute_keys(*args, **kwargs)
resegment(*args, **kwargs)
separate(*args, **kwargs)
dissolve(*args, **kwargs)
constrain_to(*args, **kwargs)
split(*args, **kwargs)
clip(*args, **kwargs)
integrate(*args, **kwargs)
cut_from(*args, **kwargs)
interpolate_from(*args, **kwargs)
distribute_from(other: DataFrame, columns: list | str | None = None, inplace: bool = False, replace: bool = False, **params) DataFrame | None[source]

Distribute attribute data from another dataframe onto the current dataframe based on linear referencing relationships. This is a shortcut for lr.relate(other)[columns].distribute(**params).

Parameters:
  • other (DataFrame) – The other DataFrame to distribute attributes from. Must have an equivalent linear referencing system.

  • columns (str or list, optional) – The column label or list of column labels to distribute from the other dataframe. If None, all columns except key and geometry columns will be distributed.

  • inplace (bool, default False) – Whether to apply changes to the DataFrame in place.

  • replace (bool, default False) – Whether to replace existing columns in the DataFrame with the same names as those being distributed. If False, an error will be raised if any column names conflict.

  • **params – Additional parameters to pass to the EventsRelation.distribute method.

Returns:

df – A copy of the current DataFrame with distributed attributes or None if inplace=True.

Return type:

DataFrame

parse_geom_m_wkt(geom_m_col: str | None = None, inplace: bool = False) DataFrame | None[source]

Parse the WKT representation of the M-enabled geometry data into a LineStringM object.

Parameters:
  • geom_m_col (str, optional) – The name of the geometry_m column to parse. If None, use the geometry_m column name from the LRS if present.

  • inplace (bool, default False) – Whether to apply changes to the DataFrame in place.

geom_m_to_wkt(geom_m_col: str | None = None, inplace: bool = False) DataFrame | None[source]

Convert LineStringM objects in the M-enabled geometry column to WKT strings. Typically used for export compatibility while using the linref LineStringM implementation. Will become unnecessary once M- enabled geometries are more widely supported in shapely.

Parameters:
  • geom_m_col (str, optional) – The name of the geometry_m column to convert. If None, use the geometry_m column name from the LRS if present.

  • inplace (bool, default False) – Whether to apply changes to the DataFrame in place.

extract_m_values(beg_col: str | None = None, end_col: str | None = None, replace: bool = False, inplace: bool = False) DataFrame | None[source]

Extract the M values from the geometry_m column, applying them to the begin and end location columns.

Parameters:
  • beg_col (str, optional) – The name of the begin location column to add. If None, uses the existing begin column name in the LRS, or ‘beg’ if no begin column is defined.

  • end_col (str, optional) – The name of the end location column to add. If None, uses the existing end column name in the LRS, or ‘end’ if no end column is defined.

  • replace (bool, default False) – Whether to replace existing begin or end columns in the dataframe. If False, an error will be raised if the columns already exist.

  • inplace (bool, default False) – Whether to apply changes to the DataFrame in place.

relate(other: DataFrame, cache: bool = True) EventsRelation[source]

Create an events data relationship between two linearly referenced datasets.

Parameters:
  • other (DataFrame) – The other DataFrame to relate with. Must have an equivalent linear referencing system.

  • cache (bool, default True) – Whether to cache computed relationship operations, such as intersections and overlays, for faster subsequent operations. For one-time operations or to save on memory use for large datasets, set cache=False.

overlay(other: DataFrame, normalize: bool = False, norm_by: str = 'right', chunksize: int = 1000, grouped: bool = True) csr_array[source]

Overlay two sets of linearly referenced datasets, computing the length or proportion of overlap between each pair of events.

Parameters:
  • other (DataFrame) – The other DataFrame to overlay with. Must have an equivalent linear referencing system.

  • normalize (bool, default False) – Whether overlapping lengths should be normalized to give a proportional result with a float value between 0 and 1.

  • norm_by (str, default 'right') – How overlapping lengths should be normalized. Only applied if normalize is True. - ‘right’ : Normalize by the length of the right events. - ‘left’ : Normalize by the length of the left events.

  • chunksize (int or None, default 1000) – The maximum number of events to process in a single chunk. Input chunksize will affect the memory usage and performance of the function. This does not affect actual results, only computation.

  • grouped (bool, default True) – Whether to process the overlay operation for each group separately. This will affect the memory usage and performance of the function. This does not affect actual results, only computation.

intersect(other: DataFrame, enforce_edges: bool = True, chunksize: int = 1000, grouped: bool = True) csr_array[source]

Identify intersections between two sets of linearly referenced datasets.

Parameters:
  • other (DataFrame) – The other DataFrame to intersect with. Must have an equivalent linear referencing system.

  • enforce_edges (bool, default True) – Whether to consider cases of coincident begin and end points, according to each collection’s closed state. For instances where these cases are not relevant, set enforce_edges=False for improved performance. Ignored for point to point intersections.

  • chunksize (int or None, default 1000) – The maximum number of events to process in a single chunk. Input chunksize will affect the memory usage and performance of the function. This does not affect actual results, only computation.

  • grouped (bool, default True) – Whether to process the overlay operation for each group separately. This will affect the memory usage and performance of the function. This does not affect actual results, only computation.

cluster(max_gap: float, name: str = 'cluster', link_col: str | list[str] | None = None, enforce_edges: bool | None = None, inplace: bool = False) DataFrame | None[source]

Cluster events based on linear referencing proximity within each group. Events whose locations are within the specified max gap of each other (directly or transitively) are assigned to the same cluster.

This method buffers each event location by the max gap to create small linear ranges, then identifies overlapping ranges within each group using a self-intersection, and finally extracts connected components from the resulting adjacency graph to form clusters.

For point events, two points are proximal if their locations are within the max gap distance. For linear events, two events are proximal if their ranges (after extension by the max gap) overlap.

If link_col is provided, events sharing the same link value(s) are additionally connected across groups, allowing clusters to span multiple routes or keys.

Parameters:
  • max_gap (float) – The maximum linear distance between event locations for them to be considered proximal. Events within this distance (directly or transitively through intermediate events) will be assigned to the same cluster.

  • name (str, default 'cluster') – The name of the cluster column to add to the DataFrame.

  • link_col (str, list of str, or None, default None) – Column name(s) identifying shared entities across groups. Events with the same link value(s) are connected in the cluster graph, allowing clusters to bridge across different key groups (e.g., an intersection ID that is shared across multiple routes). Rows with NaN in link columns are not linked.

  • enforce_edges (bool or None, default None) – Whether to treat shared edges (touching boundaries) as intersections. If None, defaults to False for linear events and is disregarded for point events.

  • inplace (bool, default False) – Whether to apply changes to the DataFrame in place.

Returns:

df – A copy of the DataFrame with a new cluster column, or None if inplace=True.

Return type:

DataFrame or None

Raises:

LRSConfigurationError – If the LRS has no location or linear data defined, or if event locations or bounds contain undefined (NaN) values.

generate_intersections(*args, **kwargs)
project(*args, **kwargs)

EventsData

class linref.EventsData(index: ndarray = None, groups: ndarray = None, locs: ndarray = None, begs: ndarray = None, ends: ndarray = None, closed: ndarray = None, dtype: dtype = <class 'float'>, copy: bool = None, force_monotonic: bool = True, **kwargs)[source]

Bases: object

Class for managing collections of events with linear or point data.

property index: ndarray

Event index.

property generic_index: ndarray

Generic 0-based integer index.

property index_data: ndarray

Event index data.

property groups: ndarray | None

Event reference groups.

property groups_hashed: ndarray | None

Event reference groups hashed.

property groups_data: ndarray

Event reference groups data.

property locs: ndarray | None

Event location measures.

property begs: ndarray | None

Event begin measures.

property ends: ndarray | None

Event end measures.

property lengths: ndarray | None

Event lengths. If the events are points, lengths are zero.

property centers: ndarray | None

Event centers. If the events are points, centers are the locations.

property num_events: int

Number of events.

property closed: str

Whether the ranges are closed on left, right, both, or neither side.

property closed_base: str

Base closed parameter without the ‘mod’ suffix.

property closed_mod: bool

Whether the closed parameter has modified edges.

property arr: ndarray
property is_linear: bool

Whether the events are linear.

property is_point: bool

Whether the events are points.

property is_located: bool

Whether the events are located.

property is_grouped: bool

Whether the events are grouped.

property is_monotonic: bool

Whether the events are all monotonic, increasing from begin to end position. If the events are points, they are always monotonic.

property is_empty: bool

Whether the collection is empty.

property anchors: list[str]

Get the anchor references for the events.

property modified_edges: ndarray

Get indexes of ranges with modified edges. Only applicable when self.closed in {‘left_mod’,’right_mod’}.

property unique_groups: ndarray | None

Get unique group values.

to_frame(index_name: str | None = None, group_name: str | list[str] | None = None, loc_name: str = 'loc', beg_name: str = 'beg', end_name: str = 'end') DataFrame[source]

Convert the collection to a pandas DataFrame.

Parameters:
  • index_name (str, optional) – Name for the index column in the DataFrame.

  • group_name (str, optional) – Name for the group column in the DataFrame.

  • loc_name (str, default 'loc') – Name for the location measure column in the DataFrame.

  • beg_name (str, default 'beg') – Name for the begin measure column in the DataFrame.

  • end_name (str, default 'end') – Name for the end measure column in the DataFrame.

Returns:

DataFrame representation of the events.

Return type:

pd.DataFrame

from_similar(index: ndarray | None = None, groups: ndarray | None = None, locs: ndarray | None = None, begs: ndarray | None = None, ends: ndarray | None = None, **kwargs) EventsData[source]

Create a new instance of the class with similar properties to the current instance.

Parameters:
  • index (np.ndarray, optional) – Event index for the new instance.

  • groups (np.ndarray, optional) – Event groups for the new instance.

  • locs (np.ndarray, optional) – Event locations for the new instance.

  • begs (np.ndarray, optional) – Event begin positions for the new instance.

  • ends (np.ndarray, optional) – Event end positions for the new instance.

  • **kwargs – Additional keyword arguments to pass to the new instance.

group_counts(*args, **kwargs)
copy(deep: bool = False) EventsData[source]

Create an exact copy of the object instance.

Parameters:

deep (bool, default False) – Whether the created copy should be a deep copy.

reset_index(inplace: bool = False) EventsData | None[source]

Reset the index to a generic 0-based index.

reset_locs(*args, **kwargs)
select(selector: ndarray | slice, ignore: bool = False, inplace: bool = False) EventsData | None[source]

Select events by index, slice, or boolean mask. Use ignore=True to use a generic, 0-based index, ignoring the current index values.

Parameters:
  • selector (array-like or slice) – Array-like of event indices, a boolean mask aligned to the events, or a slice object to select events.

  • ignore (bool, default False) – Whether to use a generic 0-based index, ignoring the current index values.

  • inplace (bool, default False) – Whether to perform the operation in place, returning None.

select_slice(slice_: slice, inplace: bool = False) EventsData | None[source]

Select events by slice.

Parameters:
  • slice (slice) – Slice object to select events.

  • inplace (bool, default False) – Whether to perform the operation in place, returning None.

select_group(group, ungroup: bool | None = None, ignore_missing: bool = True, inplace: bool = False) EventsData | None[source]

Select events by group.

Parameters:
  • group (label or array-like) – The label of the group to select or array-like of the same.

  • ungroup (bool, default None) – Whether to ungroup the selection, returning the selected events without their group labels. If None and a single group is selected, the result will be ungrouped otherwise the group labels will be retained.

  • ignore_missing (bool, default True) – Whether to ignore missing groups in the selection. If False, an error will be raised if any groups are not found in the collection. If True, missing groups will be ignored; in cases where no groups are found, an empty collection will be returned.

  • inplace (bool, default False) – Whether to perform the operation in place, returning None.

drop(mask: ndarray, inplace: bool = False) EventsData | None[source]

Drop events by boolean mask.

Parameters:
  • mask (array-like) – Boolean mask aligned to the events.

  • inplace (bool, default False) – Whether to perform the operation in place, returning None.

drop_group(group, inplace: bool = False) EventsData | None[source]

Drop events by group.

Parameters:
  • group (label or array-like) – The label of the group to drop or array-like of the same.

  • inplace (bool, default False) – Whether to perform the operation in place, returning None.

set_closed(closed: str | None = None, inplace: bool = False) EventsData | None[source]

Change whether ranges are closed on left, right, both, or neither side.

Parameters:
  • closed (str {'left', 'left_mod', 'right', 'right_mod', 'both',) – ‘neither’}, default ‘right’ Whether collection intervals are closed on the left-side, right-side, both or neither.

  • inplace (bool, default False) – Whether to perform the operation in place, returning None.

ungroup(inplace: bool = False) EventsData | None[source]

Remove group labels from the collection.

set_monotonic(*args, **kwargs)
argsort(by: str | list[str], ascending: bool | list[bool] = True) ndarray[source]
sort(by: str | list[str], ascending: bool | list[bool] = True, return_index: bool = False, inplace: bool = False) EventsData | tuple[EventsData, ndarray] | None[source]
sort_standard(return_index: bool = False, inplace: bool = False) EventsData | tuple[EventsData, ndarray] | None[source]

Sort the events by their positional information in the standard order of ‘groups’, ‘begs’, ‘ends’ for linear events and ‘groups’, ‘locs’ for point events.

Parameters:
  • return_index (bool, default False) – Whether to return an array of the indices which represent the performed sort in addition to the sorted events.

  • inplace (bool, default False) – Whether to perform the operation in place, returning None.

duplicated(subset: list[str] | None = None, keep: str = 'first') ndarray[source]

Return a boolean mask of duplicated events in terms of all or a selection of event anchors.

Parameters:
  • subset (array-like, default None) – Array-like of event anchors to use for duplicated comparison. If None, all event anchors are used.

  • keep ({'first', 'last', 'none'}, default 'first') – Whether to keep the first, last, or none of the duplicated events.

find_same(*args, **kwargs)
find_inside(*args, **kwargs)
next_same_group(all_: bool = True, when_one: bool = True) bool | ndarray[source]

Whether all or any ranges have the same group as the next range in the collection.

next_overlapping(all_: bool = True, when_one: bool = True, enforce_edges: bool = False) bool | ndarray[source]

Whether all or any ranges are overlapping the next range in the collection.

Parameters:
  • all (bool, default True) – Whether to aggregate all tests of overlapping ranges, returning a single boolean value. If True, will return True if all ranges are overlapping, False if any adjacent ranges are not overlapping. If False, will return an array of shape num_events - 1 of boolean values indicating whether each range is overlapping the next.

  • when_one (bool, default True) – The default boolean value to return when only one range is included in the collection.

  • enforce_edges (bool, default False) – Whether to consider ranges which have a common vertex as overlapping. This is independent of the collection’s closed state.

next_consecutive(*args, **kwargs)
consecutive_strings() ndarray[source]

Identify strings of consecutive events in the collection, returning an array of integers indicating which consecutive string each event belongs to.

iter_groups(*args, **kwargs)
iter_group_indices(*args, **kwargs)
separate(*args, **kwargs)
dissolve(*args, **kwargs)
resegment(*args, **kwargs)
relate(*args, **kwargs)
overlay(*args, **kwargs)
intersect(*args, **kwargs)
extend(distance: float | tuple | ndarray = 0, inplace: bool = False) EventsData | None[source]

Extend the range of events by a specified amount in either or both directions.

Parameters:
  • distance (float, array-like, or tuple, optional) – Amount to extend the event ranges. If a scalar or array-like is provided, it is applied equally to both the beginning and end of each event range. If a tuple of two values is provided, the first value extends the beginning and the second value extends the end. Positive values extend ranges outward, negative values contract ranges inward. Default is 0.

  • inplace (bool, default False) – Whether to perform the operation in place, returning None.

shift(distance: float | ndarray = 0, inplace: bool = False) EventsData | None[source]

Shift the range of events by a specified amount.

Parameters:
  • distance (float or array-like) – Amount to shift all events. If an array-like is provided, it must be the same length as the number of events in the collection. Positive values shift events to the right, negative values to the left.

  • inplace (bool, default False) – Whether to perform the operation in place, returning None.

round(decimals: int | None = None, factor: float | None = None, inplace: bool = False) EventsData | None[source]

Round the begin and end positions of the events to a specified number of decimals or to the nearest multiple of a specified factor.

Parameters:
  • decimals (int, optional) – Number of decimal places to round to. If not provided, the values will be rounded to the nearest integer.

  • factor (float, optional) – Round to the nearest multiple of this factor. If not provided, the values will be rounded to the nearest integer.

  • inplace (bool, default False) – Whether to perform the operation in place, returning None.

Events Subpackage

Extension Subpackage

Datasets

Toy datasets for linref examples and testing.

This module provides easy access to sample datasets demonstrating various linear referencing concepts and operations.

linref.datasets.load(name: str, set_lrs: bool = False) DataFrame | GeoDataFrame[source]

Load a toy dataset.

Available datasets: - ‘roadways’: Roadway linear events with geometry (10 segments) - ‘crashes’: Crash point events with geometry (20 crashes) - ‘pavement’: Pavement condition linear events (14 segments, no geometry)

Parameters:
  • name (str) – Name of the dataset to load. Options: ‘roadways’, ‘crashes’, ‘pavement’.

  • set_lrs (bool, default False) – Whether to automatically configure LRS on the loaded dataset. When True, configures LRS with standard column names (route, loc, beg, end, geometry, geometry_m, closed=’left_mod’).

Returns:

Dataset with or without LRS configured based on set_lrs parameter. Returns GeoDataFrame for datasets with geometry (roadways, crashes), DataFrame for others (pavement).

Return type:

DataFrame or GeoDataFrame

Examples

>>> import linref as lr
>>>
>>> # Load datasets without LRS (default)
>>> roads = lr.datasets.load('roadways')
>>>
>>> # Load with LRS pre-configured
>>> roads = lr.datasets.load('roadways', set_lrs=True)
>>> dissolved = roads.lr.dissolve(retain=['speed_limit'])
>>>
>>> # Or configure LRS manually
>>> roads = lr.datasets.load('roadways')
>>> roads = roads.lr.set_lrs(
...     key_col=['route'], beg_col='beg', end_col='end',
...     geom_col='geometry', closed='left_mod'
... )
linref.datasets.list_datasets() DataFrame[source]

List all available toy datasets with descriptions.

Returns:

Table with dataset names, types, and descriptions.

Return type:

DataFrame

Examples

>>> import linref as lr
>>> print(lr.datasets.list_datasets())