Name | PySAGA-cmd JSON |
Version |
1.2.6
JSON |
| download |
home_page | None |
Summary | A package that allows you to run SAGA GIS tools using Python. |
upload_time | 2024-06-29 06:19:43 |
maintainer | None |
docs_url | None |
author | None |
requires_python | >=3.9 |
license | MIT |
keywords |
pysaga-cmd
|
VCS |
|
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
No coveralls.
|
[![DOI](https://zenodo.org/badge/711593377.svg)](https://zenodo.org/doi/10.5281/zenodo.10673418)
# PySAGA-cmd
PySAGA-cmd is a simple way of running SAGA GIS tools using Python.
## How to download
Binary installers for the latest released version are available at the [Python Package Index (PyPI)](https://pypi.org/project/PySAGA-cmd/). If you want to have access to extra features (like plotting) you can download the extras as shown in the second command.
```sh
pip install PySAGA-cmd
pip install PySAGA-cmd[extras]
```
## How to use the package
### Choosing tools
Before you can use this package, you need to locate the **saga_cmd** in your system. For linux, it can be found somewhere in the `/usr/bin/` directory. For Windows, it is usually located in `C:\Program Files\SAGA`.
Accesing tools can be done with the **truediv** operator (the forward slash **/**), like in the example below.
```python
from PySAGA_cmd import (
SAGA,
get_sample_dem
)
saga = SAGA('/usr/bin/saga_cmd')
# Choosing libraries.
preprocessor = saga / 'ta_preprocessor'
# Choosing tools.
route_detection = preprocessor / 'Sink Drainage Route Detection'
sink_removal = preprocessor / 'Sink Removal'
flow_accumulation = saga / 'ta_hydrology' / 'Flow Accumulation (Parallelizable)'
```
### Executing
Executing an object is straight forward and is done using the **execute** method. For the SAGA and Library objects no keyword arguments are required. For tools, just provide the required keyword arguments.
```python
# Executing the SAGA object. Useful when you want to see the available libraries.
saga_output = saga.execute()
print(saga_output.stdout)
# Executing the Library object. Useful when you want to see the available tools.
preprocessor_output = preprocessor.execute()
print(preprocessor_output.stdout)
# Executing a Tool object.
dem = get_sample_dem()
output = 'path/to/output.sdat'
output = route_detection.execute(verbose=True, elevation=dem, sinkroute=output)
print(output.stdout)
```
### Using flags
You can provide flags for SAGA, Library and Tool objects. To see what kind of flags can be used, look at the output of the following.
```python
saga.flag = 'help'
print(saga.execute().stdout)
```
### Chaining commands
Chaining commands can be done with **PySAGA-cmd** with the **or** operator (the vertical line **|**). Consider the following example where the goal is to get a hydrologically preprocessed DEM and use that as input for the *Flow Accumulation (Parallelizable)* tool.
```python
pipe = (
route_detection(elevation=dem, sinkroute='temp.sdat') |
sink_removal(dem=route_detection.elevation,
sinkroute=route_detection.sinkroute,
dem_preproc='temp.sdat') |
flow_accumulation(dem=sink_removal.dem_preproc, flow=output)
)
outputs = pipe.execute(verbose=True)
```
Notice the use of the **or** operator operator. Also, notice how we can create temporary intermediate files by using **temp** as the path. This is useful because we didn't care about the sinkroute and dem_preproc grids and we didn't want to save them, we only wanted to use them as input for other tools.
To visualize the temporary files, access the **temp_files** attribute of SAGA.
```python
print(saga.temp_dir)
print(saga.temp_files)
```
After you are done, don't forget to clean up the temporary folder (if you used temporary files).
```python
saga.temp_dir_cleanup()
```
### Plotting
After the execution of a **Tool**, we can use the returned **Output** object to plot the results.
*The below example can be accessed [here](https://github.com/alecsandrei/PySAGA-cmd/blob/master/examples/plot.py).*
```python
# If you set a flag to the SAGA object that would stop the tool
# from working (like 'help'), make sure to remove it before accesing
# the tools, like so:
saga.flag = None
import matplotlib.pyplot as plt
from matplotlib import gridspec
# Defining tools.
slope_aspect_curvature = saga / 'ta_morphometry' / 0 # We can also use tool indices to access tools.
shading = saga / 'ta_lighting' / 'Analytical Hillshading'
# Executing tools.
output1 = slope_aspect_curvature.execute(verbose=True, elevation=dem, slope='temp.sdat')
elevation = output1.rasters['elevation']
slope = output1.rasters['slope']
output2 = shading.execute(verbose=True, elevation=dem, shade='temp.sdat', method='5')
shading = output2.rasters['shade']
fig = plt.figure(figsize=(15, 10))
gs = gridspec.GridSpec(2, 2, height_ratios=[1.5, 1])
ax1 = fig.add_subplot(gs[0])
ax2 = fig.add_subplot(gs[1])
ax3 = fig.add_subplot(gs[2])
ax4 = fig.add_subplot(gs[3])
# Maps
elevation.plot(ax=ax1, cmap='terrain', cbar_kwargs=dict(label='Elevation (meters)'))
slope.plot(ax=ax2, cmap='rainbow', cbar_kwargs=dict(label='Radians'))
shading.plot(ax=ax1, cbar=False, alpha=0.45)
ax1.set_title('Elevation map')
ax2.set_title('Slope map')
# Histograms
hist_kwargs = {
'bins': 15, 'alpha': 0.65,
'facecolor': '#2ab0ff', 'edgecolor': '#169acf',
'linewidth': 0.5
}
elevation.hist(ax=ax3, **hist_kwargs)
ax3.set_ylabel('Count')
ax3.set_xlabel('Elevation')
slope.hist(ax=ax4, **hist_kwargs)
ax4.set_ylabel('Count')
ax4.set_xlabel('Radians')
plt.tight_layout()
plt.show()
fig.savefig('../media/plot1.png', dpi=300, bbox_inches='tight')
saga.temp_dir_cleanup()
```
<img src="https://github.com/alecsandrei/PySAGA-cmd/blob/master/media/plot1.png?raw=true" />
For extra information on how to use the package, you can also look at the [notebooks](https://github.com/alecsandrei/PySAGA-cmd/tree/master/examples/notebooks) inside the examples folder on the Github page.
# TODOs
- [x] Implement recursive search for the saga_cmd file.
- [x] Improve the verbose behaviour of tool execution (add a progress bar?).
- [ ] Improve flags.
- [ ] Support the creation of toolchains?
- [x] Add "elapsed time" to progress bar.
Raw data
{
"_id": null,
"home_page": null,
"name": "PySAGA-cmd",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.9",
"maintainer_email": null,
"keywords": "PySAGA-cmd",
"author": null,
"author_email": "Alex-Andrei Cuvuliuc <cuvuliucalexandrei@gmail.com>",
"download_url": "https://files.pythonhosted.org/packages/27/dc/febcd5182b629ee55ec1f45886a338f2471b185fa0d1ac7fa62d70c90c18/pysaga_cmd-1.2.6.tar.gz",
"platform": null,
"description": "[![DOI](https://zenodo.org/badge/711593377.svg)](https://zenodo.org/doi/10.5281/zenodo.10673418)\n# PySAGA-cmd\nPySAGA-cmd is a simple way of running SAGA GIS tools using Python.\n\n## How to download\n\nBinary installers for the latest released version are available at the [Python Package Index (PyPI)](https://pypi.org/project/PySAGA-cmd/). If you want to have access to extra features (like plotting) you can download the extras as shown in the second command.\n```sh\npip install PySAGA-cmd\npip install PySAGA-cmd[extras]\n```\n\n## How to use the package\n\n### Choosing tools\n\nBefore you can use this package, you need to locate the **saga_cmd** in your system. For linux, it can be found somewhere in the `/usr/bin/` directory. For Windows, it is usually located in `C:\\Program Files\\SAGA`.\n\nAccesing tools can be done with the **truediv** operator (the forward slash **/**), like in the example below.\n\n```python\nfrom PySAGA_cmd import (\n SAGA,\n get_sample_dem\n)\n\n\nsaga = SAGA('/usr/bin/saga_cmd')\n\n# Choosing libraries.\npreprocessor = saga / 'ta_preprocessor'\n\n# Choosing tools.\nroute_detection = preprocessor / 'Sink Drainage Route Detection'\nsink_removal = preprocessor / 'Sink Removal'\nflow_accumulation = saga / 'ta_hydrology' / 'Flow Accumulation (Parallelizable)'\n```\n\n### Executing\n\nExecuting an object is straight forward and is done using the **execute** method. For the SAGA and Library objects no keyword arguments are required. For tools, just provide the required keyword arguments.\n\n```python\n# Executing the SAGA object. Useful when you want to see the available libraries.\nsaga_output = saga.execute()\nprint(saga_output.stdout)\n\n# Executing the Library object. Useful when you want to see the available tools.\npreprocessor_output = preprocessor.execute()\nprint(preprocessor_output.stdout)\n\n# Executing a Tool object.\ndem = get_sample_dem()\noutput = 'path/to/output.sdat'\noutput = route_detection.execute(verbose=True, elevation=dem, sinkroute=output)\nprint(output.stdout)\n```\n\n### Using flags\n\nYou can provide flags for SAGA, Library and Tool objects. To see what kind of flags can be used, look at the output of the following.\n\n```python\nsaga.flag = 'help'\nprint(saga.execute().stdout)\n```\n\n### Chaining commands\n\nChaining commands can be done with **PySAGA-cmd** with the **or** operator (the vertical line **|**). Consider the following example where the goal is to get a hydrologically preprocessed DEM and use that as input for the *Flow Accumulation (Parallelizable)* tool.\n\n```python\npipe = (\n route_detection(elevation=dem, sinkroute='temp.sdat') |\n sink_removal(dem=route_detection.elevation,\n sinkroute=route_detection.sinkroute,\n dem_preproc='temp.sdat') |\n flow_accumulation(dem=sink_removal.dem_preproc, flow=output)\n)\noutputs = pipe.execute(verbose=True)\n```\n\nNotice the use of the **or** operator operator. Also, notice how we can create temporary intermediate files by using **temp** as the path. This is useful because we didn't care about the sinkroute and dem_preproc grids and we didn't want to save them, we only wanted to use them as input for other tools.\n\nTo visualize the temporary files, access the **temp_files** attribute of SAGA.\n\n```python\nprint(saga.temp_dir)\nprint(saga.temp_files)\n```\n\nAfter you are done, don't forget to clean up the temporary folder (if you used temporary files).\n\n```python\nsaga.temp_dir_cleanup()\n```\n\n### Plotting\n\nAfter the execution of a **Tool**, we can use the returned **Output** object to plot the results.\n\n*The below example can be accessed [here](https://github.com/alecsandrei/PySAGA-cmd/blob/master/examples/plot.py).*\n\n```python\n# If you set a flag to the SAGA object that would stop the tool\n# from working (like 'help'), make sure to remove it before accesing\n# the tools, like so:\nsaga.flag = None\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import gridspec\n\n# Defining tools.\nslope_aspect_curvature = saga / 'ta_morphometry' / 0 # We can also use tool indices to access tools.\nshading = saga / 'ta_lighting' / 'Analytical Hillshading'\n\n# Executing tools.\noutput1 = slope_aspect_curvature.execute(verbose=True, elevation=dem, slope='temp.sdat')\nelevation = output1.rasters['elevation']\nslope = output1.rasters['slope']\n\noutput2 = shading.execute(verbose=True, elevation=dem, shade='temp.sdat', method='5')\nshading = output2.rasters['shade']\n\nfig = plt.figure(figsize=(15, 10))\n\ngs = gridspec.GridSpec(2, 2, height_ratios=[1.5, 1])\nax1 = fig.add_subplot(gs[0])\nax2 = fig.add_subplot(gs[1])\nax3 = fig.add_subplot(gs[2])\nax4 = fig.add_subplot(gs[3])\n\n# Maps\nelevation.plot(ax=ax1, cmap='terrain', cbar_kwargs=dict(label='Elevation (meters)'))\nslope.plot(ax=ax2, cmap='rainbow', cbar_kwargs=dict(label='Radians'))\nshading.plot(ax=ax1, cbar=False, alpha=0.45)\nax1.set_title('Elevation map')\nax2.set_title('Slope map')\n\n# Histograms\nhist_kwargs = {\n 'bins': 15, 'alpha': 0.65,\n 'facecolor': '#2ab0ff', 'edgecolor': '#169acf',\n 'linewidth': 0.5\n}\nelevation.hist(ax=ax3, **hist_kwargs)\nax3.set_ylabel('Count')\nax3.set_xlabel('Elevation')\nslope.hist(ax=ax4, **hist_kwargs)\nax4.set_ylabel('Count')\nax4.set_xlabel('Radians')\n\nplt.tight_layout()\nplt.show()\n\nfig.savefig('../media/plot1.png', dpi=300, bbox_inches='tight')\n\nsaga.temp_dir_cleanup()\n```\n<img src=\"https://github.com/alecsandrei/PySAGA-cmd/blob/master/media/plot1.png?raw=true\" />\n\nFor extra information on how to use the package, you can also look at the [notebooks](https://github.com/alecsandrei/PySAGA-cmd/tree/master/examples/notebooks) inside the examples folder on the Github page.\n\n\n# TODOs\n\n- [x] Implement recursive search for the saga_cmd file.\n- [x] Improve the verbose behaviour of tool execution (add a progress bar?).\n- [ ] Improve flags.\n- [ ] Support the creation of toolchains?\n- [x] Add \"elapsed time\" to progress bar.\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "A package that allows you to run SAGA GIS tools using Python.",
"version": "1.2.6",
"project_urls": {
"Homepage": "https://github.com/alecsandrei/PySAGA-cmd"
},
"split_keywords": [
"pysaga-cmd"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "d20bf9c08e2f6c7e7187f09bacba70fbe21d02f6730803cf09f0702676e38480",
"md5": "7ebbc95872d31fb7b929d599beaf518b",
"sha256": "103d8798bb09c00e9b06a3f149ef4e4ec4555ecb39cb689274d475b6bce9f279"
},
"downloads": -1,
"filename": "PySAGA_cmd-1.2.6-py3-none-any.whl",
"has_sig": false,
"md5_digest": "7ebbc95872d31fb7b929d599beaf518b",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.9",
"size": 119027,
"upload_time": "2024-06-29T06:19:40",
"upload_time_iso_8601": "2024-06-29T06:19:40.833425Z",
"url": "https://files.pythonhosted.org/packages/d2/0b/f9c08e2f6c7e7187f09bacba70fbe21d02f6730803cf09f0702676e38480/PySAGA_cmd-1.2.6-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "27dcfebcd5182b629ee55ec1f45886a338f2471b185fa0d1ac7fa62d70c90c18",
"md5": "8be9e95d2cc9598db37dd05e430505eb",
"sha256": "de1e30d4c4f1f1232a79de83f5af24ede27a5aa243785611913748599658bc28"
},
"downloads": -1,
"filename": "pysaga_cmd-1.2.6.tar.gz",
"has_sig": false,
"md5_digest": "8be9e95d2cc9598db37dd05e430505eb",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.9",
"size": 120707,
"upload_time": "2024-06-29T06:19:43",
"upload_time_iso_8601": "2024-06-29T06:19:43.245161Z",
"url": "https://files.pythonhosted.org/packages/27/dc/febcd5182b629ee55ec1f45886a338f2471b185fa0d1ac7fa62d70c90c18/pysaga_cmd-1.2.6.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-06-29 06:19:43",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "alecsandrei",
"github_project": "PySAGA-cmd",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"lcname": "pysaga-cmd"
}