# GenSimPlot

GenSimPlot is a QGIS plugin designed and developed for generating spatially optimized plots used in the simulation and analysis of geographic processes. Plugin enable to create squared, circular, rectangular, and eliptical plots maximazing overlap with the source polygons, enhancing the accuracy and representativeness of simulations.

By automating plot generation, point grid creation, and raster data extraction, GenSimPlot enhances spatial analysis workflows within QGIS, making it a versatile tool for both research and applied geographic studies.

GenSimPlot is designed to support a wide range of spatial analysis and simulation tasks, including:

- Forest growth simulations.
- Habitat suitability simulations.
- Landscape planning.
- Environmental and ecological modeling

## Key Features

### Plot Shape Generation

- Generate spatially optimized plots in square, circular, rectangular, or elliptical shapes.
- Configurable positioning options, including alignment with the bounding box, centroid, or mean coordinates of source polygons.
- Optimized placement to maximize coverage and overlap with the original polygon, improving spatial simulation outcomes.

### Regular Point Grid Creation

- Generate regular grids of points within each simulation plot.
- Configure grid density, making it suitable for high-resolution sampling within plots.
- Optional clipping of grid points to ensure they remain within the defined plot boundaries.

### Raster Data Extraction

- Extract values from environmental raster layers, such as DEM or slope, and assign these values to simulation plots or individual grid points within plots.
- Options to calculate aggregate statistics (e.g., mean, min, max) of raster values across grid points for each plot.

## Technical Requirements

GenSimPlot is developed as a QGIS plugin and requires QGIS version 3.0 or higher to run. The plugin is written in Python and uses the PyQt5 library for the user interface. The plugin is compatible with Windows, macOS, and Linux operating systems.

## Installation

GenSimPlot can be installed from the QGIS Plugin Repository or by downloading the source code from the GitHub repository.

The plugin will be available in the QGIS Vector menu after installation.

## License

The plugin is licensed under the EUPL v1.2 (European Union Public License).

## Generate Simulation Plots

The "Generate Simulation Plots" dialog provides an interface for creating simulation plots over a selected set of polygons from an input shapefile.
This tool supports generating various plot shapes — such as squares, circles, rectangles, and ellipses — with configurable positioning and placement options to align each plot with the underlying geometry of the polygon.
This dialog enables flexible plot positioning based on attributes like the bounding box, centroid, and mean coordinates of each polygon.
Additionally, random transformations such as translations, rotations, and resizing can be applied to maximize spatial overlap with source polygons, improving representativeness for spatial analyses.

Parameters:

- Input shapefile: Shapefile containing polygon features (e.g., forest stands).
- Polygon ID: Field name uniquely identifying each polygon within the input shapefile.
- Output shapefile: Path where the generated plots will be saved.
- Shape: Specifies the shape of the simulation plot. Options include square, circle, rectangle, ellipse, or “best” (which selects an optimized shape for maximal overlap).
- Position: Defines the initial alignment of the plot within each polygon:
  - Bounding Box: Aligns the plot to the centroid of the bounding box.
  - Centroid: Centers the plot on the polygon's centroid.
  - Mean Coordinates: Centers the plot on the average x and y coordinates of the polygon.
- Placement: Specifies spatial transformations to apply to the plot:
  - Fixed: Maintains a fixed position for the plot.
  - Translated: Applies random translations to vary plot positioning.
  - Rotated: Randomly rotates the plot for orientation adjustments.
  - Resized: Alters the plot’s size while preserving its area.
  - Optimized: Iteratively adjusts position, rotation, and size to maximize overlap with the polygon.

Example of generated square simulation plots with optimal spatial placement for maximal overlap with source polygons:

Example of generated simulation plots optimized using the 'best' option:

## Generate Point Grids for Simulation Plots

The "Generate Point Grids for Simulation Plots" dialog allows users to create a regular grid of points over the bounding rectangle of each simulation plot in a selected shapefile.
The grid can be customized in density and alignment, with an option to clip points to fit precisely within the plot boundaries.
Users can select an input shapefile containing simulation plots, specify the number of points along the shorter side of the bounding rectangle to control grid density, and define an output shapefile to store the generated points.
The grid aligns with each plot’s transformation, ensuring accurate representation within simulation plot geometries.

Parameters:

- Simulation plots: Shapefile containing polygon features representing the simulation plots.
- Plot ID: Field name that identifies each simulation plot within the input shapefile.
- Output shape-file: Path to the shapefile where the generated point grid will be saved.
- Number of points: The number of points to generate along the shorter side of each plot's bounding box, controlling the grid density.
- Clip points by simulation plot: Option to clip generated points to fit precisely within each plot's boundary, preserving spatial accuracy.

Example of a regularly spaced point grid generated within square simulation plots:

Example of a point grid generated within simulation plots optimized using the 'best' option:

## Raster Value Statistics by Plot Points

The "Raster Value Statistics by Plot Points" dialog enables users to calculate summary statistics of raster values for multiple points within each simulation plot.
Users can specify an input shapefile containing simulation plots, a shapefile with points positioned inside each plot, and a raster file representing an environmental variable.
After setup, the dialog extracts raster values at each point within the plots and calculates summary statistics (minimum, maximum, and mean) for each plot.
These statistics are then stored in the simulation plot attribute table as new fields.

Parameters:

