RAID documentation

Installation Guide

On a windows command cell copy the following :

git clone https://gitlab.com/bwtcreativetech/19029_raid_nr/tree/demo_test/docs
cd 19029_RAID_NR
conda create -n raid_env python=3.5
conda install --file requirements.txt

Getting Started

  • Navigate to flask_UI > info open the ipconfigFile.txt and change the value accordingly. For more information you can visit.

  • In the flask_UI directory and having your virtual env already activated run.

    start startUI.bat
    
  • You should see Flask running in a new command prompt window.You can visit your http//:localhost:4000 (default port) and use the UI.

User Guide

For the user guide, visit the user_guide section in GitLab repo.

Examples

For examples and demos, see the examples GitLab repo.

Grid Transformations

Collection of functions to operate

Grid Functions

raidnr.bwgrid.grid_transformations.array_to_tiff(fileName, nparray, bbox)[source]

Burn np.array to geoTiff.

References

https://gis.stackexchange.com/questions/37238/writing-numpy-array-to-raster-file

raidnr.bwgrid.grid_transformations.bng_to_wgs(center)[source]

Transfrom coordinates from BNG to WGS

Parameters

center (tupple) – format longitude, latitude

raidnr.bwgrid.grid_transformations.compute_distance_transform(target_layer, target=None)[source]

Distance transform algorithm implementation

Parameters
  • target_layer (nd.array) – An nd.array of shape (row_num,col_num). The raster layer that you need to compute the dt on.

  • target (array-like) – A tupple specifying the location of the target. Default value is None

Returns

  • distance_r (np.array) – An array of the same shape as the target_layer. Each element of the output array recieves as value, the distance to the closer element of the target_layer matrix.

  • m (dictionary) – A dictionary holding a vector of the slope for each cell.

raidnr.bwgrid.grid_transformations.coords_geo_to_raster(bbox, coords, pixels_size=3.0, to_int=True)[source]

Transfrom coordinates to raster row,col coords.

Parameters
  • bbox (array) – minx, miny, maxx, maxy

  • coords (tuple) – In format (long, lat)

raidnr.bwgrid.grid_transformations.distance_transform(world, movements, size=(3, 3), backward=False, debug=False)[source]

Implementation of the distance transform algorithm.

Parameters
  • world (np.array) – raster array

  • movements (dict) – dictionary to save the movement of the cells

  • backward (boolean) – perform backward scan, default is forward

  • debug (boolean) – debug the process with plots for every itteration

References

raidnr.bwgrid.grid_transformations.draw_UG_from_points(coordsX, coordsY, offset, ax, color)[source]

Draw UG given two lists for x,y coordinates of points.

Parameters
  • coordsX (list) –

  • coordsY (list) –

  • offset (the width of the grid cells) –

  • ax (ax of the plot) –

  • color (color for the lines of the grid) –

raidnr.bwgrid.grid_transformations.fill_zeros_elevation(elevation, plot=False)[source]

Fill elevation array averaging from the near values.

Parameters

elevation (array-like) – An array with values of elevation.

plotbool

Bool for plotting the results (deafault is true)

raidnr.bwgrid.grid_transformations.get_Bounds_FromShape(geopandasDf, copyDf=False)[source]

Get Bounding Box from a geopandas dataframe

Parameters

bui

raidnr.bwgrid.grid_transformations.get_UG_centroid_from_wgs(coords)[source]

wrapper for the get_UG_centroid_from_coords function.

Parameters

coords (array-like) – Coords in WGS (lat, long)

Returns

coords_ – Coord tupple in WGS (lat,long)

Return type

tupple

raidnr.bwgrid.grid_transformations.get_UG_grid_bounds(geopandasDf, corner_stone=[531087.2503762188, 181782.11191701167], offset=3, corners=False)[source]

Return the bounding box of a geoDataFrame in coordinates, alligned with the Universal Grid.

Parameters
  • geopadnasDf ((geopandas.DataFrame)) –

  • (list) (corner_stone) –

  • (int) (offset) –

  • (bool) (corners) –

raidnr.bwgrid.grid_transformations.get_cut_and_fills(len_alignment, alignment_elevation, step=1)[source]
Parameters
  • len_alignment (int) – Length of alignment

  • alignment_elevation – Elevation values of alignment.

Returns

