Skip to content

utilities module

add_crs(filename, epsg)

Add a CRS to a raster dataset.

Parameters:

Name Type Description Default
filename str

The filename of the raster dataset.

required
epsg int | str

The EPSG code of the CRS.

required
Source code in lidar/common.py
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
def add_crs(filename, epsg):
    """Add a CRS to a raster dataset.

    Args:
        filename (str): The filename of the raster dataset.
        epsg (int | str): The EPSG code of the CRS.

    """
    try:
        import rasterio
    except ImportError:
        raise ImportError(
            "rasterio is required for adding a CRS to a raster. Please install it using 'pip install rasterio'."
        )

    if not os.path.exists(filename):
        raise ValueError("filename must exist.")

    if isinstance(epsg, int):
        epsg = f"EPSG:{epsg}"
    elif isinstance(epsg, str):
        epsg = "EPSG:" + epsg
    else:
        raise ValueError("epsg must be an integer or string.")

    crs = rasterio.crs.CRS({"init": epsg})
    with rasterio.open(filename, mode="r+") as src:
        src.crs = crs

check_file_path(file_path, make_dirs=True)

Gets the absolute file path.

Parameters:

Name Type Description Default
file_path str

The path to the file.

required
make_dirs bool

Whether to create the directory if it does not exist. Defaults to True.

True

Raises:

Type Description
FileNotFoundError

If the directory could not be found.

TypeError

If the input directory path is not a string.

Returns:

Name Type Description
str

The absolute path to the file.

Source code in lidar/common.py
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
def check_file_path(file_path, make_dirs=True):
    """Gets the absolute file path.

    Args:
        file_path (str): The path to the file.
        make_dirs (bool, optional): Whether to create the directory if it does not exist. Defaults to True.

    Raises:
        FileNotFoundError: If the directory could not be found.
        TypeError: If the input directory path is not a string.

    Returns:
        str: The absolute path to the file.
    """
    if isinstance(file_path, str):
        if file_path.startswith("~"):
            file_path = os.path.expanduser(file_path)
        else:
            file_path = os.path.abspath(file_path)

        file_dir = os.path.dirname(file_path)
        if not os.path.exists(file_dir) and make_dirs:
            os.makedirs(file_dir)

        return file_path

    else:
        raise TypeError("The provided file path must be a string.")

check_install(package)

Checks whether a package is installed. If not, it will install the package.

Parameters:

Name Type Description Default
package str

The name of the package to check.

required
Source code in lidar/common.py
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
def check_install(package):
    """Checks whether a package is installed. If not, it will install the package.

    Args:
        package (str): The name of the package to check.
    """
    import subprocess

    try:
        __import__(package)
        # print('{} is already installed.'.format(package))
    except ImportError:
        print("{} is not installed. Installing ...".format(package))
        try:
            subprocess.check_call(["python", "-m", "pip", "install", package])
        except Exception as e:
            print("Failed to install {}".format(package))
            print(e)
        print("{} has been installed successfully.".format(package))

clip_image(image, mask, output)

Clip an image by mask.

Parameters:

Name Type Description Default
image str

Path to the image file in GeoTIFF format.

required
mask str | list | dict

The mask used to extract the image. It can be a path to vector datasets (e.g., GeoJSON, Shapefile), a list of coordinates, or m.user_roi.

required
output str

Path to the output file.

required

Raises:

Type Description
ImportError

If the fiona or rasterio package is not installed.

FileNotFoundError

If the image is not found.

ValueError

If the mask is not a valid GeoJSON or raster file.

FileNotFoundError

If the mask file is not found.

Source code in lidar/common.py
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
def clip_image(image, mask, output):
    """Clip an image by mask.

    Args:
        image (str): Path to the image file in GeoTIFF format.
        mask (str | list | dict): The mask used to extract the image. It can be a path to vector datasets (e.g., GeoJSON, Shapefile), a list of coordinates, or m.user_roi.
        output (str): Path to the output file.

    Raises:
        ImportError: If the fiona or rasterio package is not installed.
        FileNotFoundError: If the image is not found.
        ValueError: If the mask is not a valid GeoJSON or raster file.
        FileNotFoundError: If the mask file is not found.
    """
    import json

    try:
        import fiona
        import rasterio
        import rasterio.mask
    except ImportError as e:
        raise ImportError(e)

    if not os.path.exists(image):
        raise FileNotFoundError(f"{image} does not exist.")

    if not output.endswith(".tif"):
        raise ValueError("Output must be a tif file.")

    output = check_file_path(output)

    if isinstance(mask, str):
        if mask.startswith("http"):
            mask = download_file(mask, output)
        if not os.path.exists(mask):
            raise FileNotFoundError(f"{mask} does not exist.")
    elif isinstance(mask, list) or isinstance(mask, dict):

        if isinstance(mask, list):
            geojson = {
                "type": "FeatureCollection",
                "features": [
                    {
                        "type": "Feature",
                        "properties": {},
                        "geometry": {"type": "Polygon", "coordinates": [mask]},
                    }
                ],
            }
        else:
            geojson = {
                "type": "FeatureCollection",
                "features": [mask],
            }
        mask = temp_file_path(".geojson")
        with open(mask, "w") as f:
            json.dump(geojson, f)

    with fiona.open(mask, "r") as shapefile:
        shapes = [feature["geometry"] for feature in shapefile]

    with rasterio.open(image) as src:
        out_image, out_transform = rasterio.mask.mask(src, shapes, crop=True)
        out_meta = src.meta

    out_meta.update(
        {
            "driver": "GTiff",
            "height": out_image.shape[1],
            "width": out_image.shape[2],
            "transform": out_transform,
        }
    )

    with rasterio.open(output, "w", **out_meta) as dest:
        dest.write(out_image)

clone_repo(out_dir='.', unzip=True)

Clones the lidar GitHub repository.

Parameters:

Name Type Description Default
out_dir str

Output folder for the repo. Defaults to '.'.

'.'
unzip bool

Whether to unzip the repository. Defaults to True.

True
Source code in lidar/common.py
315
316
317
318
319
320
321
322
323
324
def clone_repo(out_dir=".", unzip=True):
    """Clones the lidar GitHub repository.

    Args:
        out_dir (str, optional): Output folder for the repo. Defaults to '.'.
        unzip (bool, optional): Whether to unzip the repository. Defaults to True.
    """
    url = "https://github.com/opengeos/lidar/archive/master.zip"
    filename = "lidar-master.zip"
    download_from_url(url, out_file_name=filename, out_dir=out_dir, unzip=unzip)

