├── test
├── tenbytenraster.keywords
├── __init__.py
├── tenbytenraster.prj
├── tenbytenraster.asc
├── tenbytenraster.asc.aux.xml
├── tenbytenraster.lic
├── tenbytenraster.qml
├── test_translations.py
├── utilities.py
├── test_init.py
├── test_qgis_environment.py
├── test_least_cost_path_algorithm.py
└── qgis_interface.py
├── icon.png
├── example
├── images
│ ├── result.png
│ └── interface.png
└── test_data
│ └── 30_30
│ ├── end.dbf
│ ├── end.shp
│ ├── end.shx
│ ├── start.dbf
│ ├── ssdem.tif
│ ├── start.shp
│ ├── start.shx
│ ├── test1.tif
│ ├── test2.tif
│ ├── test3.tif
│ ├── ssdem.tif.aux.xml
│ ├── test1.tif.aux.xml
│ ├── test2.tif.aux.xml
│ ├── test3.tif.aux.xml
│ ├── end.prj
│ ├── start.prj
│ ├── end.qpj
│ └── start.qpj
├── scripts
├── compile-strings.sh
├── run-env-linux.sh
└── update-strings.sh
├── i18n
└── af.ts
├── help
├── source
│ ├── index.rst
│ └── conf.py
├── make.bat
└── Makefile
├── README.md
├── metadata.txt
├── __init__.py
├── least_cost_path.py
├── least_cost_path_provider.py
├── plugin_upload.py
├── dijkstra_algorithm.py
├── pylintrc
├── least_cost_path_algorithm.py
└── LICENSE
/test/tenbytenraster.keywords:
--------------------------------------------------------------------------------
1 | title: Tenbytenraster
2 |
--------------------------------------------------------------------------------
/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gooong/LeastCostPath/HEAD/icon.png
--------------------------------------------------------------------------------
/example/images/result.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gooong/LeastCostPath/HEAD/example/images/result.png
--------------------------------------------------------------------------------
/example/images/interface.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gooong/LeastCostPath/HEAD/example/images/interface.png
--------------------------------------------------------------------------------
/example/test_data/30_30/end.dbf:
--------------------------------------------------------------------------------
1 | v A id N
2 |
1
--------------------------------------------------------------------------------
/example/test_data/30_30/end.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gooong/LeastCostPath/HEAD/example/test_data/30_30/end.shp
--------------------------------------------------------------------------------
/example/test_data/30_30/end.shx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gooong/LeastCostPath/HEAD/example/test_data/30_30/end.shx
--------------------------------------------------------------------------------
/example/test_data/30_30/start.dbf:
--------------------------------------------------------------------------------
1 | v A id N
2 |
1
--------------------------------------------------------------------------------
/example/test_data/30_30/ssdem.tif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gooong/LeastCostPath/HEAD/example/test_data/30_30/ssdem.tif
--------------------------------------------------------------------------------
/example/test_data/30_30/start.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gooong/LeastCostPath/HEAD/example/test_data/30_30/start.shp
--------------------------------------------------------------------------------
/example/test_data/30_30/start.shx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gooong/LeastCostPath/HEAD/example/test_data/30_30/start.shx
--------------------------------------------------------------------------------
/example/test_data/30_30/test1.tif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gooong/LeastCostPath/HEAD/example/test_data/30_30/test1.tif
--------------------------------------------------------------------------------
/example/test_data/30_30/test2.tif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gooong/LeastCostPath/HEAD/example/test_data/30_30/test2.tif
--------------------------------------------------------------------------------
/example/test_data/30_30/test3.tif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gooong/LeastCostPath/HEAD/example/test_data/30_30/test3.tif
--------------------------------------------------------------------------------
/test/__init__.py:
--------------------------------------------------------------------------------
1 | # import qgis libs so that ve set the correct sip api version
2 | import qgis # pylint: disable=W0611 # NOQA
--------------------------------------------------------------------------------
/test/tenbytenraster.prj:
--------------------------------------------------------------------------------
1 | GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]]
--------------------------------------------------------------------------------
/scripts/compile-strings.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | LRELEASE=$1
3 | LOCALES=$2
4 |
5 |
6 | for LOCALE in ${LOCALES}
7 | do
8 | echo "Processing: ${LOCALE}.ts"
9 | # Note we don't use pylupdate with qt .pro file approach as it is flakey
10 | # about what is made available.
11 | $LRELEASE i18n/${LOCALE}.ts
12 | done
13 |
--------------------------------------------------------------------------------
/example/test_data/30_30/ssdem.tif.aux.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 2080
5 | 1700.8949011446
6 | 1513
7 | 108.61224879334
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/example/test_data/30_30/test1.tif.aux.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 2080
5 | 1605.5556711759
6 | 1
7 | 401.14511073473
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/example/test_data/30_30/test2.tif.aux.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 2080
5 | 1590.0176899063
6 | 1
7 | 426.06882764284
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/example/test_data/30_30/test3.tif.aux.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 2080
5 | 1698.0096774194
6 | 1513
7 | 107.81807114527
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/i18n/af.ts:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | @default
5 |
6 |
7 | Good morning
8 | Goeie more
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/test/tenbytenraster.asc:
--------------------------------------------------------------------------------
1 | NCOLS 10
2 | NROWS 10
3 | XLLCENTER 1535380.000000
4 | YLLCENTER 5083260.000000
5 | DX 10
6 | DY 10
7 | NODATA_VALUE -9999
8 | 0 1 2 3 4 5 6 7 8 9
9 | 0 1 2 3 4 5 6 7 8 9
10 | 0 1 2 3 4 5 6 7 8 9
11 | 0 1 2 3 4 5 6 7 8 9
12 | 0 1 2 3 4 5 6 7 8 9
13 | 0 1 2 3 4 5 6 7 8 9
14 | 0 1 2 3 4 5 6 7 8 9
15 | 0 1 2 3 4 5 6 7 8 9
16 | 0 1 2 3 4 5 6 7 8 9
17 | 0 1 2 3 4 5 6 7 8 9
18 | CRS
19 | NOTES
20 |
--------------------------------------------------------------------------------
/example/test_data/30_30/end.prj:
--------------------------------------------------------------------------------
1 | PROJCS["Beijing_1954_3_degree_Gauss_Kruger_CM_102E",GEOGCS["GCS_Beijing 1954",DATUM["D_Beijing_1954",SPHEROID["Krasovsky_1940",6378245,298.3]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",102],PARAMETER["scale_factor",1],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["Meter",1]]
--------------------------------------------------------------------------------
/example/test_data/30_30/start.prj:
--------------------------------------------------------------------------------
1 | PROJCS["Beijing_1954_3_degree_Gauss_Kruger_CM_102E",GEOGCS["GCS_Beijing 1954",DATUM["D_Beijing_1954",SPHEROID["Krasovsky_1940",6378245,298.3]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",102],PARAMETER["scale_factor",1],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["Meter",1]]
--------------------------------------------------------------------------------
/test/tenbytenraster.asc.aux.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | Point
4 |
5 |
6 |
7 | 9
8 | 4.5
9 | 0
10 | 2.872281323269
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/help/source/index.rst:
--------------------------------------------------------------------------------
1 | .. LeastCostPath documentation master file, created by
2 | sphinx-quickstart on Sun Feb 12 17:11:03 2012.
3 | You can adapt this file completely to your liking, but it should at least
4 | contain the root `toctree` directive.
5 |
6 | Welcome to LeastCostPath's documentation!
7 | ============================================
8 |
9 | Contents:
10 |
11 | .. toctree::
12 | :maxdepth: 2
13 |
14 | Indices and tables
15 | ==================
16 |
17 | * :ref:`genindex`
18 | * :ref:`modindex`
19 | * :ref:`search`
20 |
21 |
--------------------------------------------------------------------------------
/example/test_data/30_30/end.qpj:
--------------------------------------------------------------------------------
1 | PROJCS["Beijing 1954 / 3-degree Gauss-Kruger CM 102E",GEOGCS["Beijing 1954",DATUM["Beijing_1954",SPHEROID["Krassowsky 1940",6378245,298.3,AUTHORITY["EPSG","7024"]],TOWGS84[15.8,-154.4,-82.3,0,0,0,0],AUTHORITY["EPSG","6214"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4214"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",102],PARAMETER["scale_factor",1],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","2431"]]
2 |
--------------------------------------------------------------------------------
/example/test_data/30_30/start.qpj:
--------------------------------------------------------------------------------
1 | PROJCS["Beijing 1954 / 3-degree Gauss-Kruger CM 102E",GEOGCS["Beijing 1954",DATUM["Beijing_1954",SPHEROID["Krassowsky 1940",6378245,298.3,AUTHORITY["EPSG","7024"]],TOWGS84[15.8,-154.4,-82.3,0,0,0,0],AUTHORITY["EPSG","6214"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4214"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",102],PARAMETER["scale_factor",1],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","2431"]]
2 |
--------------------------------------------------------------------------------
/test/tenbytenraster.lic:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Tim Sutton, Linfiniti Consulting CC
5 |
6 |
7 |
8 | tenbytenraster.asc
9 | 2700044251
10 | Yes
11 | Tim Sutton
12 | Tim Sutton (QGIS Source Tree)
13 | Tim Sutton
14 | This data is publicly available from QGIS Source Tree. The original
15 | file was created and contributed to QGIS by Tim Sutton.
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/scripts/run-env-linux.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | QGIS_PREFIX_PATH=/usr/local/qgis-2.0
4 | if [ -n "$1" ]; then
5 | QGIS_PREFIX_PATH=$1
6 | fi
7 |
8 | echo ${QGIS_PREFIX_PATH}
9 |
10 |
11 | export QGIS_PREFIX_PATH=${QGIS_PREFIX_PATH}
12 | export QGIS_PATH=${QGIS_PREFIX_PATH}
13 | export LD_LIBRARY_PATH=${QGIS_PREFIX_PATH}/lib
14 | export PYTHONPATH=${QGIS_PREFIX_PATH}/share/qgis/python:${QGIS_PREFIX_PATH}/share/qgis/python/plugins:${PYTHONPATH}
15 |
16 | echo "QGIS PATH: $QGIS_PREFIX_PATH"
17 | export QGIS_DEBUG=0
18 | export QGIS_LOG_FILE=/tmp/inasafe/realtime/logs/qgis.log
19 |
20 | export PATH=${QGIS_PREFIX_PATH}/bin:$PATH
21 |
22 | echo "This script is intended to be sourced to set up your shell to"
23 | echo "use a QGIS 2.0 built in $QGIS_PREFIX_PATH"
24 | echo
25 | echo "To use it do:"
26 | echo "source $BASH_SOURCE /your/optional/install/path"
27 | echo
28 | echo "Then use the make file supplied here e.g. make guitest"
29 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## The Least Cost Path Plugin for QGIS
2 |
3 |
4 | This algorithm finds the least cost path with given cost raster and points.
5 |
6 | 
7 | 
8 |
9 | Please ensure all the input layers have the same CRS.
10 |
11 | - Cost raster layer: Numeric raster layer that represents the cost of each spatial unit. It should not contains negative value. Pixel with `NoData` value represent it is unreachable.
12 |
13 | - Cost raster band: The input band of the cost raster.
14 |
15 | - Start-point layer: Layer that contains just one start point.
16 |
17 | - End-point(s) layer: Layer that contains the destination point(s).
18 |
19 | - Only connect with the nearest end points: If more than one destination are provided, it will find the least cost path to all the end points by default. If enabled, the least cost path will only connect start point with the nearest end point.
20 |
21 | - \[Optional\] Include liner referencing (PolylineM type): If selected, this algorithm will output the least cost path in `PolylineM` type, with the accumulated cost as linear referencing value.
22 |
23 |
24 | **Contributors:**
25 |
26 | @gjx-123, @ClaireXing, @GXIU, @Shangss, @Gooong
27 |
--------------------------------------------------------------------------------
/metadata.txt:
--------------------------------------------------------------------------------
1 | # This file contains metadata for your plugin. Since
2 | # version 2.0 of QGIS this is the proper way to supply
3 | # information about a plugin. The old method of
4 | # embedding metadata in __init__.py will
5 | # is no longer supported since version 2.0.
6 |
7 | # This file should be included when you package your plugin.# Mandatory items:
8 |
9 | [general]
10 | name=Least-Cost Path
11 | qgisMinimumVersion=3.0
12 | description=Find the least cost path with given cost raster and points
13 | version=1.1
14 | author=FlowMap Group@SESS-PKU
15 | email=xurigong@gmail.com
16 |
17 | about=This plugin finds the least cost path with given cost raster and points. Open "Processing Toolbox -- Cost distance analysis" to use this plugin after installation.
18 |
19 | tracker=https://github.com/Gooong/LeastCostPath/issues
20 | repository=https://github.com/Gooong/LeastCostPath
21 | # End of mandatory metadata
22 |
23 | # Recommended items:
24 |
25 | # Uncomment the following line and add your changelog:
26 | # changelog=
27 |
28 | # Tags are comma separated with spaces allowed
29 | tags=least cost path distance raster analysis road
30 |
31 | # The plugin is compatible with qgis_process
32 | hasProcessingProvider=yes
33 |
34 | homepage=https://github.com/Gooong/LeastCostPath
35 | category=Analysis
36 | icon=icon.png
37 | # experimental flag
38 | experimental=False
39 |
40 | # deprecated flag (applies to the whole plugin, not just a single version)
41 | deprecated=False
42 |
43 |
--------------------------------------------------------------------------------
/scripts/update-strings.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | LOCALES=$*
3 |
4 | # Get newest .py files so we don't update strings unnecessarily
5 |
6 | CHANGED_FILES=0
7 | PYTHON_FILES=`find . -regex ".*\(ui\|py\)$" -type f`
8 | for PYTHON_FILE in $PYTHON_FILES
9 | do
10 | CHANGED=$(stat -c %Y $PYTHON_FILE)
11 | if [ ${CHANGED} -gt ${CHANGED_FILES} ]
12 | then
13 | CHANGED_FILES=${CHANGED}
14 | fi
15 | done
16 |
17 | # Qt translation stuff
18 | # for .ts file
19 | UPDATE=false
20 | for LOCALE in ${LOCALES}
21 | do
22 | TRANSLATION_FILE="i18n/$LOCALE.ts"
23 | if [ ! -f ${TRANSLATION_FILE} ]
24 | then
25 | # Force translation string collection as we have a new language file
26 | touch ${TRANSLATION_FILE}
27 | UPDATE=true
28 | break
29 | fi
30 |
31 | MODIFICATION_TIME=$(stat -c %Y ${TRANSLATION_FILE})
32 | if [ ${CHANGED_FILES} -gt ${MODIFICATION_TIME} ]
33 | then
34 | # Force translation string collection as a .py file has been updated
35 | UPDATE=true
36 | break
37 | fi
38 | done
39 |
40 | if [ ${UPDATE} == true ]
41 | # retrieve all python files
42 | then
43 | print ${PYTHON_FILES}
44 | # update .ts
45 | echo "Please provide translations by editing the translation files below:"
46 | for LOCALE in ${LOCALES}
47 | do
48 | echo "i18n/"${LOCALE}".ts"
49 | # Note we don't use pylupdate with qt .pro file approach as it is flakey
50 | # about what is made available.
51 | pylupdate4 -noobsolete ${PYTHON_FILES} -ts i18n/${LOCALE}.ts
52 | done
53 | else
54 | echo "No need to edit any translation files (.ts) because no python files"
55 | echo "has been updated since the last update translation. "
56 | fi
57 |
--------------------------------------------------------------------------------
/test/tenbytenraster.qml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 | 0
26 |
27 |
--------------------------------------------------------------------------------
/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | /***************************************************************************
4 | LeastCostPath
5 | A QGIS plugin
6 | Find the least cost path with given cost raster and points
7 | Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
8 | -------------------
9 | begin : 2018-12-12
10 | copyright : (C) 2018 by FlowMap Group@SESS.PKU
11 | email : xurigong@gmail.com
12 | ***************************************************************************/
13 |
14 | /***************************************************************************
15 | * *
16 | * This program is free software; you can redistribute it and/or modify *
17 | * it under the terms of the GNU General Public License as published by *
18 | * the Free Software Foundation; either version 2 of the License, or *
19 | * (at your option) any later version. *
20 | * *
21 | ***************************************************************************/
22 | This script initializes the plugin, making it known to QGIS.
23 | """
24 |
25 | __author__ = 'FlowMap Group@SESS.PKU'
26 | __date__ = '2018-12-12'
27 | __copyright__ = '(C) 2018 by FlowMap Group@SESS.PKU'
28 |
29 |
30 | # noinspection PyPep8Naming
31 | def classFactory(iface): # pylint: disable=invalid-name
32 | """Load LeastCostPath class from file LeastCostPath.
33 |
34 | :param iface: A QGIS interface instance.
35 | :type iface: QgsInterface
36 | """
37 | #
38 | from .least_cost_path import LeastCostPathPlugin
39 | return LeastCostPathPlugin()
40 |
--------------------------------------------------------------------------------
/test/test_translations.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | """Safe Translations Test.
3 |
4 | .. note:: This program is free software; you can redistribute it and/or modify
5 | it under the terms of the GNU General Public License as published by
6 | the Free Software Foundation; either version 2 of the License, or
7 | (at your option) any later version.
8 |
9 | """
10 | from .utilities import get_qgis_app
11 |
12 | __author__ = 'ismailsunni@yahoo.co.id'
13 | __date__ = '12/10/2011'
14 | __copyright__ = ('Copyright 2012, Australia Indonesia Facility for '
15 | 'Disaster Reduction')
16 | import unittest
17 | import os
18 |
19 | from PyQt5.QtCore import QCoreApplication, QTranslator
20 |
21 | QGIS_APP = get_qgis_app()
22 |
23 |
24 | class SafeTranslationsTest(unittest.TestCase):
25 | """Test translations work."""
26 |
27 | def setUp(self):
28 | """Runs before each test."""
29 | if 'LANG' in iter(os.environ.keys()):
30 | os.environ.__delitem__('LANG')
31 |
32 | def tearDown(self):
33 | """Runs after each test."""
34 | if 'LANG' in iter(os.environ.keys()):
35 | os.environ.__delitem__('LANG')
36 |
37 | def test_qgis_translations(self):
38 | """Test that translations work."""
39 | parent_path = os.path.join(__file__, os.path.pardir, os.path.pardir)
40 | dir_path = os.path.abspath(parent_path)
41 | file_path = os.path.join(
42 | dir_path, 'i18n', 'af.qm')
43 | translator = QTranslator()
44 | translator.load(file_path)
45 | QCoreApplication.installTranslator(translator)
46 |
47 | expected_message = 'Goeie more'
48 | real_message = QCoreApplication.translate("@default", 'Good morning')
49 | self.assertEqual(real_message, expected_message)
50 |
51 |
52 | if __name__ == "__main__":
53 | suite = unittest.makeSuite(SafeTranslationsTest)
54 | runner = unittest.TextTestRunner(verbosity=2)
55 | runner.run(suite)
56 |
--------------------------------------------------------------------------------
/test/utilities.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | """Common functionality used by regression tests."""
3 |
4 | import sys
5 | import logging
6 |
7 |
8 | LOGGER = logging.getLogger('QGIS')
9 | QGIS_APP = None # Static variable used to hold hand to running QGIS app
10 | CANVAS = None
11 | PARENT = None
12 | IFACE = None
13 |
14 |
15 | def get_qgis_app():
16 | """ Start one QGIS application to test against.
17 |
18 | :returns: Handle to QGIS app, canvas, iface and parent. If there are any
19 | errors the tuple members will be returned as None.
20 | :rtype: (QgsApplication, CANVAS, IFACE, PARENT)
21 |
22 | If QGIS is already running the handle to that app will be returned.
23 | """
24 |
25 | try:
26 | from PyQt5 import QtGui, QtCore
27 | from qgis.core import QgsApplication
28 | from qgis.gui import QgsMapCanvas
29 | from .qgis_interface import QgisInterface
30 | except ImportError:
31 | return None, None, None, None
32 |
33 | global QGIS_APP # pylint: disable=W0603
34 |
35 | if QGIS_APP is None:
36 | gui_flag = True # All test will run qgis in gui mode
37 | #noinspection PyPep8Naming
38 | QGIS_APP = QgsApplication(sys.argv, gui_flag)
39 | # Make sure QGIS_PREFIX_PATH is set in your env if needed!
40 | QGIS_APP.initQgis()
41 | s = QGIS_APP.showSettings()
42 | LOGGER.debug(s)
43 |
44 | global PARENT # pylint: disable=W0603
45 | if PARENT is None:
46 | #noinspection PyPep8Naming
47 | PARENT = QtGui.QWidget()
48 |
49 | global CANVAS # pylint: disable=W0603
50 | if CANVAS is None:
51 | #noinspection PyPep8Naming
52 | CANVAS = QgsMapCanvas(PARENT)
53 | CANVAS.resize(QtCore.QSize(400, 400))
54 |
55 | global IFACE # pylint: disable=W0603
56 | if IFACE is None:
57 | # QgisInterface is a stub implementation of the QGIS plugin interface
58 | #noinspection PyPep8Naming
59 | IFACE = QgisInterface(CANVAS)
60 |
61 | return QGIS_APP, CANVAS, IFACE, PARENT
62 |
--------------------------------------------------------------------------------
/test/test_init.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | """Tests QGIS plugin init."""
3 |
4 | __author__ = 'Tim Sutton '
5 | __revision__ = '$Format:%H$'
6 | __date__ = '17/10/2010'
7 | __license__ = "GPL"
8 | __copyright__ = 'Copyright 2012, Australia Indonesia Facility for '
9 | __copyright__ += 'Disaster Reduction'
10 |
11 | import os
12 | import unittest
13 | import logging
14 | import configparser
15 |
16 | LOGGER = logging.getLogger('QGIS')
17 |
18 |
19 | class TestInit(unittest.TestCase):
20 | """Test that the plugin init is usable for QGIS.
21 |
22 | Based heavily on the validator class by Alessandro
23 | Passoti available here:
24 |
25 | http://github.com/qgis/qgis-django/blob/master/qgis-app/
26 | plugins/validator.py
27 |
28 | """
29 |
30 | def test_read_init(self):
31 | """Test that the plugin __init__ will validate on plugins.qgis.org."""
32 |
33 | # You should update this list according to the latest in
34 | # https://github.com/qgis/qgis-django/blob/master/qgis-app/
35 | # plugins/validator.py
36 |
37 | required_metadata = [
38 | 'name',
39 | 'description',
40 | 'version',
41 | 'qgisMinimumVersion',
42 | 'email',
43 | 'author']
44 |
45 | file_path = os.path.abspath(os.path.join(
46 | os.path.dirname(__file__), os.pardir,
47 | 'metadata.txt'))
48 | LOGGER.info(file_path)
49 | metadata = []
50 | parser = configparser.ConfigParser()
51 | parser.optionxform = str
52 | parser.read(file_path)
53 | message = 'Cannot find a section named "general" in %s' % file_path
54 | assert parser.has_section('general'), message
55 | metadata.extend(parser.items('general'))
56 |
57 | for expectation in required_metadata:
58 | message = ('Cannot find metadata "%s" in metadata source (%s).' % (
59 | expectation, file_path))
60 |
61 | self.assertIn(expectation, dict(metadata), message)
62 |
63 | if __name__ == '__main__':
64 | unittest.main()
65 |
--------------------------------------------------------------------------------
/test/test_qgis_environment.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | """Tests for QGIS functionality.
3 |
4 |
5 | .. note:: This program is free software; you can redistribute it and/or modify
6 | it under the terms of the GNU General Public License as published by
7 | the Free Software Foundation; either version 2 of the License, or
8 | (at your option) any later version.
9 |
10 | """
11 | __author__ = 'tim@linfiniti.com'
12 | __date__ = '20/01/2011'
13 | __copyright__ = ('Copyright 2012, Australia Indonesia Facility for '
14 | 'Disaster Reduction')
15 |
16 | import os
17 | import unittest
18 | from qgis.core import (
19 | QgsProviderRegistry,
20 | QgsCoordinateReferenceSystem,
21 | QgsRasterLayer)
22 |
23 | from .utilities import get_qgis_app
24 | QGIS_APP = get_qgis_app()
25 |
26 |
27 | class QGISTest(unittest.TestCase):
28 | """Test the QGIS Environment"""
29 |
30 | def test_qgis_environment(self):
31 | """QGIS environment has the expected providers"""
32 |
33 | r = QgsProviderRegistry.instance()
34 | self.assertIn('gdal', r.providerList())
35 | self.assertIn('ogr', r.providerList())
36 | self.assertIn('postgres', r.providerList())
37 |
38 | def test_projection(self):
39 | """Test that QGIS properly parses a wkt string.
40 | """
41 | crs = QgsCoordinateReferenceSystem()
42 | wkt = (
43 | 'GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",'
44 | 'SPHEROID["WGS_1984",6378137.0,298.257223563]],'
45 | 'PRIMEM["Greenwich",0.0],UNIT["Degree",'
46 | '0.0174532925199433]]')
47 | crs.createFromWkt(wkt)
48 | auth_id = crs.authid()
49 | expected_auth_id = 'EPSG:4326'
50 | self.assertEqual(auth_id, expected_auth_id)
51 |
52 | # now test for a loaded layer
53 | path = os.path.join(os.path.dirname(__file__), 'tenbytenraster.asc')
54 | title = 'TestRaster'
55 | layer = QgsRasterLayer(path, title)
56 | auth_id = layer.crs().authid()
57 | self.assertEqual(auth_id, expected_auth_id)
58 |
59 | if __name__ == '__main__':
60 | unittest.main()
61 |
--------------------------------------------------------------------------------
/least_cost_path.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | """
4 | /***************************************************************************
5 | LeastCostPath
6 | A QGIS plugin
7 | Find the least cost path with given cost raster and points
8 | Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
9 | -------------------
10 | begin : 2018-12-12
11 | copyright : (C) 2018 by FlowMap Group@SESS.PKU
12 | email : xurigong@gmail.com
13 | ***************************************************************************/
14 |
15 | /***************************************************************************
16 | * *
17 | * This program is free software; you can redistribute it and/or modify *
18 | * it under the terms of the GNU General Public License as published by *
19 | * the Free Software Foundation; either version 2 of the License, or *
20 | * (at your option) any later version. *
21 | * *
22 | ***************************************************************************/
23 | """
24 |
25 | __author__ = 'FlowMap Group@SESS.PKU'
26 | __date__ = '2018-12-12'
27 | __copyright__ = '(C) 2018 by FlowMap Group@SESS.PKU'
28 |
29 | # This will get replaced with a git SHA1 when you do a git archive
30 |
31 | __revision__ = '$Format:%H$'
32 |
33 | import os
34 | import sys
35 | import inspect
36 |
37 | from qgis.core import QgsProcessingAlgorithm, QgsApplication
38 | from .least_cost_path_provider import LeastCostPathProvider
39 |
40 | cmd_folder = os.path.split(inspect.getfile(inspect.currentframe()))[0]
41 |
42 | if cmd_folder not in sys.path:
43 | sys.path.insert(0, cmd_folder)
44 |
45 |
46 | class LeastCostPathPlugin(object):
47 |
48 | def __init__(self):
49 | self.provider = LeastCostPathProvider()
50 |
51 | def initGui(self):
52 | QgsApplication.processingRegistry().addProvider(self.provider)
53 |
54 | def initProcessing(self):
55 | QgsApplication.processingRegistry().addProvider(self.provider)
56 |
57 | def unload(self):
58 | QgsApplication.processingRegistry().removeProvider(self.provider)
59 |
--------------------------------------------------------------------------------
/least_cost_path_provider.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | """
4 | /***************************************************************************
5 | LeastCostPath
6 | A QGIS plugin
7 | Find the least cost path with given cost raster and points
8 | Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
9 | -------------------
10 | begin : 2018-12-12
11 | copyright : (C) 2018 by FlowMap Group@SESS.PKU
12 | email : xurigong@gmail.com
13 | ***************************************************************************/
14 |
15 | /***************************************************************************
16 | * *
17 | * This program is free software; you can redistribute it and/or modify *
18 | * it under the terms of the GNU General Public License as published by *
19 | * the Free Software Foundation; either version 2 of the License, or *
20 | * (at your option) any later version. *
21 | * *
22 | ***************************************************************************/
23 | """
24 |
25 | __author__ = 'FlowMap Group@SESS.PKU'
26 | __date__ = '2018-12-12'
27 | __copyright__ = '(C) 2018 by FlowMap Group@SESS.PKU'
28 |
29 | # This will get replaced with a git SHA1 when you do a git archive
30 |
31 | __revision__ = '$Format:%H$'
32 |
33 | from qgis.core import QgsProcessingProvider
34 | from .least_cost_path_algorithm import LeastCostPathAlgorithm
35 |
36 |
37 | class LeastCostPathProvider(QgsProcessingProvider):
38 |
39 | def __init__(self):
40 | QgsProcessingProvider.__init__(self)
41 |
42 |
43 | def unload(self):
44 | """
45 | Unloads the provider. Any tear-down steps required by the provider
46 | should be implemented here.
47 | """
48 | pass
49 |
50 | def loadAlgorithms(self):
51 | """
52 | Loads all algorithms belonging to this provider.
53 | """
54 |
55 | self.addAlgorithm(LeastCostPathAlgorithm())
56 |
57 | def id(self):
58 | """
59 | Returns the unique provider id, used for identifying the provider. This
60 | string should be a unique, short, character only string, eg "qgis" or
61 | "gdal". This string should not be localised.
62 | """
63 | return 'Cost distance analysis'
64 |
65 | def name(self):
66 | """
67 | Returns the provider name, which is used to describe the provider
68 | within the GUI.
69 |
70 | This string should be short (e.g. "Lastools") and localised.
71 | """
72 | return self.tr('Cost distance analysis')
73 |
74 | def longName(self):
75 | """
76 | Returns the a longer version of the provider name, which can include
77 | extra details such as version numbers. E.g. "Lastools LIDAR tools
78 | (version 2.2.1)". This string should be localised. The default
79 | implementation returns the same string as name().
80 | """
81 | return self.name()
82 |
--------------------------------------------------------------------------------
/test/test_least_cost_path_algorithm.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | """
4 | /***************************************************************************
5 | LeastCostPath
6 | A QGIS plugin
7 | Find the least cost path with given cost raster and points
8 | Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
9 | -------------------
10 | begin : 2018-12-12
11 | copyright : (C) 2018 by FlowMap Group@SESS.PKU
12 | email : xurigong@gmail.com
13 | ***************************************************************************/
14 |
15 | /***************************************************************************
16 | * *
17 | * This program is free software; you can redistribute it and/or modify *
18 | * it under the terms of the GNU General Public License as published by *
19 | * the Free Software Foundation; either version 2 of the License, or *
20 | * (at your option) any later version. *
21 | * *
22 | ***************************************************************************/
23 | """
24 |
25 | __author__ = 'FlowMap Group@SESS.PKU'
26 | __date__ = '2018-12-12'
27 | __copyright__ = '(C) 2018 by FlowMap Group@SESS.PKU'
28 |
29 | import unittest
30 | from ..dijkstra_algorithm import dijkstra
31 | from math import sqrt
32 |
33 |
34 | class LeastCostPathAlgorithmTest(unittest.TestCase):
35 | """Test least cost path algorithm"""
36 |
37 | def test_least_cost_path(self):
38 | matrix1 = [[1, 1, 1],
39 | [1, 1, 1],
40 | [1, 1, 1]]
41 | matrix2 = [[1, 1, 1],
42 | [1, 100, 1],
43 | [1, 1, 1]]
44 | matrix3 = [[1, 1, 1],
45 | [1, None, 1],
46 | [1, 1, 1]]
47 |
48 | start = (0, 0)
49 | ends = [(2, 2)]
50 | path, cost = dijkstra(start, ends, matrix1)
51 | self.assertEqual(cost, sqrt(2) * 2)
52 |
53 | path, cost = dijkstra(start, ends, matrix2)
54 | self.assertEqual(cost, sqrt(2) + 2)
55 |
56 | path, cost = dijkstra(start, ends, matrix3)
57 | self.assertEqual(cost, sqrt(2) + 2)
58 |
59 | ends = [(1, 1), (2, 2)]
60 | path, cost = dijkstra(start, ends, matrix2)
61 | self.assertEqual(cost, sqrt(2) + 2)
62 |
63 | # end points overlap with start point
64 | ends = [(0, 0), (2, 2)]
65 | path, cost = dijkstra(start, ends, matrix2)
66 | self.assertEqual(cost, 0)
67 | self.assertEqual(len(path), 1)
68 |
69 | def test_not_exists_least_cost_path(self):
70 |
71 | # not reachable
72 | matrix1 = [[1, None, 1],
73 | [1, None, 1],
74 | [1, None, 1]]
75 |
76 | # start is Nodata
77 | matrix2 = [[None, 1, 1],
78 | [1, 1, 1],
79 | [1, 1, 1]]
80 |
81 | # end is Nodata
82 | matrix3 = [[1, 1, 1],
83 | [1, 1, 1],
84 | [1, 1, None]]
85 |
86 | start = (0, 0)
87 | ends = [(2, 2)]
88 | path, cost = dijkstra(start, ends, matrix1)
89 | self.assertIsNone(cost)
90 |
91 | path, cost = dijkstra(start, ends, matrix2)
92 | self.assertIsNone(cost)
93 |
94 | path, cost = dijkstra(start, ends, matrix3)
95 | self.assertIsNone(cost)
96 |
--------------------------------------------------------------------------------
/plugin_upload.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | """This script uploads a plugin package on the server.
4 | Authors: A. Pasotti, V. Picavet
5 | git sha : $TemplateVCSFormat
6 | """
7 |
8 | import sys
9 | import getpass
10 | import xmlrpc.client
11 | from optparse import OptionParser
12 |
13 | # Configuration
14 | PROTOCOL = 'http'
15 | SERVER = 'plugins.qgis.org'
16 | PORT = '80'
17 | ENDPOINT = '/plugins/RPC2/'
18 | VERBOSE = False
19 |
20 |
21 | def main(parameters, arguments):
22 | """Main entry point.
23 |
24 | :param parameters: Command line parameters.
25 | :param arguments: Command line arguments.
26 | """
27 | address = "%s://%s:%s@%s:%s%s" % (
28 | PROTOCOL,
29 | parameters.username,
30 | parameters.password,
31 | parameters.server,
32 | parameters.port,
33 | ENDPOINT)
34 | print("Connecting to: %s" % hide_password(address))
35 |
36 | server = xmlrpc.client.ServerProxy(address, verbose=VERBOSE)
37 |
38 | try:
39 | plugin_id, version_id = server.plugin.upload(
40 | xmlrpc.client.Binary(open(arguments[0]).read()))
41 | print("Plugin ID: %s" % plugin_id)
42 | print("Version ID: %s" % version_id)
43 | except xmlrpc.client.ProtocolError as err:
44 | print("A protocol error occurred")
45 | print("URL: %s" % hide_password(err.url, 0))
46 | print("HTTP/HTTPS headers: %s" % err.headers)
47 | print("Error code: %d" % err.errcode)
48 | print("Error message: %s" % err.errmsg)
49 | except xmlrpc.client.Fault as err:
50 | print("A fault occurred")
51 | print("Fault code: %d" % err.faultCode)
52 | print("Fault string: %s" % err.faultString)
53 |
54 |
55 | def hide_password(url, start=6):
56 | """Returns the http url with password part replaced with '*'.
57 |
58 | :param url: URL to upload the plugin to.
59 | :type url: str
60 |
61 | :param start: Position of start of password.
62 | :type start: int
63 | """
64 | start_position = url.find(':', start) + 1
65 | end_position = url.find('@')
66 | return "%s%s%s" % (
67 | url[:start_position],
68 | '*' * (end_position - start_position),
69 | url[end_position:])
70 |
71 |
72 | if __name__ == "__main__":
73 | parser = OptionParser(usage="%prog [options] plugin.zip")
74 | parser.add_option(
75 | "-w", "--password", dest="password",
76 | help="Password for plugin site", metavar="******")
77 | parser.add_option(
78 | "-u", "--username", dest="username",
79 | help="Username of plugin site", metavar="user")
80 | parser.add_option(
81 | "-p", "--port", dest="port",
82 | help="Server port to connect to", metavar="80")
83 | parser.add_option(
84 | "-s", "--server", dest="server",
85 | help="Specify server name", metavar="plugins.qgis.org")
86 | options, args = parser.parse_args()
87 | if len(args) != 1:
88 | print("Please specify zip file.\n")
89 | parser.print_help()
90 | sys.exit(1)
91 | if not options.server:
92 | options.server = SERVER
93 | if not options.port:
94 | options.port = PORT
95 | if not options.username:
96 | # interactive mode
97 | username = getpass.getuser()
98 | print("Please enter user name [%s] :" % username, end=' ')
99 | res = input()
100 | if res != "":
101 | options.username = res
102 | else:
103 | options.username = username
104 | if not options.password:
105 | # interactive mode
106 | options.password = getpass.getpass()
107 | main(options, args)
108 |
--------------------------------------------------------------------------------
/help/make.bat:
--------------------------------------------------------------------------------
1 | @ECHO OFF
2 |
3 | REM Command file for Sphinx documentation
4 |
5 | if "%SPHINXBUILD%" == "" (
6 | set SPHINXBUILD=sphinx-build
7 | )
8 | set BUILDDIR=build
9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source
10 | if NOT "%PAPER%" == "" (
11 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
12 | )
13 |
14 | if "%1" == "" goto help
15 |
16 | if "%1" == "help" (
17 | :help
18 | echo.Please use `make ^` where ^ is one of
19 | echo. html to make standalone HTML files
20 | echo. dirhtml to make HTML files named index.html in directories
21 | echo. singlehtml to make a single large HTML file
22 | echo. pickle to make pickle files
23 | echo. json to make JSON files
24 | echo. htmlhelp to make HTML files and a HTML help project
25 | echo. qthelp to make HTML files and a qthelp project
26 | echo. devhelp to make HTML files and a Devhelp project
27 | echo. epub to make an epub
28 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
29 | echo. text to make text files
30 | echo. man to make manual pages
31 | echo. changes to make an overview over all changed/added/deprecated items
32 | echo. linkcheck to check all external links for integrity
33 | echo. doctest to run all doctests embedded in the documentation if enabled
34 | goto end
35 | )
36 |
37 | if "%1" == "clean" (
38 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
39 | del /q /s %BUILDDIR%\*
40 | goto end
41 | )
42 |
43 | if "%1" == "html" (
44 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
45 | echo.
46 | echo.Build finished. The HTML pages are in %BUILDDIR%/html.
47 | goto end
48 | )
49 |
50 | if "%1" == "dirhtml" (
51 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
52 | echo.
53 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
54 | goto end
55 | )
56 |
57 | if "%1" == "singlehtml" (
58 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
59 | echo.
60 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
61 | goto end
62 | )
63 |
64 | if "%1" == "pickle" (
65 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
66 | echo.
67 | echo.Build finished; now you can process the pickle files.
68 | goto end
69 | )
70 |
71 | if "%1" == "json" (
72 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
73 | echo.
74 | echo.Build finished; now you can process the JSON files.
75 | goto end
76 | )
77 |
78 | if "%1" == "htmlhelp" (
79 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
80 | echo.
81 | echo.Build finished; now you can run HTML Help Workshop with the ^
82 | .hhp project file in %BUILDDIR%/htmlhelp.
83 | goto end
84 | )
85 |
86 | if "%1" == "qthelp" (
87 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
88 | echo.
89 | echo.Build finished; now you can run "qcollectiongenerator" with the ^
90 | .qhcp project file in %BUILDDIR%/qthelp, like this:
91 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\template_class.qhcp
92 | echo.To view the help file:
93 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\template_class.ghc
94 | goto end
95 | )
96 |
97 | if "%1" == "devhelp" (
98 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
99 | echo.
100 | echo.Build finished.
101 | goto end
102 | )
103 |
104 | if "%1" == "epub" (
105 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
106 | echo.
107 | echo.Build finished. The epub file is in %BUILDDIR%/epub.
108 | goto end
109 | )
110 |
111 | if "%1" == "latex" (
112 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
113 | echo.
114 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
115 | goto end
116 | )
117 |
118 | if "%1" == "text" (
119 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
120 | echo.
121 | echo.Build finished. The text files are in %BUILDDIR%/text.
122 | goto end
123 | )
124 |
125 | if "%1" == "man" (
126 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
127 | echo.
128 | echo.Build finished. The manual pages are in %BUILDDIR%/man.
129 | goto end
130 | )
131 |
132 | if "%1" == "changes" (
133 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
134 | echo.
135 | echo.The overview file is in %BUILDDIR%/changes.
136 | goto end
137 | )
138 |
139 | if "%1" == "linkcheck" (
140 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
141 | echo.
142 | echo.Link check complete; look for any errors in the above output ^
143 | or in %BUILDDIR%/linkcheck/output.txt.
144 | goto end
145 | )
146 |
147 | if "%1" == "doctest" (
148 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
149 | echo.
150 | echo.Testing of doctests in the sources finished, look at the ^
151 | results in %BUILDDIR%/doctest/output.txt.
152 | goto end
153 | )
154 |
155 | :end
156 |
--------------------------------------------------------------------------------
/help/Makefile:
--------------------------------------------------------------------------------
1 | # Makefile for Sphinx documentation
2 | #
3 |
4 | # You can set these variables from the command line.
5 | SPHINXOPTS =
6 | SPHINXBUILD = sphinx-build
7 | PAPER =
8 | BUILDDIR = build
9 |
10 | # Internal variables.
11 | PAPEROPT_a4 = -D latex_paper_size=a4
12 | PAPEROPT_letter = -D latex_paper_size=letter
13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
14 |
15 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest
16 |
17 | help:
18 | @echo "Please use \`make ' where is one of"
19 | @echo " html to make standalone HTML files"
20 | @echo " dirhtml to make HTML files named index.html in directories"
21 | @echo " singlehtml to make a single large HTML file"
22 | @echo " pickle to make pickle files"
23 | @echo " json to make JSON files"
24 | @echo " htmlhelp to make HTML files and a HTML help project"
25 | @echo " qthelp to make HTML files and a qthelp project"
26 | @echo " devhelp to make HTML files and a Devhelp project"
27 | @echo " epub to make an epub"
28 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
29 | @echo " latexpdf to make LaTeX files and run them through pdflatex"
30 | @echo " text to make text files"
31 | @echo " man to make manual pages"
32 | @echo " changes to make an overview of all changed/added/deprecated items"
33 | @echo " linkcheck to check all external links for integrity"
34 | @echo " doctest to run all doctests embedded in the documentation (if enabled)"
35 |
36 | clean:
37 | -rm -rf $(BUILDDIR)/*
38 |
39 | html:
40 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
41 | @echo
42 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
43 |
44 | dirhtml:
45 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
46 | @echo
47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
48 |
49 | singlehtml:
50 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
51 | @echo
52 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
53 |
54 | pickle:
55 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
56 | @echo
57 | @echo "Build finished; now you can process the pickle files."
58 |
59 | json:
60 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
61 | @echo
62 | @echo "Build finished; now you can process the JSON files."
63 |
64 | htmlhelp:
65 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
66 | @echo
67 | @echo "Build finished; now you can run HTML Help Workshop with the" \
68 | ".hhp project file in $(BUILDDIR)/htmlhelp."
69 |
70 | qthelp:
71 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
72 | @echo
73 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \
74 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
75 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/template_class.qhcp"
76 | @echo "To view the help file:"
77 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/template_class.qhc"
78 |
79 | devhelp:
80 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
81 | @echo
82 | @echo "Build finished."
83 | @echo "To view the help file:"
84 | @echo "# mkdir -p $$HOME/.local/share/devhelp/template_class"
85 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/template_class"
86 | @echo "# devhelp"
87 |
88 | epub:
89 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
90 | @echo
91 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
92 |
93 | latex:
94 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
95 | @echo
96 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
97 | @echo "Run \`make' in that directory to run these through (pdf)latex" \
98 | "(use \`make latexpdf' here to do that automatically)."
99 |
100 | latexpdf:
101 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
102 | @echo "Running LaTeX files through pdflatex..."
103 | make -C $(BUILDDIR)/latex all-pdf
104 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
105 |
106 | text:
107 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
108 | @echo
109 | @echo "Build finished. The text files are in $(BUILDDIR)/text."
110 |
111 | man:
112 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
113 | @echo
114 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
115 |
116 | changes:
117 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
118 | @echo
119 | @echo "The overview file is in $(BUILDDIR)/changes."
120 |
121 | linkcheck:
122 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
123 | @echo
124 | @echo "Link check complete; look for any errors in the above output " \
125 | "or in $(BUILDDIR)/linkcheck/output.txt."
126 |
127 | doctest:
128 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
129 | @echo "Testing of doctests in the sources finished, look at the " \
130 | "results in $(BUILDDIR)/doctest/output.txt."
131 |
--------------------------------------------------------------------------------
/test/qgis_interface.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | """QGIS plugin implementation.
3 |
4 | .. note:: This program is free software; you can redistribute it and/or modify
5 | it under the terms of the GNU General Public License as published by
6 | the Free Software Foundation; either version 2 of the License, or
7 | (at your option) any later version.
8 |
9 | .. note:: This source code was copied from the 'postgis viewer' application
10 | with original authors:
11 | Copyright (c) 2010 by Ivan Mincik, ivan.mincik@gista.sk
12 | Copyright (c) 2011 German Carrillo, geotux_tuxman@linuxmail.org
13 | Copyright (c) 2014 Tim Sutton, tim@linfiniti.com
14 |
15 | """
16 |
17 | __author__ = 'tim@linfiniti.com'
18 | __revision__ = '$Format:%H$'
19 | __date__ = '10/01/2011'
20 | __copyright__ = (
21 | 'Copyright (c) 2010 by Ivan Mincik, ivan.mincik@gista.sk and '
22 | 'Copyright (c) 2011 German Carrillo, geotux_tuxman@linuxmail.org'
23 | 'Copyright (c) 2014 Tim Sutton, tim@linfiniti.com'
24 | )
25 |
26 | import logging
27 | from PyQt5.QtCore import QObject, pyqtSlot, pyqtSignal
28 | from qgis.core import QgsMapLayerRegistry
29 | from qgis.gui import QgsMapCanvasLayer
30 | LOGGER = logging.getLogger('QGIS')
31 |
32 |
33 | #noinspection PyMethodMayBeStatic,PyPep8Naming
34 | class QgisInterface(QObject):
35 | """Class to expose QGIS objects and functions to plugins.
36 |
37 | This class is here for enabling us to run unit tests only,
38 | so most methods are simply stubs.
39 | """
40 | currentLayerChanged = pyqtSignal(QgsMapCanvasLayer)
41 |
42 | def __init__(self, canvas):
43 | """Constructor
44 | :param canvas:
45 | """
46 | QObject.__init__(self)
47 | self.canvas = canvas
48 | # Set up slots so we can mimic the behaviour of QGIS when layers
49 | # are added.
50 | LOGGER.debug('Initialising canvas...')
51 | # noinspection PyArgumentList
52 | QgsMapLayerRegistry.instance().layersAdded.connect(self.addLayers)
53 | # noinspection PyArgumentList
54 | QgsMapLayerRegistry.instance().layerWasAdded.connect(self.addLayer)
55 | # noinspection PyArgumentList
56 | QgsMapLayerRegistry.instance().removeAll.connect(self.removeAllLayers)
57 |
58 | # For processing module
59 | self.destCrs = None
60 |
61 | @pyqtSlot('QStringList')
62 | def addLayers(self, layers):
63 | """Handle layers being added to the registry so they show up in canvas.
64 |
65 | :param layers: list list of map layers that were added
66 |
67 | .. note:: The QgsInterface api does not include this method,
68 | it is added here as a helper to facilitate testing.
69 | """
70 | #LOGGER.debug('addLayers called on qgis_interface')
71 | #LOGGER.debug('Number of layers being added: %s' % len(layers))
72 | #LOGGER.debug('Layer Count Before: %s' % len(self.canvas.layers()))
73 | current_layers = self.canvas.layers()
74 | final_layers = []
75 | for layer in current_layers:
76 | final_layers.append(QgsMapCanvasLayer(layer))
77 | for layer in layers:
78 | final_layers.append(QgsMapCanvasLayer(layer))
79 |
80 | self.canvas.setLayerSet(final_layers)
81 | #LOGGER.debug('Layer Count After: %s' % len(self.canvas.layers()))
82 |
83 | @pyqtSlot('QgsMapLayer')
84 | def addLayer(self, layer):
85 | """Handle a layer being added to the registry so it shows up in canvas.
86 |
87 | :param layer: list list of map layers that were added
88 |
89 | .. note: The QgsInterface api does not include this method, it is added
90 | here as a helper to facilitate testing.
91 |
92 | .. note: The addLayer method was deprecated in QGIS 1.8 so you should
93 | not need this method much.
94 | """
95 | pass
96 |
97 | @pyqtSlot()
98 | def removeAllLayers(self):
99 | """Remove layers from the canvas before they get deleted."""
100 | self.canvas.setLayerSet([])
101 |
102 | def newProject(self):
103 | """Create new project."""
104 | # noinspection PyArgumentList
105 | QgsMapLayerRegistry.instance().removeAllMapLayers()
106 |
107 | # ---------------- API Mock for QgsInterface follows -------------------
108 |
109 | def zoomFull(self):
110 | """Zoom to the map full extent."""
111 | pass
112 |
113 | def zoomToPrevious(self):
114 | """Zoom to previous view extent."""
115 | pass
116 |
117 | def zoomToNext(self):
118 | """Zoom to next view extent."""
119 | pass
120 |
121 | def zoomToActiveLayer(self):
122 | """Zoom to extent of active layer."""
123 | pass
124 |
125 | def addVectorLayer(self, path, base_name, provider_key):
126 | """Add a vector layer.
127 |
128 | :param path: Path to layer.
129 | :type path: str
130 |
131 | :param base_name: Base name for layer.
132 | :type base_name: str
133 |
134 | :param provider_key: Provider key e.g. 'ogr'
135 | :type provider_key: str
136 | """
137 | pass
138 |
139 | def addRasterLayer(self, path, base_name):
140 | """Add a raster layer given a raster layer file name
141 |
142 | :param path: Path to layer.
143 | :type path: str
144 |
145 | :param base_name: Base name for layer.
146 | :type base_name: str
147 | """
148 | pass
149 |
150 | def activeLayer(self):
151 | """Get pointer to the active layer (layer selected in the legend)."""
152 | # noinspection PyArgumentList
153 | layers = QgsMapLayerRegistry.instance().mapLayers()
154 | for item in layers:
155 | return layers[item]
156 |
157 | def addToolBarIcon(self, action):
158 | """Add an icon to the plugins toolbar.
159 |
160 | :param action: Action to add to the toolbar.
161 | :type action: QAction
162 | """
163 | pass
164 |
165 | def removeToolBarIcon(self, action):
166 | """Remove an action (icon) from the plugin toolbar.
167 |
168 | :param action: Action to add to the toolbar.
169 | :type action: QAction
170 | """
171 | pass
172 |
173 | def addToolBar(self, name):
174 | """Add toolbar with specified name.
175 |
176 | :param name: Name for the toolbar.
177 | :type name: str
178 | """
179 | pass
180 |
181 | def mapCanvas(self):
182 | """Return a pointer to the map canvas."""
183 | return self.canvas
184 |
185 | def mainWindow(self):
186 | """Return a pointer to the main window.
187 |
188 | In case of QGIS it returns an instance of QgisApp.
189 | """
190 | pass
191 |
192 | def addDockWidget(self, area, dock_widget):
193 | """Add a dock widget to the main window.
194 |
195 | :param area: Where in the ui the dock should be placed.
196 | :type area:
197 |
198 | :param dock_widget: A dock widget to add to the UI.
199 | :type dock_widget: QDockWidget
200 | """
201 | pass
202 |
203 | def legendInterface(self):
204 | """Get the legend."""
205 | return self.canvas
206 |
--------------------------------------------------------------------------------
/dijkstra_algorithm.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | """
4 | /***************************************************************************
5 | LeastCostPath
6 | A QGIS plugin
7 | Find the least cost path with given cost raster and points
8 | Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
9 | -------------------
10 | begin : 2018-12-12
11 | copyright : (C) 2018 by FlowMap Group@SESS.PKU
12 | email : xurigong@gmail.com
13 | ***************************************************************************/
14 |
15 | /***************************************************************************
16 | * *
17 | * This program is free software; you can redistribute it and/or modify *
18 | * it under the terms of the GNU General Public License as published by *
19 | * the Free Software Foundation; either version 2 of the License, or *
20 | * (at your option) any later version. *
21 | * *
22 | ***************************************************************************/
23 | """
24 |
25 | __author__ = 'FlowMap Group@SESS.PKU'
26 | __date__ = '2018-12-12'
27 | __copyright__ = '(C) 2018 by FlowMap Group@SESS.PKU'
28 |
29 | # This will get replaced with a git SHA1 when you do a git archive
30 |
31 | __revision__ = '$Format:%H$'
32 |
33 | from math import sqrt
34 | import queue
35 | import collections
36 |
37 | sqrt2 = sqrt(2)
38 |
39 |
40 | def dijkstra(start_tuple, end_tuples, block, find_nearest, feedback=None):
41 |
42 | class Grid:
43 | def __init__(self, matrix):
44 | self.map = matrix
45 | self.h = len(matrix)
46 | self.w = len(matrix[0])
47 | self.manhattan_boundry = None
48 | self.curr_boundry = None
49 |
50 | def _in_bounds(self, id):
51 | x, y = id
52 | return 0 <= x < self.h and 0 <= y < self.w
53 |
54 | def _passable(self, id):
55 | x, y = id
56 | return self.map[x][y] is not None
57 |
58 | def is_valid(self, id):
59 | return self._in_bounds(id) and self._passable(id)
60 |
61 | def neighbors(self, id):
62 | x, y = id
63 | results = [(x + 1, y), (x, y - 1), (x - 1, y), (x, y + 1),
64 | (x + 1, y - 1), (x + 1, y + 1), (x - 1, y - 1), (x - 1, y + 1)]
65 | results = list(filter(self.is_valid, results))
66 | return results
67 |
68 | @staticmethod
69 | def manhattan_distance(id1, id2):
70 | x1, y1 = id1
71 | x2, y2 = id2
72 | return abs(x1 - x2) + abs(y1 - y2)
73 |
74 | @staticmethod
75 | def min_manhattan(curr_node, end_nodes):
76 | return min(map(lambda node: Grid.manhattan_distance(curr_node, node), end_nodes))
77 |
78 | @staticmethod
79 | def max_manhattan(curr_node, end_nodes):
80 | return max(map(lambda node: Grid.manhattan_distance(curr_node, node), end_nodes))
81 |
82 | @staticmethod
83 | def all_manhattan(curr_node, end_nodes):
84 | return {end_node: Grid.manhattan_distance(curr_node, end_node) for end_node in end_nodes}
85 |
86 | def simple_cost(self, cur, nex):
87 | cx, cy = cur
88 | nx, ny = nex
89 | currV = self.map[cx][cy]
90 | offsetV = self.map[nx][ny]
91 | if cx == nx or cy == ny:
92 | return (currV + offsetV) / 2
93 | else:
94 | return sqrt2 * (currV + offsetV) / 2
95 |
96 | result = []
97 | grid = Grid(block)
98 |
99 | end_dict = collections.defaultdict(list)
100 | for end_tuple in end_tuples:
101 | end_dict[end_tuple[0]].append(end_tuple)
102 | end_row_cols = set(end_dict.keys())
103 | end_row_col_list = list(end_row_cols)
104 | start_row_col = start_tuple[0]
105 |
106 |
107 | frontier = queue.PriorityQueue()
108 | frontier.put((0, start_row_col))
109 | came_from = {}
110 | cost_so_far = {}
111 | decided = set()
112 |
113 | if not grid.is_valid(start_row_col):
114 | return result
115 |
116 | # init progress
117 | index = 0
118 | distance_dic = grid.all_manhattan(start_row_col, end_row_cols)
119 | if find_nearest:
120 | total_manhattan = min(distance_dic.values())
121 | else:
122 | total_manhattan = sum(distance_dic.values())
123 |
124 | total_manhattan = total_manhattan + 1
125 | bound = total_manhattan
126 | if feedback:
127 | feedback.setProgress(1 + 100 * (1 - bound / total_manhattan))
128 |
129 | came_from[start_row_col] = None
130 | cost_so_far[start_row_col] = 0
131 |
132 | while not frontier.empty():
133 | _, current_node = frontier.get()
134 | if current_node in decided:
135 | continue
136 | decided.add(current_node)
137 |
138 | # update the progress bar
139 | if feedback:
140 | if feedback.isCanceled():
141 | return None
142 |
143 | index = (index + 1) % len(end_row_col_list)
144 | target_node = end_row_col_list[index]
145 | new_manhattan = grid.manhattan_distance(current_node, target_node)
146 | if new_manhattan < distance_dic[target_node]:
147 | if find_nearest:
148 | curr_bound = new_manhattan
149 | else:
150 | curr_bound = bound - (distance_dic[target_node] - new_manhattan)
151 |
152 | distance_dic[target_node] = new_manhattan
153 |
154 | if curr_bound < bound:
155 | bound = curr_bound
156 | if feedback:
157 | feedback.setProgress(1 + 100 * (1 - bound / total_manhattan)*(1 - bound / total_manhattan))
158 |
159 | # reacn destination
160 | if current_node in end_row_cols:
161 | path = []
162 | costs = []
163 | traverse_node = current_node
164 | while traverse_node is not None:
165 | path.append(traverse_node)
166 | costs.append(cost_so_far[traverse_node])
167 | traverse_node = came_from[traverse_node]
168 |
169 | # start point and end point overlaps
170 | if len(path) == 1:
171 | path.append(start_row_col)
172 | costs.append(0.0)
173 | path.reverse()
174 | costs.reverse()
175 | result.append((path, costs, end_dict[current_node]))
176 |
177 | end_row_cols.remove(current_node)
178 | end_row_col_list.remove(current_node)
179 | if len(end_row_cols) == 0 or find_nearest:
180 | break
181 |
182 | # relax distance
183 | for nex in grid.neighbors(current_node):
184 | new_cost = cost_so_far[current_node] + grid.simple_cost(current_node, nex)
185 | if nex not in cost_so_far or new_cost < cost_so_far[nex]:
186 | cost_so_far[nex] = new_cost
187 | frontier.put((new_cost, nex))
188 | came_from[nex] = current_node
189 |
190 | return result
191 |
--------------------------------------------------------------------------------
/help/source/conf.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # LeastCostPath documentation build configuration file, created by
4 | # sphinx-quickstart on Sun Feb 12 17:11:03 2012.
5 | #
6 | # This file is execfile()d with the current directory set to its containing dir.
7 | #
8 | # Note that not all possible configuration values are present in this
9 | # autogenerated file.
10 | #
11 | # All configuration values have a default; values that are commented out
12 | # serve to show the default.
13 |
14 | import sys, os
15 |
16 | # If extensions (or modules to document with autodoc) are in another directory,
17 | # add these directories to sys.path here. If the directory is relative to the
18 | # documentation root, use os.path.abspath to make it absolute, like shown here.
19 | #sys.path.insert(0, os.path.abspath('.'))
20 |
21 | # -- General configuration -----------------------------------------------------
22 |
23 | # If your documentation needs a minimal Sphinx version, state it here.
24 | #needs_sphinx = '1.0'
25 |
26 | # Add any Sphinx extension module names here, as strings. They can be extensions
27 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
28 | extensions = ['sphinx.ext.todo', 'sphinx.ext.pngmath', 'sphinx.ext.viewcode']
29 |
30 | # Add any paths that contain templates here, relative to this directory.
31 | templates_path = ['_templates']
32 |
33 | # The suffix of source filenames.
34 | source_suffix = '.rst'
35 |
36 | # The encoding of source files.
37 | #source_encoding = 'utf-8-sig'
38 |
39 | # The master toctree document.
40 | master_doc = 'index'
41 |
42 | # General information about the project.
43 | project = u'LeastCostPath'
44 | copyright = u'2013, FlowMap Group@SESS.PKU'
45 |
46 | # The version info for the project you're documenting, acts as replacement for
47 | # |version| and |release|, also used in various other places throughout the
48 | # built documents.
49 | #
50 | # The short X.Y version.
51 | version = '1'
52 | # The full version, including alpha/beta/rc tags.
53 | release = '1'
54 |
55 | # The language for content autogenerated by Sphinx. Refer to documentation
56 | # for a list of supported languages.
57 | #language = None
58 |
59 | # There are two options for replacing |today|: either, you set today to some
60 | # non-false value, then it is used:
61 | #today = ''
62 | # Else, today_fmt is used as the format for a strftime call.
63 | #today_fmt = '%B %d, %Y'
64 |
65 | # List of patterns, relative to source directory, that match files and
66 | # directories to ignore when looking for source files.
67 | exclude_patterns = []
68 |
69 | # The reST default role (used for this markup: `text`) to use for all documents.
70 | #default_role = None
71 |
72 | # If true, '()' will be appended to :func: etc. cross-reference text.
73 | #add_function_parentheses = True
74 |
75 | # If true, the current module name will be prepended to all description
76 | # unit titles (such as .. function::).
77 | #add_TemplateModuleNames = True
78 |
79 | # If true, sectionauthor and moduleauthor directives will be shown in the
80 | # output. They are ignored by default.
81 | #show_authors = False
82 |
83 | # The name of the Pygments (syntax highlighting) style to use.
84 | pygments_style = 'sphinx'
85 |
86 | # A list of ignored prefixes for module index sorting.
87 | #modindex_common_prefix = []
88 |
89 |
90 | # -- Options for HTML output ---------------------------------------------------
91 |
92 | # The theme to use for HTML and HTML Help pages. See the documentation for
93 | # a list of builtin themes.
94 | html_theme = 'default'
95 |
96 | # Theme options are theme-specific and customize the look and feel of a theme
97 | # further. For a list of options available for each theme, see the
98 | # documentation.
99 | #html_theme_options = {}
100 |
101 | # Add any paths that contain custom themes here, relative to this directory.
102 | #html_theme_path = []
103 |
104 | # The name for this set of Sphinx documents. If None, it defaults to
105 | # " v documentation".
106 | #html_title = None
107 |
108 | # A shorter title for the navigation bar. Default is the same as html_title.
109 | #html_short_title = None
110 |
111 | # The name of an image file (relative to this directory) to place at the top
112 | # of the sidebar.
113 | #html_logo = None
114 |
115 | # The name of an image file (within the static path) to use as favicon of the
116 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
117 | # pixels large.
118 | #html_favicon = None
119 |
120 | # Add any paths that contain custom static files (such as style sheets) here,
121 | # relative to this directory. They are copied after the builtin static files,
122 | # so a file named "default.css" will overwrite the builtin "default.css".
123 | html_static_path = ['_static']
124 |
125 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
126 | # using the given strftime format.
127 | #html_last_updated_fmt = '%b %d, %Y'
128 |
129 | # If true, SmartyPants will be used to convert quotes and dashes to
130 | # typographically correct entities.
131 | #html_use_smartypants = True
132 |
133 | # Custom sidebar templates, maps document names to template names.
134 | #html_sidebars = {}
135 |
136 | # Additional templates that should be rendered to pages, maps page names to
137 | # template names.
138 | #html_additional_pages = {}
139 |
140 | # If false, no module index is generated.
141 | #html_domain_indices = True
142 |
143 | # If false, no index is generated.
144 | #html_use_index = True
145 |
146 | # If true, the index is split into individual pages for each letter.
147 | #html_split_index = False
148 |
149 | # If true, links to the reST sources are added to the pages.
150 | #html_show_sourcelink = True
151 |
152 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
153 | #html_show_sphinx = True
154 |
155 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
156 | #html_show_copyright = True
157 |
158 | # If true, an OpenSearch description file will be output, and all pages will
159 | # contain a tag referring to it. The value of this option must be the
160 | # base URL from which the finished HTML is served.
161 | #html_use_opensearch = ''
162 |
163 | # This is the file name suffix for HTML files (e.g. ".xhtml").
164 | #html_file_suffix = None
165 |
166 | # Output file base name for HTML help builder.
167 | htmlhelp_basename = 'TemplateClassdoc'
168 |
169 |
170 | # -- Options for LaTeX output --------------------------------------------------
171 |
172 | # The paper size ('letter' or 'a4').
173 | #latex_paper_size = 'letter'
174 |
175 | # The font size ('10pt', '11pt' or '12pt').
176 | #latex_font_size = '10pt'
177 |
178 | # Grouping the document tree into LaTeX files. List of tuples
179 | # (source start file, target name, title, author, documentclass [howto/manual]).
180 | latex_documents = [
181 | ('index', 'LeastCostPath.tex', u'LeastCostPath Documentation',
182 | u'FlowMap Group@SESS.PKU', 'manual'),
183 | ]
184 |
185 | # The name of an image file (relative to this directory) to place at the top of
186 | # the title page.
187 | #latex_logo = None
188 |
189 | # For "manual" documents, if this is true, then toplevel headings are parts,
190 | # not chapters.
191 | #latex_use_parts = False
192 |
193 | # If true, show page references after internal links.
194 | #latex_show_pagerefs = False
195 |
196 | # If true, show URL addresses after external links.
197 | #latex_show_urls = False
198 |
199 | # Additional stuff for the LaTeX preamble.
200 | #latex_preamble = ''
201 |
202 | # Documents to append as an appendix to all manuals.
203 | #latex_appendices = []
204 |
205 | # If false, no module index is generated.
206 | #latex_domain_indices = True
207 |
208 |
209 | # -- Options for manual page output --------------------------------------------
210 |
211 | # One entry per manual page. List of tuples
212 | # (source start file, name, description, authors, manual section).
213 | man_pages = [
214 | ('index', 'TemplateClass', u'LeastCostPath Documentation',
215 | [u'FlowMap Group@SESS.PKU'], 1)
216 | ]
217 |
--------------------------------------------------------------------------------
/pylintrc:
--------------------------------------------------------------------------------
1 | [MASTER]
2 |
3 | # Specify a configuration file.
4 | #rcfile=
5 |
6 | # Python code to execute, usually for sys.path manipulation such as
7 | # pygtk.require().
8 | #init-hook=
9 |
10 | # Profiled execution.
11 | profile=no
12 |
13 | # Add files or directories to the blacklist. They should be base names, not
14 | # paths.
15 | ignore=CVS
16 |
17 | # Pickle collected data for later comparisons.
18 | persistent=yes
19 |
20 | # List of plugins (as comma separated values of python modules names) to load,
21 | # usually to register additional checkers.
22 | load-plugins=
23 |
24 |
25 | [MESSAGES CONTROL]
26 |
27 | # Enable the message, report, category or checker with the given id(s). You can
28 | # either give multiple identifier separated by comma (,) or put this option
29 | # multiple time. See also the "--disable" option for examples.
30 | #enable=
31 |
32 | # Disable the message, report, category or checker with the given id(s). You
33 | # can either give multiple identifiers separated by comma (,) or put this
34 | # option multiple times (only on the command line, not in the configuration
35 | # file where it should appear only once).You can also use "--disable=all" to
36 | # disable everything first and then reenable specific checks. For example, if
37 | # you want to run only the similarities checker, you can use "--disable=all
38 | # --enable=similarities". If you want to run only the classes checker, but have
39 | # no Warning level messages displayed, use"--disable=all --enable=classes
40 | # --disable=W"
41 | # see http://stackoverflow.com/questions/21487025/pylint-locally-defined-disables-still-give-warnings-how-to-suppress-them
42 | disable=locally-disabled,C0103
43 |
44 |
45 | [REPORTS]
46 |
47 | # Set the output format. Available formats are text, parseable, colorized, msvs
48 | # (visual studio) and html. You can also give a reporter class, eg
49 | # mypackage.mymodule.MyReporterClass.
50 | output-format=text
51 |
52 | # Put messages in a separate file for each module / package specified on the
53 | # command line instead of printing them on stdout. Reports (if any) will be
54 | # written in a file name "pylint_global.[txt|html]".
55 | files-output=no
56 |
57 | # Tells whether to display a full report or only the messages
58 | reports=yes
59 |
60 | # Python expression which should return a note less than 10 (10 is the highest
61 | # note). You have access to the variables errors warning, statement which
62 | # respectively contain the number of errors / warnings messages and the total
63 | # number of statements analyzed. This is used by the global evaluation report
64 | # (RP0004).
65 | evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
66 |
67 | # Add a comment according to your evaluation note. This is used by the global
68 | # evaluation report (RP0004).
69 | comment=no
70 |
71 | # Template used to display messages. This is a python new-style format string
72 | # used to format the message information. See doc for all details
73 | #msg-template=
74 |
75 |
76 | [BASIC]
77 |
78 | # Required attributes for module, separated by a comma
79 | required-attributes=
80 |
81 | # List of builtins function names that should not be used, separated by a comma
82 | bad-functions=map,filter,apply,input
83 |
84 | # Regular expression which should only match correct module names
85 | module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
86 |
87 | # Regular expression which should only match correct module level names
88 | const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$
89 |
90 | # Regular expression which should only match correct class names
91 | class-rgx=[A-Z_][a-zA-Z0-9]+$
92 |
93 | # Regular expression which should only match correct function names
94 | function-rgx=[a-z_][a-z0-9_]{2,30}$
95 |
96 | # Regular expression which should only match correct method names
97 | method-rgx=[a-z_][a-z0-9_]{2,30}$
98 |
99 | # Regular expression which should only match correct instance attribute names
100 | attr-rgx=[a-z_][a-z0-9_]{2,30}$
101 |
102 | # Regular expression which should only match correct argument names
103 | argument-rgx=[a-z_][a-z0-9_]{2,30}$
104 |
105 | # Regular expression which should only match correct variable names
106 | variable-rgx=[a-z_][a-z0-9_]{2,30}$
107 |
108 | # Regular expression which should only match correct attribute names in class
109 | # bodies
110 | class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
111 |
112 | # Regular expression which should only match correct list comprehension /
113 | # generator expression variable names
114 | inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$
115 |
116 | # Good variable names which should always be accepted, separated by a comma
117 | good-names=i,j,k,ex,Run,_
118 |
119 | # Bad variable names which should always be refused, separated by a comma
120 | bad-names=foo,bar,baz,toto,tutu,tata
121 |
122 | # Regular expression which should only match function or class names that do
123 | # not require a docstring.
124 | no-docstring-rgx=__.*__
125 |
126 | # Minimum line length for functions/classes that require docstrings, shorter
127 | # ones are exempt.
128 | docstring-min-length=-1
129 |
130 |
131 | [MISCELLANEOUS]
132 |
133 | # List of note tags to take in consideration, separated by a comma.
134 | notes=FIXME,XXX,TODO
135 |
136 |
137 | [TYPECHECK]
138 |
139 | # Tells whether missing members accessed in mixin class should be ignored. A
140 | # mixin class is detected if its name ends with "mixin" (case insensitive).
141 | ignore-mixin-members=yes
142 |
143 | # List of classes names for which member attributes should not be checked
144 | # (useful for classes with attributes dynamically set).
145 | ignored-classes=SQLObject
146 |
147 | # When zope mode is activated, add a predefined set of Zope acquired attributes
148 | # to generated-members.
149 | zope=no
150 |
151 | # List of members which are set dynamically and missed by pylint inference
152 | # system, and so shouldn't trigger E0201 when accessed. Python regular
153 | # expressions are accepted.
154 | generated-members=REQUEST,acl_users,aq_parent
155 |
156 |
157 | [VARIABLES]
158 |
159 | # Tells whether we should check for unused import in __init__ files.
160 | init-import=no
161 |
162 | # A regular expression matching the beginning of the name of dummy variables
163 | # (i.e. not used).
164 | dummy-variables-rgx=_$|dummy
165 |
166 | # List of additional names supposed to be defined in builtins. Remember that
167 | # you should avoid to define new builtins when possible.
168 | additional-builtins=
169 |
170 |
171 | [FORMAT]
172 |
173 | # Maximum number of characters on a single line.
174 | max-line-length=80
175 |
176 | # Regexp for a line that is allowed to be longer than the limit.
177 | ignore-long-lines=^\s*(# )??$
178 |
179 | # Allow the body of an if to be on the same line as the test if there is no
180 | # else.
181 | single-line-if-stmt=no
182 |
183 | # List of optional constructs for which whitespace checking is disabled
184 | no-space-check=trailing-comma,dict-separator
185 |
186 | # Maximum number of lines in a module
187 | max-module-lines=1000
188 |
189 | # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
190 | # tab).
191 | indent-string=' '
192 |
193 |
194 | [SIMILARITIES]
195 |
196 | # Minimum lines number of a similarity.
197 | min-similarity-lines=4
198 |
199 | # Ignore comments when computing similarities.
200 | ignore-comments=yes
201 |
202 | # Ignore docstrings when computing similarities.
203 | ignore-docstrings=yes
204 |
205 | # Ignore imports when computing similarities.
206 | ignore-imports=no
207 |
208 |
209 | [IMPORTS]
210 |
211 | # Deprecated modules which should not be used, separated by a comma
212 | deprecated-modules=regsub,TERMIOS,Bastion,rexec
213 |
214 | # Create a graph of every (i.e. internal and external) dependencies in the
215 | # given file (report RP0402 must not be disabled)
216 | import-graph=
217 |
218 | # Create a graph of external dependencies in the given file (report RP0402 must
219 | # not be disabled)
220 | ext-import-graph=
221 |
222 | # Create a graph of internal dependencies in the given file (report RP0402 must
223 | # not be disabled)
224 | int-import-graph=
225 |
226 |
227 | [DESIGN]
228 |
229 | # Maximum number of arguments for function / method
230 | max-args=5
231 |
232 | # Argument names that match this expression will be ignored. Default to name
233 | # with leading underscore
234 | ignored-argument-names=_.*
235 |
236 | # Maximum number of locals for function / method body
237 | max-locals=15
238 |
239 | # Maximum number of return / yield for function / method body
240 | max-returns=6
241 |
242 | # Maximum number of branch for function / method body
243 | max-branches=12
244 |
245 | # Maximum number of statements in function / method body
246 | max-statements=50
247 |
248 | # Maximum number of parents for a class (see R0901).
249 | max-parents=7
250 |
251 | # Maximum number of attributes for a class (see R0902).
252 | max-attributes=7
253 |
254 | # Minimum number of public methods for a class (see R0903).
255 | min-public-methods=2
256 |
257 | # Maximum number of public methods for a class (see R0904).
258 | max-public-methods=20
259 |
260 |
261 | [CLASSES]
262 |
263 | # List of interface methods to ignore, separated by a comma. This is used for
264 | # instance to not check methods defines in Zope's Interface base class.
265 | ignore-iface-methods=isImplementedBy,deferred,extends,names,namesAndDescriptions,queryDescriptionFor,getBases,getDescriptionFor,getDoc,getName,getTaggedValue,getTaggedValueTags,isEqualOrExtendedBy,setTaggedValue,isImplementedByInstancesOf,adaptWith,is_implemented_by
266 |
267 | # List of method names used to declare (i.e. assign) instance attributes.
268 | defining-attr-methods=__init__,__new__,setUp
269 |
270 | # List of valid names for the first argument in a class method.
271 | valid-classmethod-first-arg=cls
272 |
273 | # List of valid names for the first argument in a metaclass class method.
274 | valid-metaclass-classmethod-first-arg=mcs
275 |
276 |
277 | [EXCEPTIONS]
278 |
279 | # Exceptions that will emit a warning when being caught. Defaults to
280 | # "Exception"
281 | overgeneral-exceptions=Exception
282 |
--------------------------------------------------------------------------------
/least_cost_path_algorithm.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | """
4 | /***************************************************************************
5 | LeastCostPath
6 | A QGIS plugin
7 | Find the least cost path with given cost raster and points
8 | Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
9 | -------------------
10 | begin : 2018-12-12
11 | copyright : (C) 2018 by FlowMap Group@SESS.PKU
12 | email : xurigong@gmail.com
13 | ***************************************************************************/
14 |
15 | /***************************************************************************
16 | * *
17 | * This program is free software; you can redistribute it and/or modify *
18 | * it under the terms of the GNU General Public License as published by *
19 | * the Free Software Foundation; either version 2 of the License, or *
20 | * (at your option) any later version. *
21 | * *
22 | ***************************************************************************/
23 | """
24 |
25 | __author__ = 'FlowMap Group@SESS.PKU'
26 | __date__ = '2018-12-12'
27 | __copyright__ = '(C) 2018 by FlowMap Group@SESS.PKU'
28 |
29 | # This will get replaced with a git SHA1 when you do a git archive
30 |
31 | __revision__ = '$Format:%H$'
32 |
33 | from PyQt5.QtCore import QCoreApplication, QVariant
34 | from PyQt5.QtGui import QIcon
35 | from qgis.core import (
36 | QgsFeature,
37 | QgsGeometry,
38 | QgsPoint,
39 | QgsField,
40 | QgsFields,
41 | QgsWkbTypes,
42 | QgsProcessing,
43 | QgsFeatureSink,
44 | QgsProcessingException,
45 | QgsProcessingAlgorithm,
46 | QgsProcessingParameterFeatureSource,
47 | QgsProcessingParameterFeatureSink,
48 | QgsProcessingParameterRasterLayer,
49 | QgsProcessingParameterBand,
50 | QgsProcessingParameterBoolean
51 | )
52 | import processing
53 | from .dijkstra_algorithm import dijkstra
54 | from math import floor, sqrt
55 | import queue
56 | import collections
57 |
58 |
59 | class LeastCostPathAlgorithm(QgsProcessingAlgorithm):
60 | """
61 | This is the Least Cost Path Plugin that runs dijkstra algorithm
62 | """
63 |
64 | # Constants used to refer to parameters and outputs. They will be
65 | # used when calling the algorithm from another algorithm, or when
66 | # calling from the QGIS console.
67 |
68 | INPUT_COST_RASTER = 'INPUT_COST_RASTER'
69 | INPUT_RASTER_BAND = 'INPUT_RASTER_BAND'
70 | INPUT_START_LAYER = 'INPUT_START_LAYER'
71 | INPUT_END_LAYER = 'INPUT_END_LAYER'
72 | BOOLEAN_FIND_LEAST_PATH_TO_ALL_ENDS = 'BOOLEAN_FIND_LEAST_PATH_TO_ALL_ENDS'
73 | BOOLEAN_OUTPUT_LINEAR_REFERENCE = 'BOOLEAN_OUTPUT_LINEAR_REFERENCE'
74 | OUTPUT = 'OUTPUT'
75 |
76 | def initAlgorithm(self, config):
77 | """
78 | Here we define the inputs and output of the algorithm, along
79 | with some other properties.
80 | """
81 | self.addParameter(
82 | QgsProcessingParameterRasterLayer(
83 | self.INPUT_COST_RASTER,
84 | self.tr('Cost raster layer'),
85 | )
86 | )
87 |
88 | self.addParameter(
89 | QgsProcessingParameterBand(
90 | self.INPUT_RASTER_BAND,
91 | self.tr('Cost raster band'),
92 | 0,
93 | self.INPUT_COST_RASTER,
94 | )
95 | )
96 |
97 | self.addParameter(
98 | QgsProcessingParameterFeatureSource(
99 | self.INPUT_START_LAYER,
100 | self.tr('Start-point layer'),
101 | [QgsProcessing.TypeVectorPoint]
102 | )
103 | )
104 |
105 | self.addParameter(
106 | QgsProcessingParameterFeatureSource(
107 | self.INPUT_END_LAYER,
108 | self.tr('End-point(s) layer'),
109 | [QgsProcessing.TypeVectorPoint]
110 | )
111 | )
112 |
113 | self.addParameter(
114 | QgsProcessingParameterBoolean(
115 | self.BOOLEAN_FIND_LEAST_PATH_TO_ALL_ENDS,
116 | self.tr('Only connect with the nearest end points'),
117 | defaultValue = False
118 | )
119 | )
120 |
121 | self.addParameter(
122 | QgsProcessingParameterBoolean(
123 | self.BOOLEAN_OUTPUT_LINEAR_REFERENCE,
124 | self.tr('Include liner referencing (PolylineM type)')
125 | )
126 | )
127 |
128 | self.addParameter(
129 | QgsProcessingParameterFeatureSink(
130 | self.OUTPUT,
131 | self.tr('Output least cost path')
132 | )
133 | )
134 |
135 | def processAlgorithm(self, parameters, context, feedback):
136 | """
137 | Here is where the processing itself takes place.
138 | """
139 | feedback.setProgress(1)
140 |
141 | cost_raster = self.parameterAsRasterLayer(
142 | parameters,
143 | self.INPUT_COST_RASTER,
144 | context
145 | )
146 |
147 | cost_raster_band = self.parameterAsInt(
148 | parameters,
149 | self.INPUT_RASTER_BAND,
150 | context
151 | )
152 |
153 | start_source = self.parameterAsSource(
154 | parameters,
155 | self.INPUT_START_LAYER,
156 | context
157 | )
158 |
159 | find_nearest = self.parameterAsBool(
160 | parameters,
161 | self.BOOLEAN_FIND_LEAST_PATH_TO_ALL_ENDS,
162 | context
163 | )
164 |
165 | output_linear_reference = self.parameterAsBool(
166 | parameters,
167 | self.BOOLEAN_OUTPUT_LINEAR_REFERENCE,
168 | context
169 | )
170 |
171 | end_source = self.parameterAsSource(
172 | parameters,
173 | self.INPUT_END_LAYER,
174 | context
175 | )
176 |
177 | # If source was not found, throw an exception to indicate that the algorithm
178 | # encountered a fatal error. The exception text can be any string, but in this
179 | # case we use the pre-built invalidSourceError method to return a standard
180 | # helper text for when a source cannot be evaluated
181 | if cost_raster is None:
182 | raise QgsProcessingException(self.invalidSourceError(parameters, self.INPUT_COST_RASTER))
183 | if cost_raster_band is None:
184 | raise QgsProcessingException(self.invalidSourceError(parameters, self.INPUT_RASTER_BAND))
185 | if start_source is None:
186 | raise QgsProcessingException(self.invalidSourceError(parameters, self.INPUT_START_LAYER))
187 | if end_source is None:
188 | raise QgsProcessingException(self.invalidSourceError(parameters, self.INPUT_START_LAYER))
189 |
190 | if cost_raster.crs() != start_source.sourceCrs() \
191 | or start_source.sourceCrs() != end_source.sourceCrs():
192 | raise QgsProcessingException(self.tr("ERROR: The input layers have different CRSs."))
193 |
194 | if cost_raster.rasterType() not in [cost_raster.Multiband, cost_raster.GrayOrUndefined]:
195 | raise QgsProcessingException(self.tr("ERROR: The input cost raster is not numeric."))
196 |
197 | sink_fields = MinCostPathHelper.create_fields()
198 | output_geometry_type = QgsWkbTypes.LineStringM if output_linear_reference else QgsWkbTypes.LineString
199 | (sink, dest_id) = self.parameterAsSink(
200 | parameters,
201 | self.OUTPUT,
202 | context,
203 | fields=sink_fields,
204 | geometryType=output_geometry_type,
205 | crs=cost_raster.crs(),
206 | )
207 |
208 | # If sink was not created, throw an exception to indicate that the algorithm
209 | # encountered a fatal error. The exception text can be any string, but in this
210 | # case we use the pre-built invalidSinkError method to return a standard
211 | # helper text for when a sink cannot be evaluated
212 | if sink is None:
213 | raise QgsProcessingException(self.invalidSinkError(parameters, self.OUTPUT))
214 |
215 | start_features = list(start_source.getFeatures())
216 | # feedback.pushInfo(str(len(start_features)))
217 |
218 | # row_col, pointxy, id
219 | start_tuples = MinCostPathHelper.features_to_tuples(start_features, cost_raster)
220 | if len(start_tuples) == 0:
221 | raise QgsProcessingException(self.tr("ERROR: The start-point layer contains no legal point."))
222 | elif len(start_tuples) >= 2:
223 | raise QgsProcessingException(self.tr("ERROR: The start-point layer contains more than one legal point."))
224 | start_tuple = start_tuples[0]
225 |
226 | end_features = list(end_source.getFeatures())
227 | # feedback.pushInfo(str(len(end_features)))
228 | end_tuples = MinCostPathHelper.features_to_tuples(end_features, cost_raster)
229 | if len(end_tuples) == 0:
230 | raise QgsProcessingException(self.tr("ERROR: The end-point layer contains no legal point."))
231 |
232 | # if start_row_col in end_row_cols:
233 | # raise QgsProcessingException(self.tr("ERROR: The end-point(s) overlap with start point."))
234 | # feedback.pushInfo(str(start_col_rows))
235 | # feedback.pushInfo(str(end_col_rows))
236 |
237 | block = MinCostPathHelper.get_all_block(cost_raster, cost_raster_band)
238 | matrix, contains_negative = MinCostPathHelper.block2matrix(block)
239 | feedback.pushInfo(self.tr("The size of cost raster is: %d * %d") % (block.height(), block.width()))
240 |
241 | if contains_negative:
242 | raise QgsProcessingException(self.tr("ERROR: Cost raster contains negative value."))
243 |
244 | feedback.pushInfo(self.tr("Searching least cost path..."))
245 |
246 | result = dijkstra(start_tuple, end_tuples, matrix, find_nearest, feedback)
247 | # feedback.pushInfo(str(min_cost_path))
248 | if result is None:
249 | raise QgsProcessingException(self.tr("ERROR: Search canceled."))
250 |
251 | if len(result) == 0:
252 | raise QgsProcessingException(self.tr("ERROR: The end-point(s) is not reachable from start-point."))
253 |
254 | feedback.setProgress(100)
255 | feedback.pushInfo(self.tr("Search completed! Saving path..."))
256 |
257 | for path, costs, terminal_tuples in result:
258 | for terminal_tuple in terminal_tuples:
259 | path_points = MinCostPathHelper.create_points_from_path(cost_raster, path, start_tuple[1], terminal_tuple[1])
260 | if output_linear_reference:
261 | # add linear reference
262 | for point, cost in zip(path_points, costs):
263 | point.addMValue(cost)
264 |
265 | total_cost = costs[-1]
266 | path_feature = MinCostPathHelper.create_path_feature_from_points(path_points, (start_tuple[2], terminal_tuple[2],total_cost), sink_fields)
267 | sink.addFeature(path_feature, QgsFeatureSink.FastInsert)
268 |
269 | # start_point = start_row_cols_dict[start_row_col]
270 | # end_point = end_row_cols_dict[selected_end]
271 | # path_points = MinCostPathHelper.create_points_from_path(cost_raster, min_cost_path, start_point, end_point)
272 | # if output_linear_reference:
273 | # # add linear reference
274 | # for point, cost in zip(path_points, costs):
275 | # point.addMValue(cost)
276 | # total_cost = costs[-1]
277 | # path_feature = MinCostPathHelper.create_path_feature_from_points(path_points, total_cost, sink_fields)
278 |
279 | # sink.addFeature(path_feature, QgsFeatureSink.FastInsert)
280 | return {self.OUTPUT: dest_id}
281 |
282 | def name(self):
283 | """
284 | Returns the algorithm name, used for identifying the algorithm. This
285 | string should be fixed for the algorithm, and must not be localised.
286 | The name should be unique within each provider. Names should contain
287 | lowercase alphanumeric characters only and no spaces or other
288 | formatting characters.
289 | """
290 | return 'Least Cost Path'
291 |
292 | def displayName(self):
293 | """
294 | Returns the translated algorithm name, which should be used for any
295 | user-visible display of the algorithm name.
296 | """
297 | return self.tr(self.name())
298 |
299 | def group(self):
300 | """
301 | Returns the name of the group this algorithm belongs to. This string
302 | should be localised.
303 | """
304 | return self.tr(self.groupId())
305 |
306 | def groupId(self):
307 | """
308 | Returns the unique ID of the group this algorithm belongs to. This
309 | string should be fixed for the algorithm, and must not be localised.
310 | The group id should be unique within each provider. Group id should
311 | contain lowercase alphanumeric characters only and no spaces or other
312 | formatting characters.
313 | """
314 | return ''
315 |
316 | def tr(self, string):
317 | return QCoreApplication.translate('Processing', string)
318 |
319 | def createInstance(self):
320 | return LeastCostPathAlgorithm()
321 |
322 | def helpUrl(self):
323 | return 'https://github.com/Gooong/LeastCostPath'
324 |
325 | def shortHelpString(self):
326 | return self.tr("""
327 | Please ensure all the input layers have the same CRS.
328 |
329 | - Cost raster layer: Numeric raster layer that represents the cost of each spatial unit. It should not contains negative value. Pixel with `NoData` value represent it is unreachable.
330 |
331 | - Cost raster band: The input band of the cost raster.
332 |
333 | - Start-point layer: Layer that contains just one start point.
334 |
335 | - End-point(s) layer: Layer that contains the destination point(s).
336 |
337 | - Only connect with the nearest end points: If more than one destination are provided, it will find the least cost path to all the end points by default. If enabled, the least cost path will only connect start point with the nearest end point.
338 |
339 | - \[Optional\] Include liner referencing (PolylineM type): If selected, this algorithm will output the least cost path in `PolylineM` type, with the accumulated cost as linear referencing value.
340 |
341 | """)
342 |
343 | def shortDescription(self):
344 | return self.tr('Find the least cost path with given cost raster and points.')
345 |
346 | def svgIconPath(self):
347 | return ''
348 |
349 | def tags(self):
350 | return ['least', 'cost', 'path', 'distance', 'raster', 'analysis', 'road']
351 |
352 |
353 | class MinCostPathHelper:
354 |
355 | @staticmethod
356 | def _point_to_row_col(pointxy, raster_layer):
357 | xres = raster_layer.rasterUnitsPerPixelX()
358 | yres = raster_layer.rasterUnitsPerPixelY()
359 | extent = raster_layer.dataProvider().extent()
360 |
361 | col = floor((pointxy.x() - extent.xMinimum()) / xres)
362 | row = floor((extent.yMaximum() - pointxy.y()) / yres)
363 |
364 | return row, col
365 |
366 | @staticmethod
367 | def _row_col_to_point(row_col, raster_layer):
368 | xres = raster_layer.rasterUnitsPerPixelX()
369 | yres = raster_layer.rasterUnitsPerPixelY()
370 | extent = raster_layer.dataProvider().extent()
371 |
372 | x = (row_col[1] + 0.5) * xres + extent.xMinimum()
373 | y = extent.yMaximum() - (row_col[0] + 0.5) * yres
374 | return QgsPoint(x, y)
375 |
376 | @staticmethod
377 | def create_points_from_path(cost_raster, min_cost_path, start_point, end_point):
378 | path_points = list(
379 | map(lambda row_col: MinCostPathHelper._row_col_to_point(row_col, cost_raster), min_cost_path))
380 | path_points[0].setX(start_point.x())
381 | path_points[0].setY(start_point.y())
382 | path_points[-1].setX(end_point.x())
383 | path_points[-1].setY(end_point.y())
384 | return path_points
385 |
386 | @staticmethod
387 | def create_fields():
388 | start_field = QgsField("start point id", QVariant.Int, "int")
389 | end_field = QgsField("end point id", QVariant.Int, "int")
390 | cost_field = QgsField("total cost", QVariant.Double, "double", 10, 3)
391 | fields = QgsFields()
392 | fields.append(start_field)
393 | fields.append(end_field)
394 | fields.append(cost_field)
395 | return fields
396 |
397 | @staticmethod
398 | def create_path_feature_from_points(path_points, attr_vals, fields):
399 | polyline = QgsGeometry.fromPolyline(path_points)
400 | feature = QgsFeature(fields)
401 | # feature.setAttribute(0, 1) # id
402 | start_index = feature.fieldNameIndex("start point id")
403 | end_index = feature.fieldNameIndex("end point id")
404 | cost_index = feature.fieldNameIndex("total cost")
405 | feature.setAttribute(start_index, attr_vals[0])
406 | feature.setAttribute(end_index, attr_vals[1])
407 | feature.setAttribute(cost_index, attr_vals[2]) # cost
408 | feature.setGeometry(polyline)
409 | return feature
410 |
411 | @staticmethod
412 | def features_to_tuples(point_features, raster_layer):
413 | row_cols = []
414 |
415 | extent = raster_layer.dataProvider().extent()
416 | # if extent.isNull() or extent.isEmpty:
417 | # return list(col_rows)
418 |
419 | for point_feature in point_features:
420 | if point_feature.hasGeometry():
421 |
422 | point_geom = point_feature.geometry()
423 | if point_geom.wkbType() == QgsWkbTypes.MultiPoint:
424 | multi_points = point_geom.asMultiPoint()
425 | for pointxy in multi_points:
426 | if extent.contains(pointxy):
427 | row_col = MinCostPathHelper._point_to_row_col(pointxy, raster_layer)
428 | row_cols.append((row_col, pointxy, point_feature.id()))
429 |
430 | elif point_geom.wkbType() == QgsWkbTypes.Point:
431 | pointxy = point_geom.asPoint()
432 | if extent.contains(pointxy):
433 | row_col = MinCostPathHelper._point_to_row_col(pointxy, raster_layer)
434 | row_cols.append((row_col, pointxy, point_feature.id()))
435 |
436 | return row_cols
437 |
438 | @staticmethod
439 | def get_all_block(raster_layer, band_num):
440 | provider = raster_layer.dataProvider()
441 | extent = provider.extent()
442 |
443 | xres = raster_layer.rasterUnitsPerPixelX()
444 | yres = raster_layer.rasterUnitsPerPixelY()
445 | width = floor((extent.xMaximum() - extent.xMinimum()) / xres)
446 | height = floor((extent.yMaximum() - extent.yMinimum()) / yres)
447 | return provider.block(band_num, extent, width, height)
448 |
449 | @staticmethod
450 | def block2matrix(block):
451 | contains_negative = False
452 | matrix = [[None if block.isNoData(i, j) else block.value(i, j) for j in range(block.width())]
453 | for i in range(block.height())]
454 |
455 | for l in matrix:
456 | for v in l:
457 | if v is not None:
458 | if v < 0:
459 | contains_negative = True
460 |
461 | return matrix, contains_negative
462 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------