cut,fill,tunnels,bridges – Indicies where cut and fills are needed or tunnels and bridges.

Return type

array-like

ydif : array-like

raidnr.bwgrid.grid_transformations.get_grid_from_directory(raster_path, raster_size=None)[source]

Construct cost surface from raster grids.

Parameters
  • raster_path (str) – folder path to rasters

  • raster_size (str) – Path to the directory where rasters are.

Returns

nd-array

Return type

terrain layered array containing the topography

raidnr.bwgrid.grid_transformations.get_rasters_size(path)[source]
raidnr.bwgrid.grid_transformations.raster_to_coords(bbox, raster_coords, pixel_size=3)[source]

Transfrom coordinates from raster to coords.

Parameters
  • bbox (array) – minx,maxx,miny,maxy

  • raster_coords (tuple) – In format (row,col)

Returns

Return type

tbc

raidnr.bwgrid.grid_transformations.rasterize_shape(filename, bbox, tifName='', attribute='')[source]

Burn shape to a raster defined by the input bbox.

Parameters
  • filename (str) – path to the .shp file

  • bbox (list) – bounding box for the raster [NWCorner_x, SECorner_y, SECorner_x, NWCorner_y]

  • tifName (str) – [optional]

raidnr.bwgrid.grid_transformations.reproject_tiff(input_file, output_file, to_crs='4326')[source]

Wrap for the GDAL.warp function

Parameters
  • input_file (str) – Path to input file .tif

  • ouput_file (str) – Path to ouput .tif

raidnr.bwgrid.grid_transformations.returnSquareCoords(centroid, width)[source]

Return list of coordinates (X,Y) for the corners of a square with center the given centroid.

Parameters
  • centroid (array) – [x,y]

  • width (float) – width of the cell

raidnr.bwgrid.grid_transformations.return_cost(topo_array, layerId, wx, wy, ksize=21)[source]

Return the sum of the cost at wx, wy positions, given a specifc kernel-size.

Parameters
  • topo_array (nd-array) –

  • array (terrain) –

  • layerID (int) –

  • to access the desired layer (index) –

  • wx (int or array-like) –

  • x-coordinates on the terrain (raster) –

  • wy (int or array-like) –

  • y-coordinates on the terrain (raster) –

  • ksize (int) –

  • size to sum the values. Must be an odd number (kernel) –

Returns

  • array

  • array of sum

raidnr.bwgrid.grid_transformations.return_grid_cp(startX, endX, startY, endY, offset)[source]

Generate and return the centroids of a grid given two sets of coordinates, that specify the bounding box of the grid.

Parameters
  • startX,endX (float) – horizontal coordinates

  • startY,endY (float) – vertical coordinates

  • offset (int) – width of the cells

raidnr.bwgrid.grid_transformations.return_plot_grid(sumarray, raster_coords, fileName='', w=20)[source]
raidnr.bwgrid.grid_transformations.tile_layers(tile_path, rasterPath)[source]
raidnr.bwgrid.grid_transformations.try_bounds(polygon)[source]

Extract bounding box for shapely polygon.

Parameters

polygon (shapely.geometry.Polygon) –

raidnr.bwgrid.grid_transformations.w3wGetCoordinates(w3w)[source]
Parameters
  • w3w (string) – w3w in the format of “word1.word2.word3”

  • of strings containing the what 3 words for a specific area. (List) –

raidnr.bwgrid.grid_transformations.w3wGetGrid(long, lat)[source]

Return the what3words grid id

Parameters

long (float) – coordinates in WGS84.

latfloat

coordinates in WGS84.

link to w3wGetCoordinates()

raidnr.bwgrid.grid_transformations.w3w_to_raster(w3w_list, bbox, fileName='', cost_surface='', w=20)[source]

Return the coresponding raster coordinates from a w3w location.

Parameters
  • w3w_list (list) – list of words eg. w3w_list=[‘apple’,’grid’,’row’]

  • bbox (list) – list containing [minx,maxx,miny,maxy]

raidnr.bwgrid.grid_transformations.wgs_to_bng(center)[source]

Project to BNG

Parameters

center (tupple) – format longitude, latitude

Grid Class

Core Functions

Alignment

Corridor

Frenet Frame

Rail Designer

Plane Class

class raidnr.core.plane.Plane(o, i, j, k, **kwargs)[source]
frame_triplet()[source]