convert_lidar(source, destination=None, point_format_id=None, file_version=None, **kwargs)

Converts a Las from one point format to another Automatically upgrades the file version if source file version is not compatible with the new point_format_id

Parameters:

Name Type Description Default
source str | LasBase

The source data to be converted.

required
destination str

The destination file path. Defaults to None.

None
point_format_id int

The new point format id (the default is None, which won't change the source format id).

None
file_version str

The new file version. None by default which means that the file_version may be upgraded for compatibility with the new point_format. The file version will not be downgraded.

None

Returns:

Type Description

aspy.lasdatas.base.LasBase: The converted LasData object.

Source code in lidar/common.py
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
def convert_lidar(
    source, destination=None, point_format_id=None, file_version=None, **kwargs
):
    """Converts a Las from one point format to another Automatically upgrades the file version if source file version
        is not compatible with the new point_format_id

    Args:
        source (str | laspy.lasdatas.base.LasBase): The source data to be converted.
        destination (str, optional): The destination file path. Defaults to None.
        point_format_id (int, optional): The new point format id (the default is None, which won't change the source format id).
        file_version (str, optional): The new file version. None by default which means that the file_version may be upgraded
            for compatibility with the new point_format. The file version will not be downgraded.

    Returns:
        aspy.lasdatas.base.LasBase: The converted LasData object.
    """
    try:
        import laspy
    except ImportError:
        print(
            "The laspy package is required for this function. Use `pip install laspy[lazrs,laszip]` to install it."
        )
        return

    if isinstance(source, str):
        source = read_lidar(source)

    las = laspy.convert(
        source, point_format_id=point_format_id, file_version=file_version
    )

    if destination is None:
        return las
    else:
        destination = check_file_path(destination)
        write_lidar(las, destination, **kwargs)
        return destination

csv_points_to_shp(in_csv, out_shp, latitude='latitude', longitude='longitude')

Converts a csv file containing points (latitude, longitude) into a shapefile.

Parameters:

Name Type Description Default
in_csv str

File path or HTTP URL to the input csv file. For example, https://raw.githubusercontent.com/giswqs/data/main/world/world_cities.csv

required
out_shp str

File path to the output shapefile.

required
latitude str

Column name for the latitude column. Defaults to 'latitude'.

'latitude'
longitude str

Column name for the longitude column. Defaults to 'longitude'.

'longitude'
Source code in lidar/common.py
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
def csv_points_to_shp(in_csv, out_shp, latitude="latitude", longitude="longitude"):
    """Converts a csv file containing points (latitude, longitude) into a shapefile.

    Args:
        in_csv (str): File path or HTTP URL to the input csv file. For example, https://raw.githubusercontent.com/giswqs/data/main/world/world_cities.csv
        out_shp (str): File path to the output shapefile.
        latitude (str, optional): Column name for the latitude column. Defaults to 'latitude'.
        longitude (str, optional): Column name for the longitude column. Defaults to 'longitude'.

    """
    import whitebox

    if in_csv.startswith("http") and in_csv.endswith(".csv"):
        out_dir = os.path.join(os.path.expanduser("~"), "Downloads")
        out_name = os.path.basename(in_csv)

        if not os.path.exists(out_dir):
            os.makedirs(out_dir)
        download_from_url(in_csv, out_dir=out_dir)
        in_csv = os.path.join(out_dir, out_name)

    wbt = whitebox.WhiteboxTools()
    in_csv = os.path.abspath(in_csv)
    out_shp = os.path.abspath(out_shp)

    if not os.path.exists(in_csv):
        raise Exception("The provided csv file does not exist.")

    with open(in_csv, encoding="utf-8") as csv_file:
        reader = csv.DictReader(csv_file)
        fields = reader.fieldnames
        xfield = fields.index(longitude)
        yfield = fields.index(latitude)

    wbt.csv_points_to_vector(in_csv, out_shp, xfield=xfield, yfield=yfield, epsg=4326)

csv_to_shp(in_csv, out_shp, latitude='latitude', longitude='longitude')

Converts a csv file with latlon info to a point shapefile.

Parameters:

Name Type Description Default
in_csv str

The input csv file containing longitude and latitude columns.

required
out_shp str

The file path to the output shapefile.

required
latitude str

The column name of the latitude column. Defaults to 'latitude'.

'latitude'
longitude str

The column name of the longitude column. Defaults to 'longitude'.

'longitude'
Source code in lidar/common.py
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
def csv_to_shp(in_csv, out_shp, latitude="latitude", longitude="longitude"):
    """Converts a csv file with latlon info to a point shapefile.

    Args:
        in_csv (str): The input csv file containing longitude and latitude columns.
        out_shp (str): The file path to the output shapefile.
        latitude (str, optional): The column name of the latitude column. Defaults to 'latitude'.
        longitude (str, optional): The column name of the longitude column. Defaults to 'longitude'.
    """
    import csv
    import shapefile as shp

    if in_csv.startswith("http") and in_csv.endswith(".csv"):
        out_dir = os.path.join(os.path.expanduser("~"), "Downloads")
        out_name = os.path.basename(in_csv)

        if not os.path.exists(out_dir):
            os.makedirs(out_dir)
        download_from_url(in_csv, out_dir=out_dir)
        in_csv = os.path.join(out_dir, out_name)

    out_dir = os.path.dirname(out_shp)
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)

    try:
        points = shp.Writer(out_shp, shapeType=shp.POINT)
        with open(in_csv, encoding="utf-8") as csvfile:
            csvreader = csv.DictReader(csvfile)
            header = csvreader.fieldnames
            [points.field(field) for field in header]
            for row in csvreader:
                points.point((float(row[longitude])), (float(row[latitude])))
                points.record(*tuple([row[f] for f in header]))

        out_prj = out_shp.replace(".shp", ".prj")
        with open(out_prj, "w") as f:
            prj_str = 'GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.0174532925199433]] '
            f.write(prj_str)

    except Exception as e:
        print(e)

download_file(url=None, output=None, quiet=False, proxy=None, speed=None, use_cookies=True, verify=True, id=None, fuzzy=False, resume=False, unzip=True, overwrite=False)

Download a file from URL, including Google Drive shared URL.

Parameters:

Name Type Description Default
url str

Google Drive URL is also supported. Defaults to None.

