pyearthforge 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,27 @@
1
+ """EarthForge: lazy, memory-efficient raster processing and visualization for GeoTIFFs.
2
+
3
+ from pyearthforge import raster, vector, cluster, classifier, pca
4
+
5
+ img = raster.image("scene.tif")
6
+ ndvi = img.normalizedDifference(["B8", "B4"]).rename("NDVI")
7
+ ndvi.visualize(min=-0.2, max=0.8, palette="ndvi")
8
+ ndvi.save("ndvi.tif")
9
+
10
+ Documentation: https://gitlab.com/muddasir.ndma25/earthforge
11
+ """
12
+
13
+ from .add import add
14
+ from .subtract import subtract
15
+ from . import raster # exposes the whole raster MODULE, so you call raster.image(), raster.meta()
16
+ from .raster import RasterNotFoundError, RasterReadError
17
+
18
+ # `vector`, `cluster`, `classifier` and `pca` are NOT imported here, so `from pyearthforge import raster`
19
+ # stays fast (geopandas / scikit-learn are only loaded when you use them).
20
+ # `from pyearthforge import vector, cluster, classifier, pca` still works: Python imports them on demand.
21
+
22
+ # Set to True to see the library's internal frames in tracebacks (for debugging).
23
+ FULL_TRACEBACKS = False
24
+
25
+ __all__ = ["add", "subtract", "raster", "vector", "cluster", "classifier", "pca",
26
+ "RasterNotFoundError", "RasterReadError"]
27
+ __version__ = "0.1.0"
@@ -0,0 +1,125 @@
1
+ # _errors.py -> short, clean error messages for the whole package (internal module)
2
+ #
3
+ # Errors raised by the library's own code are re-raised without the library's
4
+ # internal frames. In Jupyter / IPython only the user's code line and the
5
+ # message are shown. The errors keep their normal classes (ValueError, ...).
6
+ # Set `pyearthforge.FULL_TRACEBACKS = True` to see the internal frames when debugging.
7
+
8
+ import functools
9
+ import os
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ _PACKAGE_DIR = os.path.normcase(os.path.abspath(os.path.dirname(__file__)))
14
+ _PACKAGE = __name__.rpartition(".")[0]
15
+
16
+
17
+ class LibraryError(Exception):
18
+ """Base class for the library's own error types."""
19
+
20
+
21
+ def _in_package(filename):
22
+ return os.path.normcase(os.path.abspath(os.path.dirname(filename))) == _PACKAGE_DIR
23
+
24
+
25
+ def _full_tracebacks():
26
+ return bool(getattr(sys.modules.get(_PACKAGE), "FULL_TRACEBACKS", False))
27
+
28
+
29
+ def _raised_by_library(error):
30
+ """True if the error was raised by this package's code (not numpy, rasterio, ...)."""
31
+ tb = error.__traceback__
32
+ if tb is None:
33
+ return True
34
+ while tb.tb_next is not None:
35
+ tb = tb.tb_next
36
+ return _in_package(tb.tb_frame.f_code.co_filename)
37
+
38
+
39
+ def _frame_label(filename, lineno):
40
+ """'Cell In[3], line 2' for notebook cells, 'File path, line N' otherwise."""
41
+ try:
42
+ from IPython import get_ipython
43
+ shell = get_ipython()
44
+ count = shell.compile._filename_map.get(filename) if shell is not None else None
45
+ if count is not None:
46
+ return f"Cell In[{count}], line {lineno}"
47
+ except Exception:
48
+ pass
49
+ return f"File {filename}, line {lineno}"
50
+
51
+
52
+ class _ShortTraceback:
53
+ """Mixin for library errors: Jupyter/IPython shows only the user's code and the message.
54
+
55
+ IPython calls `_render_traceback_()` instead of printing the full traceback.
56
+ """
57
+
58
+ def _render_traceback_(self):
59
+ import traceback
60
+ red, reset = "\x1b[31m", "\x1b[39m"
61
+ name = type(self).__name__
62
+ lines = ["-" * 75, f"{red}{name}{reset}" + " " * max(1, 42 - len(name))
63
+ + "Traceback (most recent call last)"]
64
+ for frame in traceback.extract_tb(self.__traceback__):
65
+ if _in_package(frame.filename):
66
+ continue # library internals
67
+ if {"IPython", "ipykernel"} & set(Path(frame.filename).parts):
68
+ continue # notebook machinery
69
+ lines.append(_frame_label(frame.filename, frame.lineno))
70
+ if frame.line:
71
+ lines.append(f"----> {frame.line}")
72
+ lines += ["", f"{red}{name}{reset}: {self}"]
73
+ return lines
74
+
75
+
76
+ _SHORT_TYPES = {}
77
+
78
+
79
+ def _short_type(cls):
80
+ """A subclass of `cls` with the same name that has a short Jupyter traceback."""
81
+ if cls not in _SHORT_TYPES:
82
+ _SHORT_TYPES[cls] = type(cls.__name__, (_ShortTraceback, cls),
83
+ {"__module__": cls.__module__, "__qualname__": cls.__qualname__})
84
+ return _SHORT_TYPES[cls]
85
+
86
+
87
+ _CLEANED = (ValueError, TypeError, FileNotFoundError, LibraryError)
88
+
89
+
90
+ def clean_errors(func):
91
+ """Decorator: errors raised by the library show only the user's line and the message."""
92
+ @functools.wraps(func)
93
+ def wrapper(*args, **kwargs):
94
+ __tracebackhide__ = True # noqa: F841 (read by pytest)
95
+ try:
96
+ return func(*args, **kwargs)
97
+ except _CLEANED as error:
98
+ if _full_tracebacks() or not _raised_by_library(error):
99
+ raise
100
+ if not isinstance(error, _ShortTraceback):
101
+ error = _short_type(type(error))(*error.args)
102
+ raise error.with_traceback(None) from None
103
+ return wrapper
104
+
105
+
106
+ _OPERATOR_METHODS = {
107
+ "__init__", "__bool__", "__neg__", "__abs__", "__invert__", "__len__",
108
+ "__add__", "__radd__", "__sub__", "__rsub__", "__mul__", "__rmul__",
109
+ "__truediv__", "__rtruediv__", "__pow__", "__rpow__",
110
+ "__lt__", "__le__", "__gt__", "__ge__", "__and__", "__rand__", "__or__", "__ror__",
111
+ }
112
+
113
+
114
+ def clean_class(cls):
115
+ """Apply clean_errors to every public method (and operators) of a class."""
116
+ for name, attr in list(vars(cls).items()):
117
+ if name.startswith("_") and name not in _OPERATOR_METHODS:
118
+ continue
119
+ if isinstance(attr, staticmethod): # keep static methods static
120
+ setattr(cls, name, staticmethod(clean_errors(attr.__func__)))
121
+ elif isinstance(attr, classmethod):
122
+ setattr(cls, name, classmethod(clean_errors(attr.__func__)))
123
+ elif callable(attr):
124
+ setattr(cls, name, clean_errors(attr))
125
+ return cls
pyearthforge/add.py ADDED
@@ -0,0 +1,21 @@
1
+ def add(a, b):
2
+ """Returns the sum of a and b.
3
+
4
+ Works with anything that supports ``+``: numbers, NumPy arrays and Images.
5
+
6
+ Parameters
7
+ ----------
8
+ a, b : number, numpy.ndarray or Image
9
+
10
+ Returns
11
+ -------
12
+ The same type as the inputs: a + b.
13
+
14
+ Examples
15
+ --------
16
+ >>> from pyearthforge import add
17
+ >>> add(3, 4)
18
+ 7
19
+ >>> add(img.select("B4").data, 100) # NumPy array + number
20
+ """
21
+ return a + b