` `
고급 사용자는 콘솔을 통해 생산성을 향상시키는 것은 물론, 공간 처리 프레임워크의 다른 모든 GUI 항목을 통해서도 수행할 수 없는 복잡한 작업을 수행할 수 있습니다. 명령 줄 인터페이스를 사용해서 여러 알고리즘을 연결한 모델을 정의하고, 더욱 유연하고 강력한 작업 흐름을 생성하기 위한 반복문(for) 및 조건문(if)과 같은 부가적인 작업을 추가할 수 있습니다.
There is not a processing console in QGIS, but all processing commands are available instead from the QGIS built-in Python console. That means that you can incorporate those commands into your console work and connect processing algorithms to all the other features (including methods from the QGIS API) available from there.
사용자가 파이썬 콘솔에서 실행하는 코드는, 비록 어느 특정한 공간 처리 메소드를 호출하지 않더라도, 다른 모든 알고리즘과 마찬가지로 향후 툴박스, 그래픽 모델 생성기, 또는 기타 구성 요소에서 호출할 수 있는 새 알고리즘으로 변환할 수 있습니다. 사실, 툴박스에서 찾아볼 수 있는 알고리즘 가운데 일부는 단순한 스크립트일 뿐입니다.
이 절에서 QGIS 파이썬 콘솔에서 공간 처리 알고리즘을 사용하는 방법과 함께 파이썬으로 알고리즘을 작성하는 방법에 대해 설명하겠습니다.
사용자는 가장 먼저 공간 처리 함수를 다음 명령어로 가져와야 합니다:
>>> import processing
Now, there is basically just one (interesting) thing you can do with that from the console: execute an algorithm. That is done using the runalg() method, which takes the name of the algorithm to execute as its first parameter, and then a variable number of additional parameters depending on the requirements of the algorithm. So the first thing you need to know is the name of the algorithm to execute. That is not the name you see in the toolbox, but rather a unique command–line name. To find the right name for your algorithm, you can use the algslist() method. Type the following line in your console:
>>> processing.alglist()
You will see something like this.
Accumulated Cost (Anisotropic)-------->saga:accumulatedcost(anisotropic)
Accumulated Cost (Isotropic)---------->saga:accumulatedcost(isotropic)
Add Coordinates to points------------->saga:addcoordinatestopoints
Add Grid Values to Points------------->saga:addgridvaluestopoints
Add Grid Values to Shapes------------->saga:addgridvaluestoshapes
Add Polygon Attributes to Points------>saga:addpolygonattributestopoints
Aggregate----------------------------->saga:aggregate
Aggregate Point Observations---------->saga:aggregatepointobservations
Aggregation Index--------------------->saga:aggregationindex
Analytical Hierarchy Process---------->saga:analyticalhierarchyprocess
Analytical Hillshading---------------->saga:analyticalhillshading
Average With Mask 1------------------->saga:averagewithmask1
Average With Mask 2------------------->saga:averagewithmask2
Average With Thereshold 1------------->saga:averagewiththereshold1
Average With Thereshold 2------------->saga:averagewiththereshold2
Average With Thereshold 3------------->saga:averagewiththereshold3
B-Spline Approximation---------------->saga:b-splineapproximation
...
That’s a list of all the available algorithms, alphabetically ordered, along with their corresponding command-line names.
You can use a string as a parameter for this method. Instead of returning the full list of algorithms, it will only display those that include that string. If, for instance, you are looking for an algorithm to calculate slope from a DEM, type alglist("slope") to get the following result:
DTM Filter (slope-based)-------------->saga:dtmfilter(slope-based)
Downslope Distance Gradient----------->saga:downslopedistancegradient
Relative Heights and Slope Positions-->saga:relativeheightsandslopepositions
Slope Length-------------------------->saga:slopelength
Slope, Aspect, Curvature-------------->saga:slopeaspectcurvature
Upslope Area-------------------------->saga:upslopearea
Vegetation Index[slope based]--------->saga:vegetationindex[slopebased]
This result might change depending on the algorithms you have available.
It is easier now to find the algorithm you are looking for and its command-line name, in this case saga:slopeaspectcurvature.
Once you know the command-line name of the algorithm, the next thing to do is to determine the right syntax to execute it. That means knowing which parameters are needed and the order in which they have to be passed when calling the runalg() method. There is a method to describe an algorithm in detail, which can be used to get a list of the parameters that an algorithm requires and the outputs that it will generate. To get this information, you can use the alghelp(name_of_the_algorithm) method. Use the command-line name of the algorithm, not the full descriptive name.
Calling the method with saga:slopeaspectcurvature as parameter, you get the following description:
>>> processing.alghelp("saga:slopeaspectcurvature")
ALGORITHM: Slope, Aspect, Curvature
ELEVATION <ParameterRaster>
METHOD <ParameterSelection>
SLOPE <OutputRaster>
ASPECT <OutputRaster>
CURV <OutputRaster>
HCURV <OutputRaster>
VCURV <OutputRaster>
Now you have everything you need to run any algorithm. As we have already mentioned, there is only one single command to execute algorithms: runalg(). Its syntax is as follows:
>>> processing.runalg(name_of_the_algorithm, param1, param2, ..., paramN,
Output1, Output2, ..., OutputN)
The list of parameters and outputs to add depends on the algorithm you want to run, and is exactly the list that the alghelp() method gives you, in the same order as shown.
파라미터의 유형에 따라, 값을 서로 다르게 입력해야 합니다. 다음은 각 입력 파라미터 유형 별로 값을 입력하는 방법을 간단하게 설명하는 목록입니다:
Raster Layer, Vector Layer or Table. Simply use a string with the name that identifies the data object to use (the name it has in the QGIS Table of Contents) or a filename (if the corresponding layer is not opened, it will be opened but not added to the map canvas). If you have an instance of a QGIS object representing the layer, you can also pass it as parameter. If the input is optional and you do not want to use any data object, use None.
Selection. If an algorithm has a selection parameter, the value of that parameter should be entered using an integer value. To know the available options, you can use the algoptions() command, as shown in the following example:
>>> processing.algoptions("saga:slopeaspectcurvature")
METHOD(Method)
0 - [0] Maximum Slope (Travis et al. 1975)
1 - [1] Maximum Triangle Slope (Tarboton 1997)
2 - [2] Least Squares Fitted Plane (Horn 1981, Costa-Cabral & Burgess 1996)
3 - [3] Fit 2.Degree Polynom (Bauer, Rohdenburg, Bork 1985)
4 - [4] Fit 2.Degree Polynom (Heerdegen & Beran 1982)
5 - [5] Fit 2.Degree Polynom (Zevenbergen & Thorne 1987)
6 - [6] Fit 3.Degree Polynom (Haralick 1983)
In this case, the algorithm has one such parameter, with seven options. Notice that ordering is zero-based.
다중 입력: 쌍반점(;)으로 구분된 입력 서술자(descriptor)를 나타내는 문자열을 입력하십시오. 단일 레이어 또는 테이블의 경우, 데이터 객체의 명칭 또는 파일 경로를 각 입력 서술자로 사용할 수 있습니다.
XXX 테이블의 필드: 사용할 필드의 명칭을 나타내는 문자열을 입력하십시오. 이 파라미터는 대소문자를 구별합니다.
고정 테이블: 큰따옴표(")로 감싸고 쉼표(,)로 구분한 모든 테이블 값의 목록을 입력하십시오. 이때 값은 상단 행부터 왼쪽에서 오른쪽 방향으로 입력합니다. 또는 테이블을 나타내는 값의 2차원 배열을 사용할 수도 있습니다.
CRS: 원하는 좌표계의 EPGS 코드 번호를 입력하십시오.
범위(extent): xmin, xmax, ymin 및 ymax 값을 나타내는 쉼표(,)로 구분한 문자열을 입력해야 합니다.
불(boolean), 파일, 문자열 및 숫자 파라미터에 대해서는 따로 설명이 필요없습니다.
Input parameters such as strings, booleans, or numerical values have default values. To use them, specify None in the corresponding parameter entry.
For output data objects, type the file path to be used to save it, just as it is done from the toolbox. If you want to save the result to a temporary file, use None. The extension of the file determines the file format. If you enter a file extension not supported by the algorithm, the default file format for that output type will be used, and its corresponding extension appended to the given file path.
Unlike when an algorithm is executed from the toolbox, outputs are not added to the map canvas if you execute that same algorithm from the Python console. If you want to add an output to the map canvas, you have to do it yourself after running the algorithm. To do so, you can use QGIS API commands, or, even easier, use one of the handy methods provided for such tasks.
The runalg method returns a dictionary with the output names (the ones shown in the algorithm description) as keys and the file paths of those outputs as values. You can load those layers by passing the corresponding file paths to the load() method.
Apart from the functions used to call algorithms, importing the processing package will also import some additional functions that make it easier to work with data, particularly vector data. They are just convenience functions that wrap some functionality from the QGIS API, usually with a less complex syntax. These functions should be used when developing new algorithms, as they make it easier to operate with input data.
Below is a list of some of these commands. More information can be found in the classes under the processing/tools package, and also in the example scripts provided with QGIS.
You can create your own algorithms by writing the corresponding Python code and adding a few extra lines to supply additional information needed to define the semantics of the algorithm. You can find a Create new script menu under the Tools group in the Script algorithms block of the toolbox. Double-click on it to open the script editing dialog. That’s where you should type your code. Saving the script from there in the scripts folder (the default folder when you open the save file dialog) with .py extension will automatically create the corresponding algorithm.
The name of the algorithm (the one you will see in the toolbox) is created from the filename, removing its extension and replacing low hyphens with blank spaces.
Let’s have a look at the following code, which calculates the Topographic Wetness Index (TWI) directly from a DEM.
##dem=raster
##twi=output
ret_slope = processing.runalg("saga:slopeaspectcurvature", dem, 0, None,
None, None, None, None)
ret_area = processing.runalg("saga:catchmentarea(mass-fluxmethod)", dem,
0, False, False, False, False, None, None, None, None, None)
processing.runalg("saga:topographicwetnessindex(twi), ret_slope['SLOPE'],
ret_area['AREA'], None, 1, 0, twi)
As you can see, the calculation involves three algorithms, all of them coming from SAGA. The last one calculates the TWI, but it needs a slope layer and a flow accumulation layer. We do not have these layers, but since we have the DEM, we can calculate them by calling the corresponding SAGA algorithms.
The part of the code where this processing takes place is not difficult to understand if you have read the previous sections in this chapter. The first lines, however, need some additional explanation. They provide the information that is needed to turn your code into an algorithm that can be run from any of the GUI components, like the toolbox or the graphical modeler.
These lines start with a double Python comment symbol (##) and have the following structure:
[parameter_name]=[parameter_type] [optional_values]
Here is a list of all the parameter types that are supported in processing scripts, their syntax and some examples.
The parameter name is the name that will be shown to the user when executing the algorithm, and also the variable name to use in the script code. The value entered by the user for that parameter will be assigned to a variable with that name.
When showing the name of the parameter to the user, the name will be edited to improve its appearance, replacing low hyphens with spaces. So, for instance, if you want the user to see a parameter named A numerical value, you can use the variable name A_numerical_value.
Layers and table values are strings containing the file path of the corresponding object. To turn them into a QGIS object, you can use the processing.getObjectFromUri() function. Multiple inputs also have a string value, which contains the file paths to all selected object, separated by semicolons (;).
Outputs are defined in a similar manner, using the following tags:
The value assigned to the output variables is always a string with a file path. It will correspond to a temporary file path in case the user has not entered any output filename.
When you declare an output, the algorithm will try to add it to QGIS once it is finished. That is why, although the runalg() method does not load the layers it produces, the final TWI layer will be loaded (using the case of our previous example), since it is saved to the file entered by the user, which is the value of the corresponding output.
Do not use the load() method in your script algorithms, just when working with the console line. If a layer is created as output of an algorithm, it should be declared as such. Otherwise, you will not be able to properly use the algorithm in the modeler, since its syntax (as defined by the tags explained above) will not match what the algorithm really creates.
Hidden outputs (numbers and strings) do not have a value. Instead, you have to assign a value to them. To do so, just set the value of a variable with the name you used to declare that output. For instance, if you have used this declaration,
##average=output number
the following line will set the value of the output to 5:
average = 5
In addition to the tags for parameters and outputs, you can also define the group under which the algorithm will be shown, using the group tag.
If your algorithm takes a long time to process, it is a good idea to inform the user. You have a global named progress available, with two possible methods: setText(text) and setPercentage(percent) to modify the progress text and the progress bar.
Several examples are provided. Please check them to see real examples of how to create algorithms using the processing framework classes. You can right-click on any script algorithm and select Edit script to edit its code or just to see it.
As in the case of models, you can create additional documentation for your scripts, to explain what they do and how to use them. In the script editing dialog, you will find an [Edit script help] button. Click on it and it will take you to the help editing dialog. Check the section about the graphical modeler to know more about this dialog and how to use it.
Help files are saved in the same folder as the script itself, adding the .help extension to the filename. Notice that you can edit your script’s help before saving the script for the first time. If you later close the script editing dialog without saving the script (i.e., you discard it), the help content you wrote will be lost. If your script was already saved and is associated to a filename, saving the help content is done automatically.
Scripts can also be used to set pre- and post-execution hooks that are run before and after an algorithm is run. This can be used to automate tasks that should be performed whenever an algorithm is executed.
후크의 문법은 앞에서 설명한 문법과 동일하지만, alg 라는 또다른 전체 수준 변수를 사용할 수 있습니다. alg 는 방금 실행된 (또는 곧 실행될) 알고리즘을 나타내는 변수입니다.
In the General group of the processing configuration dialog, you will find two entries named Pre-execution script file and Post-execution script file where the filename of the scripts to be run in each case can be entered.