None
output str

Output filename. Default is basename of URL.

None
quiet bool

Suppress terminal output. Default is False.

False
proxy str

Proxy. Defaults to None.

None
speed float

Download byte size per second (e.g., 256KB/s = 256 * 1024). Defaults to None.

None
use_cookies bool

Flag to use cookies. Defaults to True.

True
verify bool | str

Either a bool, in which case it controls whether the server's TLS certificate is verified, or a string, in which case it must be a path to a CA bundle to use. Default is True.. Defaults to True.

True
id str

Google Drive's file ID. Defaults to None.

None
fuzzy bool

Fuzzy extraction of Google Drive's file Id. Defaults to False.

False
resume bool

Resume the download from existing tmp file if possible. Defaults to False.

False
unzip bool

Unzip the file. Defaults to True.

True
overwrite bool

Overwrite the file if it already exists. Defaults to False.

False

Returns:

Name Type Description
str

The output file path.

Source code in lidar/common.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
def download_file(
    url=None,
    output=None,
    quiet=False,
    proxy=None,
    speed=None,
    use_cookies=True,
    verify=True,
    id=None,
    fuzzy=False,
    resume=False,
    unzip=True,
    overwrite=False,
):
    """Download a file from URL, including Google Drive shared URL.

    Args:
        url (str, optional): Google Drive URL is also supported. Defaults to None.
        output (str, optional): Output filename. Default is basename of URL.
        quiet (bool, optional): Suppress terminal output. Default is False.
        proxy (str, optional): Proxy. Defaults to None.
        speed (float, optional): Download byte size per second (e.g., 256KB/s = 256 * 1024). Defaults to None.
        use_cookies (bool, optional): Flag to use cookies. Defaults to True.
        verify (bool | str, optional): Either a bool, in which case it controls whether the server's TLS certificate is verified, or a string, in which case it must be a path to a CA bundle to use. Default is True.. Defaults to True.
        id (str, optional): Google Drive's file ID. Defaults to None.
        fuzzy (bool, optional): Fuzzy extraction of Google Drive's file Id. Defaults to False.
        resume (bool, optional): Resume the download from existing tmp file if possible. Defaults to False.
        unzip (bool, optional): Unzip the file. Defaults to True.
        overwrite (bool, optional): Overwrite the file if it already exists. Defaults to False.

    Returns:
        str: The output file path.
    """

    import gdown

    if output is None:
        if isinstance(url, str) and url.startswith("http"):
            output = os.path.basename(url)

    if isinstance(url, str):
        if os.path.exists(os.path.abspath(output)) and (not overwrite):
            print(
                f"{output} already exists. Skip downloading. Set overwrite=True to overwrite."
            )
            return os.path.abspath(output)
        else:
            url = github_raw_url(url)

    if "https://drive.google.com/file/d/" in url:
        fuzzy = True

    output = gdown.download(
        url, output, quiet, proxy, speed, use_cookies, verify, id, fuzzy, resume
    )

    if unzip and output.endswith(".zip"):

        with zipfile.ZipFile(output, "r") as zip_ref:
            if not quiet:
                print("Extracting files...")
            zip_ref.extractall(os.path.dirname(output))

    return os.path.abspath(output)

download_folder(url=None, id=None, output=None, quiet=False, proxy=None, speed=None, use_cookies=True, remaining_ok=False)

Downloads the entire folder from URL.

Parameters:

Name Type Description Default
url str

URL of the Google Drive folder. Must be of the format 'https://drive.google.com/drive/folders/{url}'. Defaults to None.

None
id str

Google Drive's folder ID. Defaults to None.

None
output str

String containing the path of the output folder. Defaults to current working directory.

None
quiet bool

Suppress terminal output. Defaults to False.

False
proxy str

Proxy. Defaults to None.

None
speed float

Download byte size per second (e.g., 256KB/s = 256 * 1024). Defaults to None.

None
use_cookies bool

Flag to use cookies. Defaults to True.

True
resume bool

Resume the download from existing tmp file if possible. Defaults to False.

required

Returns:

Name Type Description
list

List of files downloaded, or None if failed.

Source code in lidar/common.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
def download_folder(
    url=None,
    id=None,
    output=None,
    quiet=False,
    proxy=None,
    speed=None,
    use_cookies=True,
    remaining_ok=False,
):
    """Downloads the entire folder from URL.

    Args:
        url (str, optional): URL of the Google Drive folder. Must be of the format 'https://drive.google.com/drive/folders/{url}'. Defaults to None.
        id (str, optional): Google Drive's folder ID. Defaults to None.
        output (str, optional):  String containing the path of the output folder. Defaults to current working directory.
        quiet (bool, optional): Suppress terminal output. Defaults to False.
        proxy (str, optional): Proxy. Defaults to None.
        speed (float, optional): Download byte size per second (e.g., 256KB/s = 256 * 1024). Defaults to None.
        use_cookies (bool, optional): Flag to use cookies. Defaults to True.
        resume (bool, optional): Resume the download from existing tmp file if possible. Defaults to False.

    Returns:
        list: List of files downloaded, or None if failed.
    """
    import gdown

    files = gdown.download_folder(
        url, id, output, quiet, proxy, speed, use_cookies, remaining_ok
    )
    return files

download_from_gdrive(gfile_url, file_name, out_dir='.', unzip=True, verbose=True)