Returns a (v1,v2,v3) of lines starting at the origin, of dimension 1.0

Speed Curve

raidnr.core.speed_curve.find_speed_curve(segments, speeds)[source]
raidnr.core.speed_curve.get_acceleration_curve()[source]
raidnr.core.speed_curve.interpolate_segment(distance, segment)[source]
raidnr.core.speed_curve.max_speed_before_braking(v0, v_final, smax)[source]
raidnr.core.speed_curve.s_to_reach_v(v0, v_final)[source]
raidnr.core.speed_curve.set_acceleration_curve(acc_x=[0, 17.8816, 20.1168, 22.352, 24.587, 26.822, 60], acc_y=[0.49, 0.24, 0.195, 0.156, 0.126, 0.12, 0.05], kind='linear')[source]

Set the kind of the interpolation for the acceleration curve

raidnr.core.speed_curve.v_given_s(v0, smax, braking=False)[source]

Manager

Design Manager

Remapper

class raidnr.manager.remapper.RemapperEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]
default(object)[source]

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this:

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    # Let the base class default method raise the TypeError
    return JSONEncoder.default(self, o)

Utility

Dashboards

raidnr.util.dashboards.to_mileage(pointLayer, line)[source]

Finds the mileage of each point that is part of a line

Parameters: pointLayer: geopandas geodataframe of point features line: shapely LineString

External Methods

raidnr.util.ext_methods.angle_deviation_3pt(p0, p1=array([0, 0]), p2=None)[source]

Compute angle (in degrees) for p0p1p2 corner

Parameters

p0,p1,p2,p3 (array-like) – points in the form of [x,y]

Returns

angle

Return type

float

raidnr.util.ext_methods.apply_circle(p1, p2, p3)[source]

Apply affine transformation to a circle sector to pass by three points

p1array-like

point on alignment 1

p2array-like

intersection point of tangents

p1array-like

point on alignment 2

Returns

array of points

Return type

array

raidnr.util.ext_methods.bezier(poly, s)[source]

Deprecated

ref: https://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html#spline-interpolation

raidnr.util.ext_methods.circle_3pt(A, B, C)[source]

Calculate a circple by three points.

Parameters
raidnr.util.ext_methods.circle_pts()[source]

(x-1)^2 + (y-1)^2 = 1

Returns

list of points of the circle sector (0 to pi/2/)

Return type

array

raidnr.util.ext_methods.concatenate_arrays(myarray)[source]
raidnr.util.ext_methods.distance_deviation_3pt(p1, p2, p)[source]

WIP

raidnr.util.ext_methods.distance_mask(dists, lim_dist, lim_n)[source]

Extract subsets of a list of distances, given a limit threshold. Used for

raidnr.util.ext_methods.ellipse_pts()[source]

(x-1)^2 + (y-1)^2 + 2cxy = 1 c = 1/2

ref1: https://math.stackexchange.com/questions/252368/defining-constructing-an-ellipse ref2: https://math.stackexchange.com/questions/2645689/what-is-the-parametric-equation-of-a-rotated-ellipse-given-the-angle-of-rotatio ref3: go to wolfram alpha, insert the equation and click on properties for the centre and radii

raidnr.util.ext_methods.extract_elevation(pt, dtm_grid, layer='DTM')[source]

Extract elevation of an alignment in relation to a DTM

Parameters
  • pt (numpy.array) – 3-d array in world coordinates

  • dtm_grid (raidnr.bwgrid.grid.Grid) – Grid object

  • layer (str) – [optional] the layer to extract from the grid. Note: this function can be used to extract other types of layers (e.g. Woodland)

Returns

average of the four closest values, weighted by distance ratios

Return type

float

raidnr.util.ext_methods.fetch_shp(shpPath, name)[source]

WIP

raidnr.util.ext_methods.filter_files(path, ext='shp', no_of_groups=None)[source]

Filter groups of files by extension. Useful to filter .shp

Parameters
  • path (str) – path to search files into

  • ext (str) – [optional] file extension. default=’.shp’

  • no_of_groups (int or None) – [optional] check that only n files exists with that extension (i.e. n groups)

Returns

file paths selected

Return type

list<str>

raidnr.util.ext_methods.group_files(fns)[source]

group files by filename. Useful for shapefiles

Parameters

fn (list<str>) – list of filenames

