Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions pysits/docs/content/impute_linear.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
Replace NA values by linear interpolation

Remove NA by linear interpolation

Args:
data (list | pandas.DataFrame): A time series vector or matrix.

Returns:
R: A set of filtered time series using the imputation function.
9 changes: 9 additions & 0 deletions pysits/docs/content/impute_mean.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
Remove NA using mean

Remove NA using mean

Args:
data (list[float] | pandas.DataFrame): A time series or matrix.

Returns:
R: A set of filtered time series using the imputation function.
23 changes: 23 additions & 0 deletions pysits/docs/content/impute_mean_window.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
Remove NA using weighted moving average

Remove NA using weighted moving average

Args:
data (list): A time series vector or matrix.
k (int): Width of the moving average window. Expands to both sides
of the center element e.g. k = 2 means 4 observations (2 left,
2 right) are taken into account. If all observations in the
current window are NA, the window size is automatically
increased until there are at least 2 non-NA values present.
weighting (str): The weighting strategy to be used. More details
below (default is "simple").

Returns:
R: A set of filtered time series using the imputation function.

Notes:
The `weighting` parameter defines the weighting strategy used in the
moving window. The strategies available are:
- `simple` - Simple Moving Average (SMA) (default option)
- `linear` - Linear Weighted Moving Average (LWMA)
- `exponential` - Exponential Weighted Moving Average (EWMA)
9 changes: 9 additions & 0 deletions pysits/docs/content/impute_median.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
Remove NA using median

Remove NA using median

Args:
data (list[float] | SITSMatrix): A time series vector or matrix.

Returns:
R: A set of filtered time series using the imputation function.
112 changes: 112 additions & 0 deletions pysits/docs/content/plot.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
Plot sits objects.

Unified plotting function that dispatches on the type of the object passed
as `x`. It mirrors the many `plot` methods of the R `sits` package,
covering data cubes (raster, SAR, DEM, vector, RGB), probability and
uncertainty cubes, variance cubes, classified images, time series patterns
and predictions, machine learning / deep learning models, clustering and
self-organizing map (SOM) results, accuracy tables, and t-SNE / embedding
visualizations. The set of accepted keyword arguments depends on the type
of object being plotted.

Args:
x (SITSCubeModel | SITSTimeSeriesModel | SITSTimeSeriesPatternsModel | SITSMachineLearningMethod | SITSConfusionMatrix): Object to be
plotted. Supported objects include classified raster images,
classified segments, digital elevation model cubes, multi-year
land use/cover embedding predictions, sample distances, class
temporal patterns, probability cubes, raster, SAR, and vector
data cubes, confusion matrices / accuracy metrics, dendrograms,
trained models, time series predictions, t-SNE projections, SOM
results, uncertainty cubes, and variance cubes.
y: Ignored. Present for compatibility with the generic `plot`.
band (str): Band used for plotting a single-band (grey scale) image.
Applies to raster, SAR, DEM, and vector cubes, and to SOM maps.
red (str): Band assigned to the red channel of an RGB composite
(raster, SAR, and vector cubes).
green (str): Band assigned to the green channel of an RGB composite.
blue (str): Band assigned to the blue channel of an RGB composite.
tile (str): Tile to be plotted (data cubes, probability, uncertainty,
and variance cubes).
dates (list[str]): Dates to be plotted (raster, SAR, and vector
cubes).
roi (dict | geopandas.GeoDataFrame): Spatial extent (region of
interest) to plot, in WGS 84.
labels (list[str]): Labels to plot (probability and variance cubes).
bands (list[str]): Bands to be viewed (patterns and time series
predictions).
legend (dict): Associates labels to colors, or a legend specification
for SOM plots.
legend_position (str): Where to place the legend (typically "inside"
or "outside", with defaults varying by plot type).
legend_title (str): Title of the legend (probability and variance
cubes).
palette (str): An RColorBrewer or "cols4all" (or HCL) palette used
for color mapping.
rev (bool): Whether to reverse the color order in the palette.
scale (float): Relative scale of plot text and map (typically 0.4 to
1.0).
quantile (float): Minimum quantile to plot (probability and variance
cubes).
first_quantile (float): First quantile for stretching images.
last_quantile (float): Last quantile for stretching images.
max_cog_size (int): Maximum size of COG (Cloud Optimized GeoTIFF)
overviews, in lines/columns or pixels.
seg_color (str): Color used to draw segment boundaries (vector cubes).
line_width (float): Line width used to draw segment boundaries
(vector cubes).
type (str): Type of plot; meaning depends on the object. For accuracy
objects it is "confusion_matrix" or "metrics"; for variance cubes
it is "map" or "hist"; for SOM maps it is "codes" or "mapping".
cluster: Cluster object produced by `sits_cluster_dendro`, used when
plotting a dendrogram.
cutree_height (float): Height at which to draw a dashed horizontal
line indicating where the dendrogram is cut.
name_cluster (str): Cluster to plot (SOM cluster evaluation).
title (str): Title of the plot (SOM cluster evaluation).
year_grid (bool): Whether to plot patterns as a grid of panels with
labels as columns and years as rows. Defaults to False.
tree_idx (int): Index of the tree to be plotted for an XGBoost model.
plot_embedding (str): For embedding predictions, either "none" (plot
only predicted class intervals) or "area" (overlay a smoothed
vertical embedding profile per year).
stretch (tuple[float, float]): For embedding plots, lower/upper
quantiles used to stretch embedding values before plotting.
class_alpha (float): Transparency of class polygons in embedding plots
(0-1).
area_alpha (float): Transparency of the embedding area in embedding
plots (0-1).
area_width (float): Horizontal width fraction of the embedding area.
area_spar (float): Smoothing parameter for the embedding area spline.
**kwargs (dict): Further specifications passed to the underlying plot.