- Simulation plots: Shapefile containing polygons representing the plots.
- Plot ID: Field name containing the unique identifier for each simulation plot.
- Simulation plot points: Shapefile containing point geometries located within each plot. These points are used as sampling locations for raster values.
- Output field name: Prefix for the output fields that will store calculated statistics. The prefix can be up to 5 characters.
  In the simulation plot shapefile, the fields will be named as: `<prefix>_min`, `<prefix>_max`, and `<prefix>_mean`.
  In the points shapefile, the raster values at each point location will be stored in a field with the given output field name.
  If the specified fields do not already exist, they will be created automatically.
- Raster: Binary ArcGIS raster file containing the environmental variable to be extracted and analyzed.

## Raster Value by Plot Centroid

The "Extract Values By Centroid" dialog allows users to extract raster values at the centroids of simulation plots stored in an input shapefile.
Users can specify both an input simulation plot shapefile and a raster file, and designate an output field where the extracted raster values will be saved in the simulation plot attribute table.
This dialog simplifies the assignment of spatially relevant raster data to simulation plots, enabling efficient and accurate data integration for analysis.

Parameters:

- Simulation plots: Shapefile containing polygon geometries representing the simulation plots.
- Output field name: The name of the field to store the extracted raster value at each plot's centroid.
  - The field name can be up to 10 characters in length.
  - If the field exists, its values will be overwritten; otherwise, a new field will be created in the shapefile.
- Raster: The ArcGIS binary raster file containing the environmental data to be extracted.

## Scripting

The GenSimPlot library provides classes and functions for automating the generation of simulation plots, creation of point grids, and extraction of raster values.
These tools can be executed from the QGIS Python console or integrated into custom Python workflows for streamlined spatial analysis.

Example usage of `GenSimPlotLib` classes:

        from GenSimPlotLib import PlotGenerator, PointsGenerator, SimulationPlotVariables
        from GenSimPlotUtilities import GProgressDialog

        #Initialize the progress dialog
        progressDlg = GProgressDialog()
        progressDlg.show()

        #Define input parameters
        workingFolder = "c:\\data\\"
        inputShp = workingFolder + "forest_stands.shp"
        polygonID = "id"
        plotsShp = workingFolder + "plots.shp"
        pointsShp = workingFolder + "points.shp"
        nPoints = 10
        clipPoints = True
        demRaster = workingFolder + "dem\\dem"
        slopeRaster = workingFolder + "dem\\slope"

        #Generate optimized simulation plots
        plotGen = PlotGenerator()
        plotGen.generateBestPlots(inputShp, polygonID, plotsShp, progressDlg)

        #Generate a grid of points within the plots
        pointsGen = SimulationPlotVariables()
        pointsGen.generatePoints(plotsShp, polygonID, pointsShp, nPoints, clipPoints, progressDlg)

        #Extract raster values for each point within plots and calculate plot-level statistics
        rasterStats = SimulationPlotVariables()
        rasterStats.valueFromPoints(plotsShp, polygonID, pointsShp, "elev", demRaster, progressDlg)

        #Extract raster values for each plot centroid
        rasterCentroid = SimulationPlotVariables()
        rasterCentroid.valueFromCentroid(plotsShp, "slope", slopeRaster, progressDlg)

        #Close the progress dialog
        progressDlg.close()

## Hyperparameters Tuning

The GenSimPlot library provides a configurable set of hyperparameters that govern the optimization of simulation plot generation. These parameters can be adjusted to improve the spatial alignment and representativeness of the generated plots:

- randomIterations: Specifies the number of random iterations used in generating each simulation plot.
- percTranslate: Defines the maximum percentage for random translation along the x and y axes.
- maxAlpha: Sets the maximum allowable rotation angle (in degrees) for random plot orientation.
- maxResizePerc: Determines the maximum percentage by which the plot size can be randomly adjusted.
- sideRatioMax: Limits the maximum allowable ratio between the longer and shorter sides of rectangular plots.

Hyperparameter settings can be saved to a configuration file named gensimplot.cnf, which is formatted in JSON. These parameters can be manually adjusted within the configuration file, providing users with a convenient way to customize the simulation plot generation process. The hyperparameters are automatically loaded during the initialization of the `PlotGenerator` class.

The `HTuning` class implements methods for managing the hyperparameter tuning process.

The example below demonstrates how to use the `HTuning` class in GenSimPlot to automate the hyperparameters tuning process. The procedure involves randomly selecting hyperparameter values within specified ranges and evaluating the quality of the resulting simulation plots based on overlap statistics with the input polygons. This process is repeated for a user-defined number of iterations. The resulting metrics, including overlap percentages and execution times, are appended to a designated CSV file for subsequent analysis.

        from htuning import HTuning
        from GenSimPlotUtilities import GProgressDialog

        # Initialize the progress dialog
        progressDlg = GProgressDialog()
        progressDlg.show()

        ht = HTuning()

        ht.run(
            workingFolder = "C:\\data\\",
            polygonShpFN = "polygons.shp",
            idFieldName = "id",
            outputPlotFNBase = "splots",
            outputStatisticsFN = "statistics_best.csv",
            progressDlg = progressDlg,
            minIterations = 50,
            maxIterations = 1000,
            minTranslatePerc = 0.01,
            maxTranslatePerc = 0.25,
            minAngleLimit = 1.0,
            maxAngleLimit = 45.0,
            minResizePerc = 0.01,
            maxResizePerc = 0.25,
            position = "bounding box",
            placement = "optimized",
            shape = "best",
            numberOfTests = 25,
        )

        # Close the progress dialog
        progressDlg.close()