Download a file shared via Google Drive (e.g., https://drive.google.com/file/d/18SUo_HcDGltuWYZs1s7PpOmOq_FvFn04/view?usp=sharing)

Parameters:

Name Type Description Default
gfile_url str

The Google Drive shared file URL

required
file_name str

The output file name to use.

required
out_dir str

The output directory. Defaults to '.'.

'.'
unzip bool

Whether to unzip the output file if it is a zip file. Defaults to True.

True
verbose bool

Whether to display or not the output of the function

True
Source code in lidar/common.py
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
def download_from_gdrive(gfile_url, file_name, out_dir=".", unzip=True, verbose=True):
    """Download a file shared via Google Drive
       (e.g., https://drive.google.com/file/d/18SUo_HcDGltuWYZs1s7PpOmOq_FvFn04/view?usp=sharing)

    Args:
        gfile_url (str): The Google Drive shared file URL
        file_name (str): The output file name to use.
        out_dir (str, optional): The output directory. Defaults to '.'.
        unzip (bool, optional): Whether to unzip the output file if it is a zip file. Defaults to True.
        verbose (bool, optional): Whether to display or not the output of the function
    """
    try:
        from google_drive_downloader import GoogleDriveDownloader as gdd
    except ImportError:
        print("GoogleDriveDownloader package not installed. Installing ...")
        subprocess.check_call(
            ["python", "-m", "pip", "install", "googledrivedownloader"]
        )
        from google_drive_downloader import GoogleDriveDownloader as gdd

    file_id = gfile_url.split("/")[5]
    if verbose:
        print("Google Drive file id: {}".format(file_id))

    dest_path = os.path.join(out_dir, file_name)
    gdd.download_file_from_google_drive(file_id, dest_path, True, unzip)

    return

download_from_url(url, out_file_name=None, out_dir='.', unzip=True, verbose=True)

Download a file from a URL (e.g., https://github.com/giswqs/whitebox/raw/master/examples/testdata.zip)

Parameters:

Name Type Description Default
url str

The HTTP URL to download.

required
out_file_name str

The output file name to use. Defaults to None.

None
out_dir str

The output directory to use. Defaults to '.'.

'.'
unzip bool

Whether to unzip the downloaded file if it is a zip file. Defaults to True.

True
verbose bool

Whether to display or not the output of the function

True
Source code in lidar/common.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
def download_from_url(url, out_file_name=None, out_dir=".", unzip=True, verbose=True):
    """Download a file from a URL (e.g., https://github.com/giswqs/whitebox/raw/master/examples/testdata.zip)

    Args:
        url (str): The HTTP URL to download.
        out_file_name (str, optional): The output file name to use. Defaults to None.
        out_dir (str, optional): The output directory to use. Defaults to '.'.
        unzip (bool, optional): Whether to unzip the downloaded file if it is a zip file. Defaults to True.
        verbose (bool, optional): Whether to display or not the output of the function
    """
    in_file_name = os.path.basename(url)

    if out_file_name is None:
        out_file_name = in_file_name
    out_file_path = os.path.join(os.path.abspath(out_dir), out_file_name)

    if verbose:
        print("Downloading {} ...".format(url))

    try:
        urllib.request.urlretrieve(url, out_file_path)
    except Exception:
        raise Exception("The URL is invalid. Please double check the URL.")

    final_path = out_file_path

    if unzip:
        # if it is a zip file
        if ".zip" in out_file_name:
            if verbose:
                print("Unzipping {} ...".format(out_file_name))
            with zipfile.ZipFile(out_file_path, "r") as zip_ref:
                zip_ref.extractall(out_dir)
            final_path = os.path.join(
                os.path.abspath(out_dir), out_file_name.replace(".zip", "")
            )

        # if it is a tar file
        if ".tar" in out_file_name:
            if verbose:
                print("Unzipping {} ...".format(out_file_name))
            with tarfile.open(out_file_path, "r") as tar_ref:

                def is_within_directory(directory, target):

                    abs_directory = os.path.abspath(directory)
                    abs_target = os.path.abspath(target)

                    prefix = os.path.commonprefix([abs_directory, abs_target])

                    return prefix == abs_directory

                def safe_extract(tar, path=".", members=None, *, numeric_owner=False):

                    for member in tar.getmembers():
                        member_path = os.path.join(path, member.name)
                        if not is_within_directory(path, member_path):
                            raise Exception("Attempted Path Traversal in Tar File")

                    tar.extractall(path, members, numeric_owner=numeric_owner)

                safe_extract(tar_ref, out_dir)
            final_path = os.path.join(
                os.path.abspath(out_dir), out_file_name.replace(".tart", "")
            )

    if verbose:
        print("Data downloaded to: {}".format(final_path))

    return

download_ned_by_bbox(bbox, datasets=None, out_dir=None, return_url=False, download_args={}, **kwargs)

Download the US National Elevation Datasets (NED) for a bounding box. See https://apps.nationalmap.gov/tnmaccess/#/ for more information.

Parameters:

Name Type Description Default
bbox list

The bounding box in the form [xmin, ymin, xmax, ymax].

required
huc_type str

The HUC type, e.g., huc2, huc4, huc8. Defaults to "huc8".

required
datasets str

Comma-delimited list of valid dataset tag names. The commonly used datasets include: Digital Elevation Model (DEM) 1 meter National Elevation Dataset (NED) 1/3 arc-second Current National Elevation Dataset (NED) 1/9 arc-second Current National Elevation Dataset (NED) 1 arc-second Current For more information, see https://apps.nationalmap.gov/tnmaccess/#/product Defaults to None, which will be the (NED) 1/3 arc-second

None
out_dir str

The output directory. Defaults to None, which will use the current working directory.

None
return_url bool

If True, the URL will be returned instead of downloading the data. Defaults to False.

False
download_args dict

The download arguments to be passed to the download_file function. Defaults to {}.

{}

Returns:

Name Type Description
list

The list of downloaded files.

Source code in lidar/common.py
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
def download_ned_by_bbox(
    bbox,
    datasets=None,
    out_dir=None,
    return_url=False,
    download_args={},
    **kwargs,
):
    """Download the US National Elevation Datasets (NED) for a bounding box. See https://apps.nationalmap.gov/tnmaccess/#/ for more information.

    Args:
        bbox (list): The bounding box in the form [xmin, ymin, xmax, ymax].
        huc_type (str, optional): The HUC type, e.g., huc2, huc4, huc8. Defaults to "huc8".
        datasets (str, optional): Comma-delimited list of valid dataset tag names. The commonly used datasets include:
            Digital Elevation Model (DEM) 1 meter
            National Elevation Dataset (NED) 1/3 arc-second Current
            National Elevation Dataset (NED) 1/9 arc-second Current
            National Elevation Dataset (NED) 1 arc-second Current
            For more information, see https://apps.nationalmap.gov/tnmaccess/#/product
            Defaults to None, which will be the (NED) 1/3 arc-second
        out_dir (str, optional): The output directory. Defaults to None, which will use the current working directory.
        return_url (bool, optional): If True, the URL will be returned instead of downloading the data. Defaults to False.
        download_args (dict, optional): The download arguments to be passed to the download_file function. Defaults to {}.

    Returns:
        list: The list of downloaded files.
    """

    import requests

    endpoint = "https://tnmaccess.nationalmap.gov/api/v1/products?"

    if datasets is None:
        datasets = "National Elevation Dataset (NED) 1/3 arc-second Current"

    if out_dir is None:
        out_dir = os.getcwd()

    if isinstance(bbox, list):
        bbox = ",".join([str(x) for x in bbox])

    kwargs["datasets"] = datasets
    kwargs["bbox"] = bbox

    result = requests.get(endpoint, params=kwargs).json()
    if "errorMessage" in result:
        raise ValueError(result["errorMessage"])
    else:
        links = [x["downloadURL"] for x in result["items"]]
        for index, link in enumerate(links):
            if "historical" in link:
                link = link.replace("historical", "current")[:-13] + ".tif"
                links[index] = link

    if return_url:
        return links
    else:
        for index, link in enumerate(links):

            r = requests.head(link)
            if r.status_code == 200:
                filepath = os.path.join(out_dir, os.path.basename(link))
                print(
                    f"Downloading {index + 1} of {len(links)}: {os.path.basename(link)}"
                )
                download_file(link, filepath, **download_args)
            else:
                print(f"{link} does not exist.")

download_ned_by_huc(huc_id, huc_type='huc8', datasets=None, out_dir=None, return_url=False, download_args={}, **kwargs)

Download the US National Elevation Datasets (NED) for a Hydrologic Unit region. See https://apps.nationalmap.gov/tnmaccess/#/ for more information.

Parameters:

Name Type Description Default
huc_id str

The HUC ID, for example, "01010002"

required
huc_type str

The HUC type, e.g., huc2, huc4, huc8. Defaults to "huc8".

'huc8'
datasets str

Comma-delimited list of valid dataset tag names. The commonly used datasets include: Digital Elevation Model (DEM) 1 meter National Elevation Dataset (NED) 1/3 arc-second Current National Elevation Dataset (NED) 1/9 arc-second Current National Elevation Dataset (NED) 1 arc-second Current For more information, see https://apps.nationalmap.gov/tnmaccess/#/product Defaults to None, which will be the (NED) 1/3 arc-second

None
out_dir str

The output directory. Defaults to None, which will use the current working directory.

None
return_url bool

If True, the URL will be returned instead of downloading the data. Defaults to False.

False
download_args dict

The download arguments to be passed to the download_file function. Defaults to {}.

{}

Returns:

Name Type Description
list

The list of downloaded files.

Source code in lidar/common.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
def download_ned_by_huc(
    huc_id,
    huc_type="huc8",
    datasets=None,
    out_dir=None,
    return_url=False,
    download_args={},
    **kwargs,
):
    """Download the US National Elevation Datasets (NED) for a Hydrologic Unit region. See https://apps.nationalmap.gov/tnmaccess/#/ for more information.

    Args:
        huc_id (str): The HUC ID, for example, "01010002"
        huc_type (str, optional): The HUC type, e.g., huc2, huc4, huc8. Defaults to "huc8".
        datasets (str, optional): Comma-delimited list of valid dataset tag names. The commonly used datasets include:
            Digital Elevation Model (DEM) 1 meter
            National Elevation Dataset (NED) 1/3 arc-second Current
            National Elevation Dataset (NED) 1/9 arc-second Current
            National Elevation Dataset (NED) 1 arc-second Current
            For more information, see https://apps.nationalmap.gov/tnmaccess/#/product
            Defaults to None, which will be the (NED) 1/3 arc-second
        out_dir (str, optional): The output directory. Defaults to None, which will use the current working directory.
        return_url (bool, optional): If True, the URL will be returned instead of downloading the data. Defaults to False.
        download_args (dict, optional): The download arguments to be passed to the download_file function. Defaults to {}.

    Returns:
        list: The list of downloaded files.
    """

    import requests

    endpoint = "https://tnmaccess.nationalmap.gov/api/v1/products?"

    if datasets is None:
        datasets = "National Elevation Dataset (NED) 1/3 arc-second Current"

    if out_dir is None:
        out_dir = os.getcwd()

    kwargs["datasets"] = datasets
    kwargs["polyType"] = huc_type
    kwargs["polyCode"] = huc_id

    result = requests.get(endpoint, params=kwargs).json()
    if "errorMessage" in result:
        raise ValueError(result["errorMessage"])
    else:
        links = [x["downloadURL"] for x in result["items"]]
        for index, link in enumerate(links):
            if "historical" in link:
                link = link.replace("historical", "current")[:-13] + ".tif"
                links[index] = link

    if return_url:
        return links
    else:
        for index, link in enumerate(links):

            r = requests.head(link)
            if r.status_code == 200:
                filepath = os.path.join(out_dir, os.path.basename(link))
                print(
                    f"Downloading {index + 1} of {len(links)}: {os.path.basename(link)}"
                )
                download_file(link, filepath, **download_args)
            else:
                print(f"{link} does not exist.")

geometry_bounds(geometry, decimals=4)

Returns the bounds of a geometry.

Parameters:

Name Type Description Default
geometry dict

A GeoJSON geometry.

required
decimals int

The number of decimal places to round the bounds to. Defaults to 4.

4

Returns:

Name Type Description
list

A list of bounds in the form of [minx, miny, maxx, maxy].

Source code in lidar/common.py
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
def geometry_bounds(geometry, decimals=4):
    """Returns the bounds of a geometry.

    Args:
        geometry (dict): A GeoJSON geometry.
        decimals (int, optional): The number of decimal places to round the bounds to. Defaults to 4.

    Returns:
        list: A list of bounds in the form of [minx, miny, maxx, maxy].
    """
    if isinstance(geometry, dict):
        if "geometry" in geometry:
            coords = geometry["geometry"]["coordinates"][0]
        else:
            coords = geometry["coordinates"][0]

    else:
        raise ValueError("geometry must be a GeoJSON-like dictionary.")

    x = [p[0] for p in coords]
    y = [p[1] for p in coords]
    west = round(min(x), decimals)
    east = round(max(x), decimals)
    south = round(min(y), decimals)
    north = round(max(y), decimals)
    return [west, south, east, north]

github_raw_url(url)

Get the raw URL for a GitHub file.

Parameters:

Name Type Description Default
url str

The GitHub URL.

required

Returns: str: The raw URL.

Source code in lidar/common.py
416
417
418
419
420
421
422
423
424
425
426
427
428
def github_raw_url(url):
    """Get the raw URL for a GitHub file.

    Args:
        url (str): The GitHub URL.
    Returns:
        str: The raw URL.
    """
    if isinstance(url, str) and url.startswith("https://github.com/") and "blob" in url:
        url = url.replace("github.com", "raw.githubusercontent.com").replace(
            "blob/", ""
        )
    return url

in_colab_shell()

Tests if the code is being executed within Google Colab.

Source code in lidar/common.py
10
11
12
13
14
15
16
17
def in_colab_shell():
    """Tests if the code is being executed within Google Colab."""
    try:
        import google.colab  # pylint: disable=unused-variable

        return True
    except ImportError:
        return False

is_drive_mounted()

Checks whether Google Drive is mounted in Google Colab.

Returns:

Name Type Description
bool

Returns True if Google Drive is mounted, False otherwise.

Source code in lidar/common.py
20
21
22
23
24
25
26
27
28
29
30
def is_drive_mounted():
    """Checks whether Google Drive is mounted in Google Colab.

    Returns:
        bool: Returns True if Google Drive is mounted, False otherwise.
    """
    drive_path = "/content/drive/My Drive"
    if os.path.exists(drive_path):
        return True
    else:
        return False

is_tool(name)

Check whether name is on PATH and marked as executable.

Source code in lidar/common.py
391
392
393
394
395
396
def is_tool(name):
    """Check whether `name` is on PATH and marked as executable."""

    from shutil import which

    return which(name) is not None

join_csv_to_gdf(shapefile_path, csv_path, gdf_join_column, csv_join_column)

Joins a CSV file to a GeoDataFrame based on a common column.

Parameters:

Name Type Description Default
shapefile_path str

Path to the Shapefile.

required
csv_path str

Path to the CSV file.

required
gdf_join_column str

Name of the join column in the GeoDataFrame.

required
csv_join_column str

Name of the join column in the CSV.

required

Returns:

Type Description

geopandas.GeoDataFrame: The GeoDataFrame with the joined data.

Source code in lidar/common.py
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
def join_csv_to_gdf(shapefile_path, csv_path, gdf_join_column, csv_join_column):
    """
    Joins a CSV file to a GeoDataFrame based on a common column.

    Args:
        shapefile_path (str): Path to the Shapefile.
        csv_path (str): Path to the CSV file.
        gdf_join_column (str): Name of the join column in the GeoDataFrame.
        csv_join_column (str): Name of the join column in the CSV.

    Returns:
        geopandas.GeoDataFrame: The GeoDataFrame with the joined data.
    """
    import pandas as pd
    import geopandas as gpd

    # Load the datasets
    gdf = gpd.read_file(shapefile_path)
    csv_data = pd.read_csv(csv_path)

    # Perform the join
    result = gdf.merge(
        csv_data, left_on=gdf_join_column, right_on=csv_join_column, how="left"
    )

    return result

join_tables(in_shp, in_csv, out_shp)

Joins a CSV table to a shapefile.

Parameters:

Name Type Description Default
in_shp str

Path to the input shapefile.

required
in_csv str

Path to the input CSV file.

required
out_shp str

Path to the output shapefile.

required
Source code in lidar/common.py
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
def join_tables(in_shp, in_csv, out_shp):
    """Joins a CSV table to a shapefile.

    Args:
        in_shp (str): Path to the input shapefile.
        in_csv (str): Path to the input CSV file.
        out_shp (str): Path to the output shapefile.
    """
    import geopandas as gpd
    import pandas as pd

    dep_df = gpd.read_file(in_shp)
    info_df = pd.read_csv(in_csv)
    if len(info_df) > 0:
        info_df.columns = [col.replace("-", "_")[:10] for col in info_df.columns]
        info_df["id"] = info_df["region_id"]
        info_df.drop("region_id", axis=1, inplace=True)
        df = pd.merge(dep_df, info_df, on="id")
        df.to_file(out_shp)
    else:
        print("No data to join")

lidar_to_dsm(filename, output=None, resolution=1.0, radius=0.5, minz=None, maxz=None, max_triangle_edge_length=None, verbose=True, **kwargs)

Generates a digital surface model (DSM) from a LiDAR point cloud. It is a wrapper for the whitebox.lidar_digital_surface_model. See https://www.whiteboxgeo.com/manual/wbt_book/available_tools/lidar_tools.html#LidarDigitalSurfaceModel

Parameters:

Name Type Description Default
filename str

The input LiDAR file.

required
output str

The output file. Defaults to None.

None
resolution float

The resolution of the output raster. Defaults to 1.0.

1.0
radius float

The search radius. Defaults to 0.5.

0.5
minz float

Optional minimum elevation for inclusion in interpolation.

None
maxz float

Optional maximum elevation for inclusion in interpolation.

None
max_triangle_edge_length float

Optional maximum triangle edge length; triangles larger than this size will not be gridded

None
verbose bool

description. Defaults to True.

True
Source code in lidar/common.py
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
def lidar_to_dsm(
    filename,
    output=None,
    resolution=1.0,
    radius=0.5,
    minz=None,
    maxz=None,
    max_triangle_edge_length=None,
    verbose=True,
    **kwargs,
):
    """Generates a digital surface model (DSM) from a LiDAR point cloud. It is a wrapper for the `whitebox.lidar_digital_surface_model`.
        See https://www.whiteboxgeo.com/manual/wbt_book/available_tools/lidar_tools.html#LidarDigitalSurfaceModel

    Args:
        filename (str): The input LiDAR file.
        output (str, optional): The output file. Defaults to None.
        resolution (float, optional): The resolution of the output raster. Defaults to 1.0.
        radius (float, optional): The search radius. Defaults to 0.5.
        minz (float, optional): Optional minimum elevation for inclusion in interpolation.
        maxz (float, optional): Optional maximum elevation for inclusion in interpolation.
        max_triangle_edge_length (float, optional): Optional maximum triangle edge length; triangles larger than this size will not be gridded
        verbose (bool, optional): _description_. Defaults to True.
    """
    import whitebox

    wbt = whitebox.WhiteboxTools()
    wbt.verbose = verbose

    filename = os.path.abspath(filename)
    if output is not None:
        output = os.path.abspath(output)

    wbt.lidar_digital_surface_model(
        i=filename,
        output=output,
        resolution=resolution,
        radius=radius,
        minz=minz,
        maxz=maxz,
        max_triangle_edge_length=max_triangle_edge_length,
        **kwargs,
    )

mosaic(images, output, ext='.tif', merge_args={}, verbose=True, **kwargs)

Mosaics a list of images into a single image. Inspired by https://bit.ly/3A6roDK.

Parameters:

Name Type Description Default
images str | list

An input directory containing images or a list of images.

required
output str

The output image filepath.

required
ext str

The image file extension. Defaults to '.tif'.

'.tif'
merge_args dict

A dictionary of arguments to pass to the rasterio.merge function. Defaults to {}.

{}
verbose bool

Whether to print progress. Defaults to True.

True
Source code in lidar/common.py
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
def mosaic(images, output, ext=".tif", merge_args={}, verbose=True, **kwargs):
    """Mosaics a list of images into a single image. Inspired by https://bit.ly/3A6roDK.

    Args:
        images (str | list): An input directory containing images or a list of images.
        output (str): The output image filepath.
        ext (str, optional): The image file extension. Defaults to '.tif'.
        merge_args (dict, optional): A dictionary of arguments to pass to the rasterio.merge function. Defaults to {}.
        verbose (bool, optional): Whether to print progress. Defaults to True.

    """
    from rasterio.merge import merge
    import rasterio as rio
    from pathlib import Path
    import shutil

    output = os.path.abspath(output)

    if isinstance(images, str):
        path = Path(images)
        raster_files = list(path.iterdir())
        raster_files = [f for f in raster_files if f.suffix == ext]
    elif isinstance(images, list):
        raster_files = images
    else:
        raise ValueError("images must be a list of raster files.")

    if len(raster_files) == 0:
        print("No raster files found.")
        return
    elif len(raster_files) == 1:
        shutil.copyfile(raster_files[0], output)
        return

    raster_to_mosiac = []

    if not os.path.exists(os.path.dirname(output)):
        os.makedirs(os.path.dirname(output))

    for index, p in enumerate(raster_files):
        if verbose:
            print(f"Reading {index+1}/{len(raster_files)}: {os.path.basename(p)}")
        raster = rio.open(p, **kwargs)
        raster_to_mosiac.append(raster)

    if verbose:
        print("Merging rasters...")
    arr, transform = merge(raster_to_mosiac, **merge_args)

    output_meta = raster.meta.copy()
    output_meta.update(
        {
            "driver": "GTiff",
            "height": arr.shape[1],
            "width": arr.shape[2],
            "transform": transform,
        }
    )

    with rio.open(output, "w", **output_meta) as m:
        m.write(arr)

random_string(string_length=3)

Generates a random string of fixed length.

Parameters:

Name Type Description Default
string_length int

Fixed length. Defaults to 3.

3

Returns:

Name Type Description
str

A random string

Source code in lidar/common.py
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
def random_string(string_length=3):
    """Generates a random string of fixed length.

    Args:
        string_length (int, optional): Fixed length. Defaults to 3.

    Returns:
        str: A random string
    """
    import random
    import string

    # random.seed(1001)
    letters = string.ascii_lowercase
    return "".join(random.choice(letters) for i in range(string_length))

read_lidar(filename, **kwargs)

Read a LAS file.

Parameters:

Name Type Description Default
filename str

A local file path or HTTP URL to a LAS file.

required

Returns:

Name Type Description
LasData

The LasData object return by laspy.read.

Source code in lidar/common.py
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
def read_lidar(filename, **kwargs):
    """Read a LAS file.

    Args:
        filename (str): A local file path or HTTP URL to a LAS file.

    Returns:
        LasData: The LasData object return by laspy.read.
    """
    try:
        import laspy
    except ImportError:
        print(
            "The laspy package is required for this function. Use `pip install laspy[lazrs,laszip]` to install it."
        )
        return

    if (
        isinstance(filename, str)
        and filename.startswith("http")
        and (filename.endswith(".las") or filename.endswith(".laz"))
    ):
        filename = github_raw_url(filename)
        filename = download_file(filename)

    return laspy.read(filename, **kwargs)

reproject_image(image, output, dst_crs='EPSG:4326', resampling='nearest', **kwargs)

Reprojects an image.

Parameters:

Name Type Description Default
image str

The input image filepath.

required
output str

The output image filepath.

required
dst_crs str

The destination CRS. Defaults to "EPSG:4326".

'EPSG:4326'
resampling Resampling

The resampling method. Defaults to "nearest".

'nearest'
**kwargs

Additional keyword arguments to pass to rasterio.open.

{}
Source code in lidar/common.py
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
def reproject_image(image, output, dst_crs="EPSG:4326", resampling="nearest", **kwargs):
    """Reprojects an image.

    Args:
        image (str): The input image filepath.
        output (str): The output image filepath.
        dst_crs (str, optional): The destination CRS. Defaults to "EPSG:4326".
        resampling (Resampling, optional): The resampling method. Defaults to "nearest".
        **kwargs: Additional keyword arguments to pass to rasterio.open.

    """
    import rasterio as rio
    from rasterio.warp import calculate_default_transform, reproject, Resampling

    if isinstance(resampling, str):
        resampling = getattr(Resampling, resampling)

    image = os.path.abspath(image)
    output = os.path.abspath(output)

    if not os.path.exists(os.path.dirname(output)):
        os.makedirs(os.path.dirname(output))

    with rio.open(image, **kwargs) as src:
        transform, width, height = calculate_default_transform(
            src.crs, dst_crs, src.width, src.height, *src.bounds
        )
        kwargs = src.meta.copy()
        kwargs.update(
            {
                "crs": dst_crs,
                "transform": transform,
                "width": width,
                "height": height,
            }
        )

        with rio.open(output, "w", **kwargs) as dst:
            for i in range(1, src.count + 1):
                reproject(
                    source=rio.band(src, i),
                    destination=rio.band(dst, i),
                    src_transform=src.transform,
                    src_crs=src.crs,
                    dst_transform=transform,
                    dst_crs=dst_crs,
                    resampling=resampling,
                    dst_resolution=(10, 10),
                    **kwargs,
                )

resample(src, dst, resolution, **kwargs)

Resample a raster to a new resolution.

Parameters:

Name Type Description Default
src str

The source raster.

required
dst str

The destination raster.

required
resolution float

The new resolution.

required
Source code in lidar/common.py
865
866
867
868
869
870
871
872
873
874
875
def resample(src, dst, resolution, **kwargs):
    """Resample a raster to a new resolution.

    Args:
        src (str): The source raster.
        dst (str): The destination raster.
        resolution (float): The new resolution.
    """
    from osgeo import gdal

    gdal.Warp(dst, src, xRes=resolution, yRes=resolution, **kwargs)

temp_file_path(extension)

Returns a temporary file path.

Parameters:

Name Type Description Default
extension str

The file extension.

required

Returns:

Name Type Description
str

The temporary file path.

Source code in lidar/common.py
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
def temp_file_path(extension):
    """Returns a temporary file path.

    Args:
        extension (str): The file extension.

    Returns:
        str: The temporary file path.
    """

    import tempfile
    import uuid

    if not extension.startswith("."):
        extension = "." + extension
    file_id = str(uuid.uuid4())
    file_path = os.path.join(tempfile.gettempdir(), f"{file_id}{extension}")

    return file_path

update_package()

Updates the lidar package from the lidar GitHub repository without the need to use pip or conda. In this way, I don't have to keep updating pypi and conda-forge with every minor update of the package.

Source code in lidar/common.py
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
def update_package():
    """Updates the lidar package from the lidar GitHub repository without the need to use pip or conda.
    In this way, I don't have to keep updating pypi and conda-forge with every minor update of the package.

    """
    import shutil

    try:
        download_dir = os.path.join(os.path.expanduser("~"), "Downloads")
        if not os.path.exists(download_dir):
            os.makedirs(download_dir)
        clone_repo(out_dir=download_dir)

        pkg_dir = os.path.join(download_dir, "lidar-master")
        work_dir = os.getcwd()
        os.chdir(pkg_dir)

        if shutil.which("pip") is None:
            cmd = "pip3 install ."
        else:
            cmd = "pip install ."

        os.system(cmd)
        os.chdir(work_dir)

        print(
            "\nPlease comment out 'lidar.update_package()' and restart the kernel to take effect:\nJupyter menu -> Kernel -> Restart & Clear Output"
        )

    except Exception as e:
        raise Exception(e)

view_lidar(filename, cmap='terrain', backend='pyvista', background=None, eye_dome_lighting=False, **kwargs)

View LiDAR data in 3D.

Parameters:

Name Type Description Default
filename str

The filepath to the LiDAR data.

required
cmap str

The colormap to use. Defaults to "terrain". cmap currently does not work for the open3d backend.

'terrain'
backend str

The plotting backend to use, can be pyvista, ipygany, panel, and open3d. Defaults to "pyvista".

'pyvista'
background str

The background color to use. Defaults to None.

None
eye_dome_lighting bool

Whether to use eye dome lighting. Defaults to False.

False

Raises:

Type Description
FileNotFoundError

If the file does not exist.

ValueError

If the backend is not supported.

Source code in lidar/common.py
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
def view_lidar(
    filename,
    cmap="terrain",
    backend="pyvista",
    background=None,
    eye_dome_lighting=False,
    **kwargs,
):
    """View LiDAR data in 3D.

    Args:
        filename (str): The filepath to the LiDAR data.
        cmap (str, optional): The colormap to use. Defaults to "terrain". cmap currently does not work for the open3d backend.
        backend (str, optional): The plotting backend to use, can be pyvista, ipygany, panel, and open3d. Defaults to "pyvista".
        background (str, optional): The background color to use. Defaults to None.
        eye_dome_lighting (bool, optional): Whether to use eye dome lighting. Defaults to False.

    Raises:
        FileNotFoundError: If the file does not exist.
        ValueError: If the backend is not supported.
    """

    import sys

    if os.environ.get("USE_MKDOCS") is not None:
        return

    if "google.colab" in sys.modules:
        print("This function is not supported in Google Colab.")
        return

    warnings.filterwarnings("ignore")
    filename = os.path.abspath(filename)
    if not os.path.exists(filename):
        raise FileNotFoundError(f"{filename} does not exist.")

    backend = backend.lower()
    if backend in ["pyvista", "ipygany", "panel"]:
        try:
            import pyntcloud
        except ImportError:
            print(
                "The pyvista and pyntcloud packages are required for this function. Use pip install leafmap[lidar] to install them."
            )
            return

        try:
            if backend == "pyvista":
                backend = None
            if backend == "ipygany":
                cmap = None
            data = pyntcloud.PyntCloud.from_file(filename)
            mesh = data.to_instance("pyvista", mesh=False)
            mesh = mesh.elevation()
            mesh.plot(
                scalars="Elevation",
                cmap=cmap,
                jupyter_backend=backend,
                background=background,
                eye_dome_lighting=eye_dome_lighting,
                **kwargs,
            )

        except Exception as e:
            print("Something went wrong.")
            print(e)
            return

    elif backend == "open3d":
        try:
            import laspy
            import open3d as o3d
            import numpy as np
        except ImportError:
            print(
                "The laspy and open3d packages are required for this function. Use pip install laspy open3d to install them."
            )
            return

        try:
            las = laspy.read(filename)
            point_data = np.stack([las.X, las.Y, las.Z], axis=0).transpose((1, 0))
            geom = o3d.geometry.PointCloud()
            geom.points = o3d.utility.Vector3dVector(point_data)
            # geom.colors =  o3d.utility.Vector3dVector(colors)  # need to add colors. A list in the form of [[r,g,b], [r,g,b]] with value range 0-1. https://github.com/isl-org/Open3D/issues/614
            o3d.visualization.draw_geometries([geom], **kwargs)

        except Exception as e:
            print("Something went wrong.")
            print(e)
            return

    else:
        raise ValueError(f"{backend} is not a valid backend.")

write_lidar(source, destination, do_compress=None, laz_backend=None)

Writes to a stream or file.

Parameters:

Name Type Description Default
source str | LasBase

The source data to be written.

required
destination str

The destination filepath.

required
do_compress bool

Flags to indicate if you want to compress the data. Defaults to None.

None
laz_backend str

The laz backend to use. Defaults to None.

None
Source code in lidar/common.py
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
def write_lidar(source, destination, do_compress=None, laz_backend=None):
    """Writes to a stream or file.

    Args:
        source (str | laspy.lasdatas.base.LasBase): The source data to be written.
        destination (str): The destination filepath.
        do_compress (bool, optional): Flags to indicate if you want to compress the data. Defaults to None.
        laz_backend (str, optional): The laz backend to use. Defaults to None.
    """

    try:
        import laspy
    except ImportError:
        print(
            "The laspy package is required for this function. Use `pip install laspy[lazrs,laszip]` to install it."
        )
        return

    if isinstance(source, str):
        source = read_lidar(source)

    source.write(destination, do_compress=do_compress, laz_backend=laz_backend)