Returns:
None: A plot is produced. Depending on the input type this may be a
color map of classified pixels, an RGB or grey-scale image, a
probability or uncertainty map, a variance map (optionally with
segment overlays), a dendrogram, a confusion matrix, a SOM map, a
model diagnostic plot, or a plot for patterns, predictions,
embeddings, and t-SNE projections. Some methods are called only for
their side effect of drawing the plot.

Notes:
The `roi` argument can be defined as a `dict` giving the spatial
extent (for example with `lon_min`, `lon_max`, `lat_min`, `lat_max`),
a `geopandas.GeoDataFrame`, or another spatial specification accepted
by `sits`. Vector cube plots overlay the segments produced by
`sits_segment` on top of the raster image; their appearance is
controlled by `seg_color` and `line_width`.

Examples:
from pysits import *

# Plot a set of time series patterns
patterns = sits_patterns(cerrado_2classes)
plot(patterns)

# Train a random forest model and plot variable importance
rfor_model = sits_train(samples_modis_ndvi, ml_method=sits_rfor())
plot(rfor_model)

# Plot a SOM map produced from a set of samples
som_map = sits_som_map(samples_modis_ndvi)
plot(som_map)
80 changes: 80 additions & 0 deletions pysits/docs/content/sits_accuracy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
Assess classification accuracy

This function calculates the accuracy of the classification result. The input
is either a set of classified time series or a classified data cube. Classified
time series are produced by `sits_classify`. Classified images are generated
using `sits_classify` followed by `sits_label_classification`.
For a set of time series, `sits_accuracy` creates a confusion matrix and
calculates the resulting statistics using package `caret`. For a classified
image, the function uses an area-weighted technique proposed by Olofsson et al.
according to references [1-3] to produce reliable accuracy estimates at 95%
confidence level. In both cases, it provides an accuracy assessment of the
classified, including Overall Accuracy, Kappa, User's Accuracy, Producer's
Accuracy and error matrix (confusion matrix).

Args:
data (SITSCubeModel | SITSTimeSeriesModel): Either a data cube with
classified images or a set of time series.
prediction_attr (str): Name of the column of the segments object that
contains the predicted values (only for vector class cubes).
reference_attr (str): Name of the column of the segments object that
contains the reference values (only for vector class cubes).
validation (str | pathlib.Path | pandas.DataFrame | geopandas.GeoDataFrame | SITSTimeSeriesModel):
Samples for validation (see below). Only required when data is a
raster class cube.
method (str): Either 'olofsson' or 'pixel' to compute accuracy (only
for raster class cubes).
**kwargs (dict): Specific parameters.