raidnr.util.ext_methods.interpolate_poly(linestring)[source]

Resample curve by interpolation.

Parameters
  • linestring (Shapely.geometry.LineString) – Polyline to interpolate

  • step_distance (float) – granularity on resampled, interpolated curve

Returns

  • np.array

  • link (https://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html#spline-interpolation)

raidnr.util.ext_methods.intersection(x1, y1, x2, y2)[source]

Intersections of curves.Computes the (x,y) locations where two curves intersect. The curves can be broken with NaNs or have vertical segments.

x,y=intersection(x1,y1,x2,y2)

Example

a, b = 1, 2 phi = np.linspace(3, 10, 100) x1 = a*phi - b*np.sin(phi) y1 = a - b*np.cos(phi) x2=phi y2=np.sin(phi)+2 x,y=intersection(x1,y1,x2,y2) plt.plot(x1,y1,c=’r’) plt.plot(x2,y2,c=’g’) plt.plot(x,y,’*k’) plt.show()

raidnr.util.ext_methods.line_intersection(line1, line2)[source]

Intersection between two lines

Parameters
  • line1 (array-like) – give two points as ((A_x,A_y),(B_x,B_y))

  • line2 (array-like) – give two points as ((A_x,A_y),(B_x,B_y))

Returns

  • tuple – intersection point as (x,y)

  • ref (https://stackoverflow.com/questions/20677795/how-do-i-compute-the-intersection-point-of-two-lines)

raidnr.util.ext_methods.list_files(path)[source]

List all files in a directory

Parameters

path (str) – folder path

raidnr.util.ext_methods.load_speed_limits(fileName, output_full_df=False)[source]

WIP

raidnr.util.ext_methods.max_var(poly)[source]

Given a polyline, finds the furthest point from the line constructed as (start-end)

Parameters

poly (numpy.array) – array (x,y[,z]) points

Returns

(index, distance) of the firthest point

Return type

tuple

raidnr.util.ext_methods.moving_average(a, n=3)[source]

Moving average of an array

Parameters

a (array-like) – array to calculate the moving average of

Returns

modified array

Return type

array

raidnr.util.ext_methods.pick_from_arrays(a1, a2, mask)[source]

Sukhbinder 5 April 2017 Based on: https://github.com/sukhbinder/intersection/blob/master/intersection.py

raidnr.util.ext_methods.points_from_spline(spline, u)[source]

Extract points at u parameters.

Parameters
  • spline (spline3d) – numpy spline function

  • u (list<float>) – parameters at which extract points

Returns

points along a spline

Return type

nd-array

raidnr.util.ext_methods.pt_dist_sq(pt1, pt2)[source]

Calculate the squared distance between two ND-points.

Parameters
  • pt1 (tuple) – initial point

  • pt2 (tuple) – final point

Returns

squared distance

Return type

float

raidnr.util.ext_methods.purge_poly(fn)[source]

Purge a collection of segments and build up one polyline as LineString object

Parameters

fn (str) – shapefile filename

Returns

re-assembled polyine

Return type

LineString

raidnr.util.ext_methods.reconstruct_poly(linestring, step_distance)[source]

Resample curve by interpolation.

Parameters
  • linestring (Shapely.geometry.LineString) – Polyline to interpolate

  • step_distance (float) – granularity on resampled, interpolated curve

Returns

  • np.array

  • link (https://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html#spline-interpolation)

raidnr.util.ext_methods.recover_homogenous_affine_transformation(p, p_prime)[source]

Find the unique homogeneous affine transformation that maps a set of 3 points to another set of 3 points in 3D space:

p_prime == np.dot(p, R) + t

where R is an unknown rotation matrix, t is an unknown translation vector, and p and p_prime are the original and transformed set of points stored as row vectors:

p = np.array((p1, p2, p3)) p_prime = np.array((p1_prime, p2_prime, p3_prime))

The result of this function is an augmented 4-by-4 matrix A that represents this affine transformation:

np.column_stack((p_prime, (1, 1, 1))) == np.dot(np.column_stack((p, (1, 1, 1))), A)

Source: https://math.stackexchange.com/a/222170 (robjohn)

raidnr.util.ext_methods.renderColorsForQuiver3d(colors)[source]

Used to fix the colors of a quiver 3d.

link: https://github.com/matplotlib/matplotlib/issues/8484

raidnr.util.ext_methods.repeatForEach(elements, times)[source]

link: https://github.com/matplotlib/matplotlib/issues/8484

raidnr.util.ext_methods.resample_poly(linestring, limit_distance, rmv_duplicates=True, tolerance=0.01)[source]

Resample a shapely.geometry.Linestring to avoid segments above a length threshold.

Parameters

linestring (shapely.geometry.Linestring) – the linestring to resample.

limit_distancefloat

maximum distance a segment can be.

rmv_duplicatesbool

remove duplicate points.

tolerance: float

distance below which two points are considered duplicates.

Returns

resampled Linestring object

Return type

shapely.geometry.Linestring

raidnr.util.ext_methods.resample_pts(pt1, pt2, n)[source]

Return a list of points in between two ND-points at equal distance.

Parameters
  • pt1 (tuple) – initial point

  • pt2 (tuple) – final point

Returns

pts

Return type

list<tuple>

raidnr.util.ext_methods.slope(X, Y)[source]

Calculate the slope as ratio 1:X meters and as percentage X: ndarray of the end distance of the segment with x gradient Y: ndarray of the gradient values of each segment

Returns ndarray of ratio and pct values of slope

raidnr.util.ext_methods.smoothen_poly(poly, tolerance, as_ratio=False)[source]

Simplify a polyline to not exceed a maximum distance from the input.

Parameters
  • poly (numpy.array) – a set of 2D or 3D points

  • tolerance (float) – maximum allowed distance

Returns

array (x,y[,z]) points

Return type

numpy.array

raidnr.util.ext_methods.snap_bbox(bbox, path=None)[source]

Snap a bounding box to the w3w grid

Parameters
  • bbox (array-like) – [min_x, min_y, max_x, max_y]

  • fn (str) – folder where to save the bbox shapefile

Returns

[min_x, min_y, max_x, max_y] snapped to the w3w grid

Return type

array-link

raidnr.util.ext_methods.speedOnDiffCant(R, cant_max=150, cant_small=100, cant_xsmall=50, cant_min=25, max_speed=200)[source]
raidnr.util.ext_methods.tangent_vector(pt, tan, unitize=True, mult=1.0)[source]

create a tangent vector from a point and a direction.

Parameters
  • pt (numpy.array) – vector application point

  • tan (numpy.array) – vector

Returns

(start, end) positions, where start and end are (x,y[,z]) arrays

Return type

numpy.array

raidnr.util.ext_methods.transform_pt(point, trans_mat)[source]

Apply affine matrix to points

Parameters
  • points (array-like) – array of points as [x,y,z]

  • trans_mat (array-like) – affine transformation matrix. Use recover_homogenous_affine_transformation from this module to retrieve a transformation matrix from two sets of three points

Least Cost Path

raidnr.util.least_cost_path.generateWorld(shape=(100, 100))[source]

Random noise surface cost.

Parameters

shape (tupple) – Shape of the cost surface

Returns

Surface cost, weights >0

Return type

world

raidnr.util.least_cost_path.get_least_cost(world, origin, destination, plot=False, ax=None)[source]

Uses the route_through_array function of skiimage, to compute a least_cost path in a raster.

Parameters
  • destination (origin,) – Coordinates of the origin, destination. Since the cost surface is in a np.array use (y,x) instead of (x,y)

  • plot (bool) – Returns plot of the path if path= True

Returns

path – Array of the least cost path.

Return type

np.array

Spatial Toolbox

raidnr.util.SpatialToolbox.Assets(PATH_OS, a, FNAME_BUFFER)[source]

PATH_OS: Path to the folder where all input layers are stored a: shapely.LineString of the alignment FNAME_BUFFER: the path to the buffer csv

raidnr.util.SpatialToolbox.OneLine(line_gdf)[source]

The function takes as an input a geopandas geo-dataframe with multiple LineStrings that make a network to a unified LineString. The output of the function is a geo-dataframe

Keyword arguments: line_gdf - geopandas geo-dataframe of multiple LineStrings

raidnr.util.SpatialToolbox.SingleSidedBuffer(line, dist, side)[source]

This function creates single sided buffer for left or down side (depending on the orientation of the line) of a LineString.

Result is a shapely.Polygon

Parameters
  • line (a shapely.LineString object) –

  • dist (the buffer distance | based on the units of the line's CRS) –

  • side (a string defining the side towrds which the buffer will be created | values: 'left'/'right'/'both') –

raidnr.util.SpatialToolbox.bng_to_3857(center)[source]

Transfrom coordinates from BNG to WGS

Parameters

center (tuple) –

Returns

Return type

tuple

raidnr.util.SpatialToolbox.bng_to_wgs(center)[source]

Transfrom coordinates from BNG to WGS

Parameters

center (tuple) –

Returns

Return type

tuple

raidnr.util.SpatialToolbox.bufferShp(bf, clippedPath, outputPath)[source]

Takes as input a series of shapefiles and applies a buffer zone based on a csv file. The geometries are dissolved and saved in an output folder location.

Parameters
  • bf (pd.DataFrame) – buffer distances

  • clippedPath (str) – folder path where all shapefiles are stored

  • outPath (str) – the folder where result layers will be stored

Returns

Return type

None

raidnr.util.SpatialToolbox.circuity_area(shape, origin, destination, gmax, fill_value=1.0)[source]

Calculate circuity

Parameters
  • shape (tuple) – (i,j) shape of the raster

  • gmax (float) – maximum circuity

  • origin (tuple) – origin point

  • destination (tuple) – destination point

  • fill_value (float) – [optional] default=0. value to assign to points outside of allowed circuity

raidnr.util.SpatialToolbox.clipGPD(inputFile, bbox)[source]

Workaround clipping problems using geopandas. https://gis.stackexchange.com/questions/280535/known-intersecting-polygons-returning-false-for-intersects-in-geopandas

Parameters
  • inputFile (geodataFrame) – File to be clipped

  • bbox (geodataFrame) – Bounding box to clip the inputFile

Returns

clipped_file – Clipped file

Return type

geodataFrame

raidnr.util.SpatialToolbox.clipOGR(bboxFile, filePath, outputFile)[source]

Clipping function using ogr

Parameters
  • bboxFile (str) – Path to the bbox.shp file

  • filePath (str) – Path for the shp to be clipped

  • outputFile (str) – Path to the clipped .shp

Returns

Return type

None

raidnr.util.SpatialToolbox.clipShp(contextPath, clippedPath, bboxFile)[source]

Takes as input a series of shapefiles in a folder clips them to a bbox. Returns a series of clipped shapefiles.

Parameters
  • contextPath (str) – the path of the folder where shapefiles are stored

  • clippedPath (str) – the path of the folder where the result shapefiles will be stored

  • bboxFile (str) – the path of the bbox.shp

Returns

Return type

None

raidnr.util.SpatialToolbox.clip_polyLines(bboxFile, filePath, outputFile)[source]

Function for clipping lines within a polygon object from: https://www.earthdatascience.org/courses/earth-analytics-python/spatial-data-vector-shapefiles/clip-vector-data-in-python-geopandas-shapely/

Keyword arguments: lineLayer–geopandas geodataframe of Line geometry clipLayer–geopandas geodataframe of Polygon geometry

raidnr.util.SpatialToolbox.clip_polyPoints(pointLayer, clipLayer)[source]

Return a geopandas.GeoDataFrame with only the points that fall within a specified Polygon

Parameters
  • pointLayer (geopandas.GeoDataFrame of Point features) –

  • clipLayer (shapely.Polygon) –

raidnr.util.SpatialToolbox.clip_polyPolygons(gdf, clipLayer)[source]
raidnr.util.SpatialToolbox.clip_raster(bbox, raster, raster_out)[source]

Parameters:

bbox: str

path to the bbox shapefile

raster: str

path to the raster file to be clipped

raster_out: str

path to the clipped raster

Returns

.tif file clipped to the given bounding box

raidnr.util.SpatialToolbox.cut(line, distance)[source]

Cuts a line in two at a distance from its starting point

This is taken from shapely manual

raidnr.util.SpatialToolbox.cut_line_at_points(line, points)[source]

cut line at multiple points

Parameters
  • line (shapely LineString) – line to cut

  • points (shapely points) – points to cut the line with

Returns

cut lines

Return type

shapely LineString

raidnr.util.SpatialToolbox.fill_gaps(elevation, max_distance=100)[source]

Fills gaps in SRTM elevation data for which the distance from missing pixel to nearest existing one is smaller than max_distance.

elevationnumpy.ndarray

SRTM elevation data (in meters)

max_distance: int

maximal distance (in pixels) between a missing point

Returns

elevation – SRTM elevation data with filled gaps

Return type

numpy.ndarray

raidnr.util.SpatialToolbox.fromCoordsToBbox(minx, miny, maxx, maxy, savePath, dist=50)[source]
raidnr.util.SpatialToolbox.fromMultiToSimpleGeometry(gdf)[source]
raidnr.util.SpatialToolbox.get_clipping_bounds(bbox, raster)[source]
raster: str

raster path | C:raster

aster.tif

bboxstr

bbox shp path | C:bboxbox.shp

coordinates of the bounding box

raidnr.util.SpatialToolbox.plot_metrics_basemap(self, plotTitle, metric, fn)[source]

plotTitle: string - title of the plot metric: np.array

raidnr.util.SpatialToolbox.select_segment(orig_pt, dest_pt, line)[source]
Parameters
  • orig_pt (shapely Point) – start of the segment | should be part of the segment

  • dest_pt (shapely Point) – end of the segment | should be part of the segment

  • line (shapely LineString) – subsegment

Returns

Return type

shapely LineString

raidnr.util.SpatialToolbox.shapeID(gdf)[source]

Creates a geo dataframe that contains only the geometry and a custom ID

Parameters

gdf (geopandas geodataframe) – gdf

Returns

Return type

geopandas geodataframe

raidnr.util.SpatialToolbox.snap_points(pointLayer, Line)[source]

This function takes as input a geodatframe of points and snaps the points to a LineString geodataframe.

NOTE: The Line GeoDataFrame should be one unique line, meaning that len(Line)=0

The function returns the original point geodataframe but with the geometry column being replaced by the snapped point coordinates.

pointLayer– geopandas GeoDataFrame of ‘Point’ geometry Line– geopandas GeoDataFrame of ‘LineString’ geometry

raidnr.util.SpatialToolbox.speed_pts_to_segs(speed_pt, alignment, track_id, bf_dist=20.0)[source]
Parameters
  • speed_pt (str or shapely Point/MultiPoint series) – shapefile filename or shapely geometry of speed points

  • alignment (ALignment or LineString) – alignment

  • track_id (int) – track id

raidnr.util.SpatialToolbox.split_line_with_points(line, points)[source]

Splits a line string in several segments considering a list of points.

The points used to cut the line are assumed to be in the line string and given in the order of appearance they have in the line string.

Parameters
  • line (shapely LineString) – line

  • points (shapely points) – points

Returns

  • shapely LineString

  • >>> line = LineString( [(1,2), (8,7), (4,5), (2,4), (4,7), (8,5), (9,18),

  • … (1,2),(12,7),(4,5),(6,5),(4,9)] )

  • >>> points = [Point(2,4), Point(9,18), Point(6,5)]

  • >>> [str(s) for s in split_line_with_points(line, points)]

  • [‘LINESTRING (1 2, 8 7, 4 5, 2 4)’, ‘LINESTRING (2 4, 4 7, 8 5, 9 18)’, ‘LINESTRING (9 18, 1 2, 12 7, 4 5, 6 5)’, ‘LINESTRING (6 5, 4 9)’]

raidnr.util.SpatialToolbox.translate_raster(inputfile, outputfile)[source]

Parameters:

inputfile: str

path and file name of the .asc file to convert

outputfile: str

path and file for the created .tif file

Returns

.tif file

raidnr.util.SpatialToolbox.wgs_to_bng(center)[source]

Project to BNG

Parameters

center (tuple) –

Returns

Return type

tuple

Vertical Alignment

raidnr.util.vertical_alignment.airline_dist(startX, startY, endX, endY, x, y)[source]

Compute the airline distances between each grid cell and the origin & destination of the path.

Parameters
  • startY (startX,) – the position of the origin in the array (index)

  • endY (endX,) – the position of the destination in the array (index)

  • X (the row index of all grid cells) –

  • Y (the column index of all grid cells) –

raidnr.util.vertical_alignment.evaluate_circuity(circuity, gmax=4)[source]

Circuity is given by: (Ls + Le)/Lse Where: - Ls,Le is the distance between the cell and the start & end point of the alignment, respectively - Lse: the distance between the start & end cells of the alignment

Indices and tables