Returns:
SITSData: The error_matrix, the class_areas, the unbiased estimated
areas, the standard error areas, confidence interval 95 and the accuracy
(user, producer, and overall), or `None` if the data is empty. The result
can be visualized directly on the screen.

Notes:
The `validation` data needs to contain the following columns: "latitude",
"longitude", "start_date", "end_date", and "label". It can be either a path
to a CSV file, a `SITSTimeSeriesModel`, a `pandas.DataFrame`, or a
`geopandas.GeoDataFrame`.
When `validation` is a `geopandas.GeoDataFrame`, the columns "latitude"
and "longitude" are not required as the locations are extracted from the
geometry column. The `centroid` is calculated before extracting the
location values for any geometry type.

Examples:
from pysits import *

# show accuracy for a set of samples
train_data = sits_sample(samples_modis_ndvi, frac=0.5)
test_data = sits_sample(samples_modis_ndvi, frac=0.5)
rfor_model = sits_train(train_data, sits_rfor())
points_class = sits_classify(
data=test_data, ml_model=rfor_model
)
acc = sits_accuracy(points_class)

# show accuracy for a data cube classification
# create a random forest model
rfor_model = sits_train(samples_modis_ndvi, sits_rfor())
# create a data cube from local files
data_dir = r_package_dir("extdata/raster/mod13q1", package="sits")
cube = sits_cube(
source="BDC",
collection="MOD13Q1-6.1",
data_dir=data_dir
)
# classify a data cube
import tempfile
probs_cube = sits_classify(
data=cube, ml_model=rfor_model, output_dir=tempfile.gettempdir()
)
# label the probability cube
label_cube = sits_label_classification(
probs_cube,
output_dir=tempfile.gettempdir()
)
# obtain the ground truth for accuracy assessment
ground_truth = r_package_dir("extdata/samples/samples_sinop_crop.csv", package="sits")
# make accuracy assessment
as_ = sits_accuracy(label_cube, validation=ground_truth)
11 changes: 11 additions & 0 deletions pysits/docs/content/sits_accuracy_summary.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
Print accuracy summary

Adaptation of the caret::print.confusionMatrix method for the more common
usage in Earth Observation.

Args:
x (SITSConfusionMatrix): accuracy object to summarize.
digits (int): number of significant digits when printed.

Returns:
SITSData: called for side effects.
55 changes: 55 additions & 0 deletions pysits/docs/content/sits_add_base_cube.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
Add base maps to a time series data cube

This function add base maps to time series data cube. Base maps have
information that is stable in time (e.g, DEM) which provide relevant
information for modelling and classification.
To add a base cube to an existing data cube, they should share the same
sensor, resolution, bounding box, timeline, and have different bands.

Args:
cube1 (SITSCubeModel): Data cube.
cube2 (SITSCubeModel): Data cube with base information.

Returns:
SITSCubeModel: a merged data cube with the inclusion of base
information.

Examples:
from pysits import *
import tempfile
import os

s2_cube = sits_cube(
source="MPC",
collection="SENTINEL-2-L2A",
tiles="18HYE",
bands=["B8A", "CLOUD"],
start_date="2022-01-01",
end_date="2022-03-31"
)
output_dir = os.path.join(tempfile.gettempdir(), "reg")
if not os.path.exists(output_dir):
os.makedirs(output_dir)
dem_cube = sits_cube(
source="MPC",
collection="COP-DEM-GLO-30",
tiles="18HYE",
bands="ELEVATION"
)
s2_reg = sits_regularize(
cube=s2_cube,
period="P1M",
res=240,
output_dir=output_dir,
multicores=2,
memsize=4
)
dem_reg = sits_regularize(
cube=dem_cube,
res=240,
tiles="18HYE",
output_dir=output_dir,
multicores=2,
memsize=4
)
s2_reg = sits_add_base_cube(s2_reg, dem_reg)
Loading
Loading