├── Dataset ├── README.md ├── autobahn.gpkg ├── heli.tif └── umgebung.gpkg ├── Hands on Exercises.md ├── LICENSE ├── README.md ├── Scripts ├── Master Script Model.py ├── Master Script Straightforward.py ├── Master Script with Info.py ├── Models │ └── Workshop Graphic Modeler Example.model3 ├── README.md ├── Task 5.py └── Tasks 1-4.2.py ├── Workflow ├── Highway Construction Workflow English.doc └── readme.md └── Workshop Slides ├── GeoPython Conference 2018.pdf ├── Slides Images ├── Buffer Log Example.png ├── Graphic Modeler Example.png ├── Graphic Modeler.png ├── History Tool.png ├── Processing Toolbox.png ├── Scripts Tool 2.png ├── Scripts Tool.png ├── Task 1.png ├── Task 3 Example.png ├── Task 3.1.png ├── Task 3.2.png ├── Task 4 Example.png ├── Task 4.1.png ├── Task 4.2.png ├── Task 5.1.png ├── Task 5.2.png ├── Task 6.1.png ├── Task 6.2.png ├── Task 7.png └── readme └── readme.md /Dataset/README.md: -------------------------------------------------------------------------------- 1 | Included are two datasets necessary for the workflow to be completed. 2 | \ 3 | **Credits go to Claas Leiner of the University of Kassel, 2010 as this workflow was based on Task 6 of the course "Introduction to GIS and Digital Cartography"** 4 | **Note: This workflow has been adapted by Stefan Keller, Geometa Lab, Hochschule fur Technik Rapperswil for use as course material.** 5 | **Note 2: Subsequently, it was translated into English by Kang Zi Jing into English and updated for QGIS 3.0, for use in the GeoPython Conference 2018.** 6 | 7 | This folder contains 3 files: 8 | * umgebung.gpkg 9 | * autobahn.gpkg 10 | * heli.tif 11 | 12 | The **_umgebung.gpkg_** file is a GeoPackage file which contains a multi-polygonal vector layer with a database containing attributes like 13 | the use of habitats, the laws that protects the specific habitat, etc.\ 14 | The **_autobahn.gpkg_** file is a GeoPackage file which contains a line vector layer which shows the propsed route of the autobahn to be 15 | constructed without showing the physical space (of 20m) that it would take up.\ 16 | The **_heli.tif_** file is generally inconsequent for the majority of the workshop and the main workshop tutorial. It is basically a raster file to be added as a reference basemap at the end of the entire workflow, for user reference and some aesthetic value.\ 17 | \ 18 | These files, along with its attributes, have been kept in its original language, German, so as to avoid introducing any possible errors 19 | or other ambiguities when performing geoanalytical tasks on them in the course of the workshop. For your reference, below is a 20 | glossary of the translations of some of the attributes that would be used in the workshop. 21 | \ 22 | It is entirely possible to finish the workflow without knowing what the German words mean, but for non native speakers, the terms that would be used and 23 | we are interested in are bolded in the table below, for convenience. 24 | 25 | # Glossary 26 | |German|English|Meaning of Attribute| 27 | |:---:|:---:|:---:| 28 | |**umgebung**|environment|See above| 29 | |**autobahn**|highway/expressway|See above| 30 | ||| 31 | ||| 32 | |fid|Habitat ID|ID of Habitat/Attribute| 33 | |nutzung|(Land) Use|What the habitat is used for| 34 | |nutzungs_nr|(Land) Use no.|Different uses ordered by a number| 35 | |bfn_gesetz|Law number under BFN|The associated BFN law| 36 | |bfn_biotop_nr|Biotope no. under BFN|BFN Biotope number| 37 | |bfn_biotop_text|Biotope text under BFN|BFN Biotope description| 38 | |**ffh_typ_nr**|FFH Type|Boolean: Protected by FFH| 39 | |ffh_typ_text|FFH Type Text|Reference Text for Associated FFH| 40 | |**geschuetzt_biotop**|Protected Biotope|Boolean: Protected Species| 41 | |gruenland_typ|Open Field Type|Type of Open Field| 42 | |eutend_gruenland_|Open Field|Boolean: Open Field| 43 | |**bedeutend_gruendland_typ**|Significant Open Field|Boolean: Significance| 44 | * Note: The cells with "Boolean" in front means that the attributes is Booleanic, a 0 means false while a 1 means true for the attribute associated. 45 | -------------------------------------------------------------------------------- /Dataset/autobahn.gpkg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geometalab/GeoPythonConf2018-QGIS-Processing-Workshop/c74abbd235a9795c8dacbec10259c6fd07f27f6f/Dataset/autobahn.gpkg -------------------------------------------------------------------------------- /Dataset/heli.tif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geometalab/GeoPythonConf2018-QGIS-Processing-Workshop/c74abbd235a9795c8dacbec10259c6fd07f27f6f/Dataset/heli.tif -------------------------------------------------------------------------------- /Dataset/umgebung.gpkg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geometalab/GeoPythonConf2018-QGIS-Processing-Workshop/c74abbd235a9795c8dacbec10259c6fd07f27f6f/Dataset/umgebung.gpkg -------------------------------------------------------------------------------- /Hands on Exercises.md: -------------------------------------------------------------------------------- 1 | # GeoPython Conference 2018 2 | **Processing Framework: Automating Tasks with Python** 3 | \ 4 | A QGIS workshop for the GeoPython Conference 2018 5 | 6 | ## Getting started 7 | 1. [Download and install QGIS 3.x](https://www.qgis.org/en/site/forusers/download.html) (Only QGIS 3.0 and above is supported because of changes in the update from 2.18 to 3.0 8 | 2. Get the sample data that we will be using from this repository 9 | 3. Fire up QGIS and we're ready! 10 | 11 | Downloading the standalone or OSGeo4W installer will automatically install the correct version of Python as well as Qt and PyQt. 12 | 13 | ## Setting up your development environment 14 | To try out our hands on examples, the following is required: 15 | * QGIS 3.x (We will be using QGIS 3.0) 16 | * Python 3.x (We will be using Python 3.6) 17 | * Qt 18 | * PyQt 19 | 20 | **Notes:** 21 | * This repository contains the hands-on problem sets and tasks that we will try out during the workshop. It also contains the suggested solutions, master scripts, and graphic models for the tasks, and problem as a whole. 22 | * For QGIS <2.99 users, these problem sets are still workable, but do take note that as QGIS upgraded from QGIS 2.18 to QGIS 3.0.0, there are a lot of changes, including the Python syntax to be upgrade from Python 2.6 to Python 3.6 23 | * It is still possible to follow this workshop in QGIS 2.18, but do make sure that you are aware of the backwards incompatible changes as many methods and functions were made obsolete or renamed. You can see the [version changelog here](https://qgis.org/api/api_break.html#qgis_api_break_3_0_QgsGeometryAnalyzer) 24 | * To be more specific and as a disclaimer, it is rather redundant if you are following this workshop using QGIS 2.18, as the LTR version of QGIS would soon be updated to QGIS 3.x, and the workshop here would still be very likely to work in the LTR 25 | 26 | ## Getting more sample data 27 | If you want more sample data or resources to further try out QGIS on your own, look no further: 28 | 29 | * [The PyQGIS Programmer's Guide](http://locatepress.com/ppg3) 30 | * [The QGIS website also has some sample data](http://www.qgis.org) 31 | * For raster layers to play around with, we can download one of the [Natural Earth rasters](http://www.naturalearthdata.com/downloads/) 32 | * You can also check out [our Geometa Lab Blog](geometa.tumblr.com) for some posts on QGIS tips and tricks and other tidbits on GIS 33 | 34 | ## Using the QGIS Python Console 35 | * With QGIS running, open the console by going to `Plugins -> Python Console`, clicking on the `Python Console` button from the `Plugin toolbar`, or simply press `Alt + Ctrl + P` on the keyboard 36 | * The toolbar contains the tools **Clear console, Import Class, Run Command, Show Editor, Settings,** and **Help** 37 | * The built-in code editor can be used alongside the console 38 | * The QGIS API offers a large number of [Python classes](http://labs.webgeodatavore.com/partage/diagramme_principal.html) that we can use. See [Searchable documentation of PyQGIS classes](http://geoapis.sourcepole.com/qgispyapi/qgsnetworkaccessmanager) 39 | * For the convenience of the user, the following statements are executed when the consoles is started 40 | ```python 41 | from qgis.core import * 42 | import qgis.utils 43 | ``` 44 | 45 | ## Introduction to Processing Framework 46 | * More information can be found in the slides also available in this repository 47 | 48 | ## About PyQGIS 49 | * QGIS 0.9.0 introduced Python to its client 50 | * PyQGIS or Python Console in QGIS client 51 | * Features of PyQGIS: 52 | * Automatically run Python code when QGIS starts 53 | * Create custom applications with Python API 54 | * Run Python code and commands on the Python Console 55 | * Create and use Python plugins 56 | 57 | \ 58 | \ 59 | \ 60 | # **Task: Perform Geospatial Analysis on Protected Habitats in an Environment** 61 | * Problem: The construction of an autobahn/expressway will lead to detrimental impact onto the habitats on its environment. Analyze the protected habitats that would be affected by the construction. 62 | * Source: This task is based on Task 6 of the course _Introduction to GIS and Digital Cartography_ by Claas Leiner, University of Kassel, 2010. 63 | * Adapted to a class for Vector Analysis by Stefan Keller, FS 2017 64 | * Translated and adapted for QGIS 3.0 and the GeoPython Conference by Kang Zi Jing, 2018 65 | * The workflow can be found in the repository, here [link to the tutorial course] 66 | 67 | **As you can already tell, doing this over and over again on different files is very tedious, boring and repetitive. Is there a way to automate this? Yes! With the help of scripting and PyQGIS, we can!**\ 68 | \ 69 | With the click of a button to run a script, we can automate this task in mere seconds.\ 70 | This problem will be broken down into smaller problem sets and tasks to break the problem apart. The tasks will be progressive, from getting familiar with the QGIS client to using its Processing toolbox tools, like the Graphical Modeler before moving on to creating your own custom script. 71 | 72 | 73 | ## **Task 1.** Adding GeoPackage as Layers into QGIS 74 | - **Dataset used:** Umgebung.gpkg, Autobahn.gpkg 75 | - **Tools used:** QGIS GUI, PyQGIS 76 | - **Description:** To load .gpkg files into QGIS client 77 | - **Objective:** Manually load vector layers on QGIS, and then using the Python console 78 | 79 | #### Task 1.1. Manually adding the GeoPackage files into QGIS 80 | 1. Run QGIS 3.0 on your machine 81 | 2. The first step is to set the Project CRS to 31467, DHDN/Gauss-Kruger Zone 3 82 | 3. You can do this manually by clicking on the CRS at the bottom-right of the window, or by clicking `Project -> Project Properties -> CRS` or you can press `Ctrl + Shift + P` to open up Project Properties and then clicking CRS 83 | 4. From there, change the CRS to DHDN/Gauss-Kruger zone 3, EPSG: 31467 84 | 5. Once you're done, check that it says 31467 at the bottom of the window on the CRS tab 85 | 6. Now on the browser panel, look for GeoPackage, right click it and select **New Connection** 86 | 7. Navigate to the folder you saved environment/umgebung.gpkg in and add it 87 | 8. On the browser panel, show the child items of environment/umgebung.gpkg and drag the vector layer onto the map canvas 88 | 9. As we are going to focus on scripting in Python, let's remove this layer: right click the layer under Layers, and click on remove 89 | 90 | #### Task 1.2. Creating a Dialog Box to ask for User Input on File to Add\ 91 | We want to write a script to automate tasks, so let us explore asking for user input for file path 92 | 1. On the Menu Toolbar, click `Plugins -> Python Console` or press `Ctrl + Alt + P` on your keyboard to open up the Python Console 93 | 2. You can run Python code on the console to perform various tasks, try creating a file dialog box that asks for user input on the file path 94 | 3. `envPath = QFileDialog.getOpenFileName(QFileDialog(), "Environment Layer Select", "setDefaultPath")[0]` 95 | 4. The `[0]` is because the above returns a list, and we only need the first value of it, which is the file path 96 | 97 | #### Task 1.3. Adding Vector Layers into QGIS 98 | Now we can add the user input layer into QGIS 99 | 1. `env = iface.addVectorLayer(envPath, 'nameIt', 'ogr')` 100 | 2. If the layer name is saved as something else, you can change it with `env.setName("newName")` 101 | 3. Practice and do the same for the Autobahn layer using the Python console 102 | 103 | ![Reference](https://github.com/bigzijing/Geopython-Conference-2018/blob/master/Workshop%20Presentation%20Slides/Workflow%20Example%20Images/Task%201.png) 104 | 105 | ## Task 2. Adding Buffers to Autobahn Layer 106 | - **Dataset used:** Autobahn.gpkg 107 | - **Tools used:** Processing Graphic Modeler, Python Console 108 | - **Description:** To create buffer layers for the Autobahn to simulate the actual physical space of it 109 | - **Objective:** Running Processing algorithms on the Graphic Modeler, and then with Pythonic code 110 | 111 | #### Task 2.1. Introduction and Running the Graphic Modeler 112 | The Graphic Modeler is a good introduction to scripting in PyQGIS because the coding and scripting is displayed for the user as something visual, which is easy on the beginners 113 | 1. To start off, you need to open up your Processing Toolbox, on the menu toolbar, click `Processing -> Toolbox` or press `Ctrl + Alt + T` and see that the Processing Toolbox window now appears on the right side of the QGIS window 114 | 2. On the Toolbox's menu toolbar, click `Models -> Create New Model` 115 | 3. First, we need to visualize and get an idea of what we want to achieve (this helps us to form pseudo code before creating actual code in the future): Run through the Autobahn layer with a Buffer algorithm to create a new Autobahn layer that is 40m wide in diameter 116 | 117 | #### Task 2.2. Create a 20m buffer file for the Autobahn layer using the Graphic Modeler 118 | With the Processing Graphic Modeler open, we can now visualize and build Task 2.1.3 119 | 1. Name the Model `Autobahn Buffer` and the Group `vector` 120 | 2. On the bottom left, click on Input if it is not already selected, and drag Vector Layer into the blank canvas 121 | 3. Name the parameter name `Autobahn` and under Geometry type, select Line as we only want it to exclusively deal with line geometries 122 | 4. Drag a Number under Input into the canvas, and name it `Buffer Distance`, you may choose to fill in the other fields 123 | 5. On the bottom left, click on Algorithms, and in the searchbar, type 'Buffer', and drag the Algorithm called Buffer into the canvas, making sure it is under *Vector Geometry* and not any other algorithm provider 124 | 6. In the Input Layer field, select `Autobahn` from the dropdown menu, in the Distance field, type `@bufferdistance`, and in the Buffered field, type *Output Layer Name* 125 | 7. On your canvas, you should see that **Buffer Distance** and **Autobahn** are connected as inputs to **Buffer** which gives an output named **Output Layer Name** 126 | 8. On the menu toolbar, click on the green arrow Run Model or press F5 to run the model 127 | 9. Under Autobahn, select your Autobahn vector layer from the drop down menu, under Buffer Distance, type in **20** and under Output Layer Name, type **Autobahn 20** and run it 128 | 10. Let the Model run and after processing, you should see the output vector on your main QGIS window 129 | 130 | ![Reference](https://github.com/bigzijing/Geopython-Conference-2018/blob/master/Workshop%20Presentation%20Slides/Slide%20Images/Graphic%20Modeler%20Example.png) 131 | 132 | #### Task 2.3. Recreating the same function using a standalone script 133 | Now that you visualized your steps, you can now try to translate them into actual Pythonic code on the Python Console\ 134 | 1. On the main QGIS window, at the Processing Toolbox, search for **Buffer**, this is the algorithm that we utilized in the Modeler 135 | 2. Double click on it and you can do essentially the same thing as we did in the modeler, except with a few extra fields that we set to default in the Modeler 136 | 3. Enter the fields for **Input Layer, Distance and Buffered** and run it 137 | 4. At the top of the window, click on Log, you will see a bunch of code, we will be needing this for our script 138 | 5. Study the Input parameters and copy its entire line of code 139 | 6. On the PyQGIS console, type `atbn = QgsProject.instance().mapLayersByName('%NAMEOFYOURAUTOBAHNLAYER%')[0]`, this assigns the vector layer of your autobahn to the variable `atbn` 140 | 7. On the PyQGIS console, type `param =` and paste the copied code, and edit some fields, it should look something like this:\ 141 | `` 142 | param = { 'INPUT' : atbn, 'DISTANCE' : 20, 'SEGMENTS' : 5, 'END_CAP_STYLE' : 0, 'JOIN_STYLE' : 0, 'MITER_LIMIT' : 2, 'DISSOLVE' : False, 'OUTPUT' : 'memory:' } 143 | `` 144 | We changed the file paths or assigned them to variables to make it easier for us because the Python console cannot read Unicode characters like `\` 145 | 8. Now to add the output as a map layer, type: 146 | ``` 147 | algoOutput = processing.run("qgis:buffer", param) 148 | autobahn20 = QgsProject.instance().addMapLayer(algoOutput['OUTPUT']) 149 | autobahn20.setName("Autobahn 20") 150 | ``` 151 | 152 | ![Reference](https://github.com/bigzijing/Geopython-Conference-2018/blob/master/Workshop%20Presentation%20Slides/Slide%20Images/Buffer%20Log%20Example.png) 153 | 154 | #### Task 2.4. Creating 2 more buffers 155 | Often times, the actual physical space that a highway construction takes up, is smaller than the actual impact that it causes to the environment.\ 156 | Create 2 more buffers to depict 2 more impact zones that the construction of the Autobahn would cause\ 157 | Bonus: You may also create a script that interactively asks for user input before running the Buffer algorithm 158 | 1. On the Processing Toolbox, press the Scripts button and select **Create New Script** 159 | 2. It will open up a text editor where you can write your Pythonic scripts 160 | 3. Add the following as the header of your script: 161 | ``` 162 | from qgis.core import QgsProject 163 | import processing 164 | ``` 165 | 4. Write a script that does the following: 166 | ``` 167 | 1. Using Autobahn 20 and 100m as inputs, create a new buffer naemd Autobahn 100 168 | 2. Using Autobahn 100 and 200m as inputs, create a new buffer named Autobahn 300 169 | 170 | Hint: You might need to assign the variable `autobahn20` in the script, do this with: `autobahn20 = QgsProject.instance().mapLayersByName("%name_of_layer%)[0] 171 | ``` 172 | 5. Save the script 173 | 174 | ## Task 3. Performing Union on the Buffer Areas 175 | - **Dataset used:** Autobahn.gpkg, and the 3 buffer results from previous task 176 | - **Tools used:** Python Console, Script Editor 177 | - **Description:** Now that we have 3 separate buffer layers to showcase the impact areas, we should perform an Union on them to create an overall area of impact from constructing the highway 178 | - **Objective:** Get more familiar with using Pythonic code to run Processing algorithms 179 | 180 | #### Task 3.1. Union-ing the Inner Impact Zone 181 | Now that we have tried to run Processing algorithms on the Python Console, let us try it on a standalone script 182 | 1. Open a new script and include the same headers from the previous script here 183 | 2. Now, we are going to run a different algorithm, the Union 184 | 3. Back on the main QGIS window, in the Processing Toolbox search bar, search **Union** and you can try running the Union algorithm under **Vector Overlay** 185 | 4. The inputs will be **Autobahn 20** and **Autobahn 100**, and name the output **Inner Impact Area** 186 | 5. Using the input parameters under Log of the algorithm window, write a script similar to Task 2 187 | 6. If you have trouble doing it, you can try using the Modeler to visualize your script 188 | 189 | #### Task 3.2. Union-ing the Overall Impact Area 190 | Next, we perform the Union algorithm on the result of the previous task, the Inner Impact Zone, with the Outer Impact Zone to aggregate the total Area of Impact 191 | 1. Do the same for the resulting layer, Inner Impact Area and Autobahn 300 and name the output **Impact Area** 192 | 2. You will now have a layer that is the union of all 3 Autobahn buffers 193 | 3. You can see a screenshot of what your project should roughly look like below: 194 | 195 | ![Reference](https://github.com/bigzijing/Geopython-Conference-2018/blob/master/Workshop%20Presentation%20Slides/Slide%20Images/Task%203%20Example.png) 196 | 197 | ## Task 4. Refining Code 198 | - **Dataset used:** Umgebung.gpkg, union result from previous task 199 | - **Tools used:** Script Editor 200 | - **Description:** Now that we have an overall impact area, we run an Intersection algorithm on it and the Environment layer to highlight the habitats that would be affected 201 | - **Objectives:** More scripting with Processing algorithms, also introduction to function declarations 202 | 203 | #### Task 4.1. Performing Intersection on Environment and Impact Area 204 | You have already created your own script! Now that we are more familiar with scripting, we shall now cover the rest of the tasks using scripts \ 205 | Now, as mentioned, run an Intersection algorithm on the Environment layer as well as the Impact Zone layer 206 | 1. Similar to Task 3, we shall now run an Intersection algorithm on the **Impact Area** layer and the **Environment** layer 207 | 2. However, let's make our script cleaner and friendlier, we can do this by defining functions, which are reusable blocks of code 208 | 3. Start by creating a new script with the same headers as previous and then change the following pseudo code into actual Python code: 209 | ``` 210 | from dataSources import dataLibraries 211 | 212 | def intersect_layers(layer1, layer2, outputName): 213 | param = { 'INPUT' : layer1, 'OVERLAY' : layer2, 'INPUT_FIELDS' : [], 'OVERLAY_FIELDS' : [], 'OUTPUT' : 'memory:' } 214 | intxnOp = QgsProject.instance().addMapLayer(processing.run("qgis:intersection", param)['OUTPUT']) 215 | intxnOp.setName(outputName) 216 | 217 | ``` 218 | 4. Save the script, and on the Python Console select Open Script and open the script you just saved, after that, select Run Script on the Python Console. What happened is that you created a function in the script such that when the script is run, a function named **intersect_layers** is available to be called, which takes 3 variable inputs **layer1, layer2** and **outputName** 219 | 5. When you call the function with the correct inputs, it will create and output, with the name of outputName, which is the intersection of the first 2 input vector layers 220 | 6. For this to work for us, we have to assign the **Environment** layer and **Impact Area** layer 221 | 7. Hint: 222 | ``` 223 | layerA = QgsProject.instance().mapLayersByName('Environment') 224 | layerB... 225 | opName = ' xxx ' 226 | 227 | intersect_layers(layerA, layerB, opName) 228 | ``` 229 | 8. Your result should look something like this: 230 | 231 | ![Reference](https://github.com/bigzijing/Geopython-Conference-2018/blob/master/Workshop%20Presentation%20Slides/Slide%20Images/Task%204%20Example.png) 232 | 233 | #### Task 4.2. Doing the Same for Previous Tasks 234 | Now that you have learned how to define a function in a script, do it for: 235 | 1. Adding a vector layer with user input from a dialog box 236 | 2. Adding a buffer 237 | 3. Performing an union 238 | 4. Performing an intersection 239 | 5. Hint: It should look something like this: 240 | ``` 241 | import libraries 242 | 243 | def add_layer(inputs): 244 | """your code here""" 245 | 246 | def set_CRS(input): 247 | """your code here""" 248 | 249 | def more_functions(inputs): 250 | """"your code here"""" 251 | ```` 252 | 7. Once you have finished the script, run it, then on the Python console, declare and assign your variables, then try running the functions you have defined, you should be able to recreate the project thus far 253 | 8. Due to time constraint during the actual workshop, we might not have time to do this for every task, so here is a script that works and already have these function declarations [link] 254 | 9. We shall now continue writing the script by declaring functions to allow easy reusability and calling 255 | 256 | ## Task 5. Selecting Features from Queries 257 | - **Dataset used:** Umgebung.gpkg 258 | - **Tools used:** Query Features and Script Editor 259 | - **Description:** Now, we have to sieve out, from the impacted and affected habitats, those that are protected species from the others 260 | - **Objectives:** Feature query on QGIS, feature query in PyQGIS, adding layers in PyQGIS 261 | 262 | #### Task 5.1. Running a Query on the Environment Vector Layer Attributes 263 | Query the attributes of the Environment Shapefile to determine the features that are protected by law\ 264 | 1. To do this, right click on the Environment layer in the Layers panel, and select Open Attribute Table 265 | 2. On the top menu bar, click the button that says `Select features with an expression` 266 | 3. Write the expression for which you want to select queries with, for our case, we are looking for habitats where `"ffh_typ_nr" = 1`, `"geschuetzt_biotop" = 1`, or `"bedeutend_gruendland_type" = 1` 267 | 4. Once you have written the expression, click on `Select Features`, you should have 43 features highlighted 268 | 269 | ![Reference](https://github.com/bigzijing/Geopython-Conference-2018/blob/master/Workshop%20Presentation%20Slides/Workflow%20Example%20Images/Task%206.1.png) 270 | 271 | #### Task 5.2. Translating Query Feature into Pythonic Code 272 | Now we do what we did in 5.1 using Pythonic code in our script 273 | 274 | 1. Remember, we are looking for habitats where `"ffh_typ_nr" = 1`, `"geschuetzt_biotop" = 1`, or `"bedeutend_gruendland_type" = 1` 275 | 2. In your script, type: 276 | ``` 277 | expr = QgsExpression("\"ffh_typ_nr\"=1 or \"geschuetzt_biotop\" = 1 or \"bedeutend_gruenland_typ\" = 1") 278 | ``` 279 | 3. Next, we need to select all features that meet this query: 280 | ``` 281 | it = env.getFeatures(QgsFeatureRequest(expr)) 282 | ``` 283 | 284 | ![Reference](https://github.com/bigzijing/Geopython-Conference-2018/blob/master/Workshop%20Presentation%20Slides/Workflow%20Example%20Images/Task%206.2.png) 285 | 286 | 287 | #### Task 5.3. Adding Vector Layer of Selected Features 288 | Now we have to create new layers with just the selected features to show which features are actually affected by the Autobahn construction 289 | 1. Now that we have a layer with highlighted features, go back to the QGIS window, right click the Environment layer and select `Save As...` 290 | 2. On the new window, fill in the relevant fills, and make sure that `Save only selected features` is checked 291 | 292 | #### Task 5.4. Translating Vector Layer Adding into Pythonic Code 293 | 1. And then, we want to create a new layer made from the selected features: 294 | ``` 295 | ids = [i.id() for i in it] 296 | intersectedHabs.selectByIds(ids) 297 | valuable = env.materialize(QgsFeatureRequest().setFilterFids(intersectedHabs.selectedFeatureIds())) 298 | QgsProject.instance().addMapLayer(valuable) 299 | ``` 300 | 5. Lastly, we can set the name and deselect the highlighted features with `%LAYERNAME%.selectByIds([])` 301 | 302 | ## Task 6. Stylizing and Cleaning Up 303 | - **Dataset used:** 304 | - **Tools used:** Script Editor 305 | - **Description:** Stylize the map layers to make results more obvious and clean up the project to make it more readable 306 | - **Objectives:** Various styling tools and functions on QGIS, and then on PyQGIS 307 | 308 | #### Task 6.1. Deleting Intermediate Layers 309 | Some of the intermediate layers can be deleted because they serve no actual analytical purpose 310 | 1. Look at your project and determine which ones are inconsequent to your overall analysis, and you may want to delete them from the project to make it more readable and less cluttered 311 | 2. Psuedocode for doing this: 312 | ``` 313 | - find the id of the map layers you want to delete, you may find it through mapLayersByName() 314 | - make sure that you have the pointer to the vector map layer object of the layer you want to delete 315 | - call removeMapLayer() from QgsProject instance 316 | ``` 317 | 318 | #### Task 6.2. Hiding Layers 319 | Some of the result layers can be useful, but too many layers visible on the project makes it hard to read\ 320 | Uncheck their visibility using a script so that they are still available, but not visible on the Map Canvas\ 321 | 1. Pseudocode: 322 | ``` 323 | - get a pointer to your layer under layerTreeRoot() 324 | - setItemVisibilityChecked(False) for that data object 325 | ``` 326 | 327 | #### Task 6.3. Stylizing Map Layers 328 | There are many styles that can be utilized on the layers so that you can get information at a glance\ 329 | For today, we try to stylize them by categorizing different data in different colors and similar data in different shades 330 | 1. First we have to choose the attributes we want to categorize our vector layer in, for this example, say we want to make all the valuable habitats that are impacted to be green, and we want to categorize it by the type of FFH classification it falls into 331 | 2. To do that, we have to find out how many unique FFH classifications we have in the layer: 332 | ``` 333 | classNames = valuableIntersected.fields().indexFromName('ffh_typ_text') 334 | uniqueClass = valuableIntersected.dataProvider().uniqueValues(classNames) 335 | 336 | categories = [] 337 | count = 0 338 | 339 | for class in uniqueClass: 340 | count += 1 341 | ``` 342 | 3. Now, we categorize the different types of attibutes with a different shade of color: 343 | ``` 344 | for classes in uniqueClass: 345 | symbol = QgsSymbol.defaultSymbol(layer.geometryType()) 346 | layerStyle = {} 347 | layerStyle['color'] = '%d, %d, %d' % ( your desired RGB values ) 348 | layerStyle['outline'] = '#000000' 349 | symbolLayer = QgsSimpleFillSymbolLayer.create(layerStyle) 350 | if symbolLayer is not None: 351 | symbol.changeSymbolLayer(0, symbolLayer) 352 | 353 | category = QgsRendererCategory(uniqueClass, symbol, str(classes) 354 | categories.append(category) 355 | ``` 356 | 4. Run the renderer and repaint: 357 | ``` 358 | renderer = QgsCategorizedSymbolRenderer('ffh_typ_text', categories) 359 | if renderer is not None: 360 | valuableIntersected.setRenderer(renderer) 361 | valuableIntersected.triggerRepaint() 362 | ``` 363 | 364 | #### Task 6.4. Adding a Basemap 365 | We can add a raster basemap as a reference for your geospatial data analysis 366 | 1. Get an input for the path which the raster map is stored 367 | 2. Use addRasterLayer() to add the raster layer 368 | 3. You may want to player with the renderer() and symbol() to adjust the basemap stylization settings 369 | 370 | #### Task 6.5. Rearranging the Layers 371 | Let's rearrange the layers for better visibility by putting the original Autobahn 20 and Autobahn vector files at the top of the order 372 | 1. Get the layerTreeRoot() of the QgsProject 373 | 2. Find the layers you want to reslot using findLayer() 374 | 3. clone them using clone() 375 | 4. Get a pointer to the parent object of the layer using parent() 376 | 5. Insert the clones into the parent node and remove the original layers using insertChildNode(position, layer) and removeChildNode() 377 | 6. Refresh the map canvas 378 | 379 | ![Reference](https://github.com/bigzijing/Geopython-Conference-2018/blob/master/Workshop%20Presentation%20Slides/Workflow%20Example%20Images/Task%207.png) 380 | 381 | ## Task 7. Finishing Up 382 | - **Dataset used:** 383 | - **Tools used:** Script Editor 384 | - **Description:** Finish up and make sure that all your code is in a single script and everything works when you run it! 385 | - **Objectives:** Finishing touches, making sure all is good 386 | 387 | #### Task 7.1. Finishing Touches 388 | For the last touch, make sure that all your functions and code are all properly ordered and functions properly 389 | 1. Clear the QGIS canvas by typing `QgsProject.instance().clear()` 390 | 2. Run your script once again and make sure that the workflow progresses as intended 391 | 3. If your final results look like the end result, you just created an automated script that helps automate a workflow! 392 | 393 | # Bonus: Interactive and Independent Script 394 | We have created many different functions to help us achieve our tasks\ 395 | Can we do better to join them all into just 1 script entity?\ 396 | Can we do even better and create a script that is interactive and uses the user inputs to automate our tasks?\ 397 | Can we publish these scripts or create something that others can use? 398 | \ 399 | There are many ways to customize your scripts and workflow processing in QGIS! You may create a Processing Script that is accessible on the Toolbox (not shown here), make it a plugin, run it with Script Runner plugin, or just run it in the Python console. The great thing about flexibility is you have the freedom to do as you please to suit your needs, so practice away! 400 | 401 | #### Bonus: Creating a Main Script 402 | 1. For the more advanced coders, you might want to create a Class and declare methods instead of just defining functions, as in this workshop, we did not go in-depth into classes 403 | 2. Otherwise, finish this script that does everything with just being called once 404 | 3. Make the script interactive, and get the user inputs on file paths, algorithm parameters, etc. 405 | 4. Once you are satisfied with that script, you might even want to consider converting it into a plugin so that it can be published and used by others 406 | 407 | 408 | ## Notes and Disclaimer 409 | Note that there is no 'perfect' or 'only' solution when it comes to scripting, and as such, the scripts that were demonstrated and available in this workshop/repository are only for references and to guide you. With that said, always try to maintain good programming practices so that your code is clean, readable and easy to maintain. 410 | 411 | ## References, Resources and Additional Help 412 | * [Processing: A Python Framework for the Seamless Integration of Geoprocessing Tools in QGIS by Anita Graser](http://www.mdpi.com/2220-9964/4/4/2219/htm) 413 | * In-depth development history on Processing Framework 414 | * [Anita Graser's blog](http://anitagraser.com) 415 | * [Processing GitHub repository by Victor Olaya (developer of Processing)](https://github.com/qgis/QGIS-Processing) 416 | * [QGIS Testing Documentation](https://docs.qgis.org/testing/en/docs/) 417 | * Contains a lot of resources and documentations 418 | * Links to tutorials and textbooks like the PyQGIS Cookbook, QGIS Developers Guide 419 | * [QGIS Tutorials by Ujaval Gandhi](http://www.qgistutorials.com/en/) 420 | * Helpful step by step tutorials on many aspects of QGIS 421 | * Vast amount of resources, forums and an active and helpful community online 422 | * Special thanks to helpful developers like Anita Graser and other users on GIS Stack Exchange for answering my questions 423 | * And of course, the wonderful people at Geometa Lab, HSR 424 | 425 | ## Contact 426 | Kang Zi Jing, author and owner of this GitHub repository: zkang[at]hsr[dot]ch 427 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GeoPython Conference 2018 2 | **Processing Framework: Automating Tasks with Python** 3 | \ 4 | Homepage: https://giswiki.hsr.ch/Workshop_QGIS_Python_GeoPython_2018 5 | 6 | License of source code is GPL2, license of material is CC-BY-4.0 unless stated otherwise. 7 | 8 | # QGIS Processing Framework: Automating Tasks with Python 9 | 10 | A QGIS workshop for the GeoPython Conference 2018 11 | \ 12 | \ 13 | This repository contains a few folders for use in the GeoPython Conference 2018 and whomever is interested in learning about 14 | QGIS, its Processing Framework, as well as coding in Python. 15 | \ 16 | \ 17 | This workshop talks about the **history and conception** of the Processing framework, **how it ties in and became part of QGIS**, as well 18 | as its **features, advantages and limitations**. The workshop then continues with an **introduction to a workflow, how to 19 | complete tasks manually**, and then moving into **hands-on exercises** that teaches participants progressively on 20 | **how to complete certain tasks manually, and how to complete the same tasks with tools that Processing offers: _Graphic Modeler_, _Script_, 21 | _Batch Processing_, and more**. The workshop also covers **scripting (standalone from Processing)**, and as part of its bonus 22 | materials, **method definitions and classes**.\ 23 | \ 24 | The workshop is created with **beginners in mind**, and welcomes both seasoned programmers and newcomers as it is progressive and broken 25 | into digestable parts. 26 | \ 27 | \ 28 | **Dataset** folder contains the relevant sample data you require to perform your geospatial analysis in the workflow\ 29 | **Scripts** folder contains the model scripts that you can reference as a guide and model to help you solve the task problems\ 30 | **Workflow** folder contains the original workflow that we want to automate, in case you want to try out the tasks without Python, or 31 | if you are very new to GIS/programming and cannot keep up\ 32 | **Presentation Slides** folder contains the presentation slides used during the workshop as well as the images shown on the slides 33 | \ 34 | \ 35 | Help: In case you are stuck or lost, the folders also include a 'readme' file to guide you along.\ 36 | Error: In case of error reporting or any other issues, feel free to contact me. Contact details as follow.\ 37 | Contact: Kang Zi Jing, zkang[at]hsr[dot]ch 38 | -------------------------------------------------------------------------------- /Scripts/Master Script Model.py: -------------------------------------------------------------------------------- 1 | """ 2 | This is the suggested solution for the Processing Framework: Automating Tasks with Pythong workshop for the GeoPython Conference 2018 3 | Author: Kang Zi Jing 4 | GitHub repository: [link] 5 | 6 | This is a interactive script that takes from the users some inputs, i.e. filepath of the Environment gpkg, Autobahn gpkg, and then it does the rest without much more prompt. 7 | This source code is written with a Class definition, as it asks for a user input for the file path and then consequently carries out the rest of the methods, for better encapsulation, modularity, and reusability. If you are looking for the task by task solutions (what to type on the console, which is better for beginners), or the function definitions, check the GitHub repository again. 8 | """ 9 | 10 | """ Import data libraries """ 11 | from qgis import core 12 | from PyQt5.QtWidgets import * 13 | from qgis.utils import iface 14 | from qgis.core import QgsProject 15 | import processing 16 | 17 | class HabitatAnalyzer: 18 | """Declaring a class for code cleanliness, encapsulation and modularity. Also allows for better organization and clarity when more than an analysis needs to be performed. 19 | The following are methods that an instance of HabitatAnalyzer can call. 20 | When 'HabitatAnalyzer(iface)' is called, the iface referred to would be used to create an instance of HabitatAnalyzer with __init__() method 21 | The other methods help move the script through our workflow. They can be called in success to one another with the method run_script() but can also be called inidividually by their method names if desired""" 22 | 23 | def __init__(self, iface): 24 | self.iface = iface 25 | 26 | """The following 4 methods are just a repackage of library included GUI user-input functions. I rewrote them as class methods to shorten them and make them more readable.""" 27 | 28 | def question(self, title, content): 29 | return QMessageBox.question(iface.mainWindow(), title, content, QMessageBox.Yes, QMessageBox.No) 30 | 31 | def information(self, title, content): 32 | return QMessageBox.information(iface.mainWindow(), title, content) 33 | 34 | def fileDialog(self, title): 35 | return QFileDialog.getOpenFileName(QFileDialog(), title, "%APPDATA%") 36 | 37 | def inputDialog(self, inputType, title, content): 38 | if (inputType == 1): 39 | return QInputDialog.getText(iface.mainWindow(), title, content) 40 | if (inputType == 2): 41 | return QInputDialog.getInt(iface.mainWindow(), title, content) 42 | 43 | def welcome(self): 44 | self.information("Habitat Analyzer", "Welcome to Habitat Analyzer") 45 | return self.question("Habitat Analyzer", "Would you like to run the script?") 46 | 47 | def check_layer_exists(self, layerName): 48 | return (len(QgsProject.instance().mapLayersByName(layerName))) 49 | 50 | """The following methods are the core methods to help us move through our workflow. Should be essentially similar to the ones we used in the previous 2 scripts, just that these allow a bit more room for interactivity and user input by having altered parameters""" 51 | 52 | def load_layers(self, type): 53 | answer = QMessageBox.No 54 | while (answer == QMessageBox.No): 55 | self.information("File Select", "Select your " + type + " layer from a Geopackage") 56 | input = self.fileDialog("File Select")[0] 57 | while (input[-5:] != ".gpkg"): 58 | self.information("Invalid Geopackage", "That is not a .gpkg file! Please reselect!") 59 | input = self.fileDialog("File Select")[0] 60 | answer = self.question("Confirmation", "Is " + input + " the correct file?") 61 | if answer == QMessageBox.Yes: 62 | inputAnswer = self.inputDialog(1, "Layer Name", "Name your layer: ") 63 | layer = iface.addVectorLayer(input, "", "ogr") 64 | if ((inputAnswer[1]) == True): 65 | layer.setName(inputAnswer[0]) 66 | break 67 | self.information("Reselect", "Please select the correct " + type + " file!") 68 | 69 | def buffer_creation(self): 70 | answer = self.question("Buffer Creation", "Would you like to create a buffer?") 71 | if answer == QMessageBox.Yes: 72 | bufferNumber = self.inputDialog(2, "Buffer Creation", "How many buffers do you want to create?") 73 | for x in range(0, (bufferNumber[0])): 74 | 75 | layerInput = self.inputDialog(1, "Buffer %d" % (x+1), "Enter the name of your layer to be buffered: ") 76 | while ((layerInput[1] == True) and (len(QgsProject.instance().mapLayersByName(layerInput[0])) == 0)): 77 | self.information("Error", "There is no layer named " + layerInput[0] + "!") 78 | layerInput = self.inputDialog(1, "Buffer %d" % (x+1), "Enter the name of your layer to be buffered: ") 79 | if layerInput[1] == False: 80 | break 81 | layerName = layerInput[0] 82 | bufferDist = self.inputDialog(2, "Buffer %d" % (x+1), "Enter the distance to buffer: ")[0] 83 | param = { 'INPUT' : QgsProject.instance().mapLayersByName(layerName)[0], 'DISTANCE' : bufferDist, 'SEGMENTS' : 5, 'END_CAP_STYLE' : 0, 'JOIN_STYLE' : 0, 'MITER_LIMIT' : 2, 'DISSOLVE' : False, 'OUTPUT' : 'memory:' } 84 | bufferLayer = QgsProject.instance().addMapLayer(processing.run("qgis:buffer", param)['OUTPUT']) 85 | inputAnswer = self.inputDialog(1, "Layer Name", "Name the output buffer layer: ") 86 | if (inputAnswer[1] == True): 87 | bufferLayer.setName(inputAnswer[0]) 88 | 89 | def old_buffer_creation(self): 90 | answer = self.question("Buffer Creation", "Would you like to create a buffer?") 91 | if answer == QMessageBox.Yes: 92 | bufferNumber = self.inputDialog(2, "Buffer Creation", "How many buffers do you want to create?") 93 | print("Input selected: " + str(bufferNumber[0])) 94 | for x in range(0, (bufferNumber[0])): 95 | 96 | layerName = self.inputDialog(1, "Buffer %d" % x, "Enter the name of your layer to be buffered: ") 97 | if (layerName[1] == QMessageBox.Cancel): 98 | break 99 | while (len(QgsProject.instance().mapLayersByName(layerName[0])) == 0): 100 | if (layerName[1] == QMessageBox.Cancel): 101 | break 102 | self.information("Error", "There is no layer named " + layerName[0] + "!") 103 | layerName = self.inputDialog(1, "Buffer %d" % x, "Enter the name of your layer to be buffered: ") 104 | bufferDist = self.inputDialog(2, "Buffer %d" % x, "Enter the distance to buffer: ")[0] 105 | while (len(layerName) != 0): 106 | param = { 'INPUT' : QgsProject.instance().mapLayersByName(layerName[0])[0], 'DISTANCE' : bufferDist, 'SEGMENTS' : 5, 'END_CAP_STYLE' : 0, 'JOIN_STYLE' : 0, 'MITER_LIMIT' : 2, 'DISSOLVE' : False, 'OUTPUT' : 'memory:' } 107 | bufferLayer = QgsProject.instance().addMapLayer(processing.run("qgis:buffer", param)['OUTPUT']) 108 | inputAnswer = self.inputDialog(1, "Layer Name", "Name the output buffer layer: ") 109 | if (inputAnswer[1] == True): 110 | bufferLayer.setName(inputAnswer[0]) 111 | if (len(layerName) == 0): 112 | self.information("Error!", "The layer name you gave does not exist! Try again!") 113 | 114 | def perform_union(self): 115 | answer = self.question("Union Creation", "Would you like to union 2 layers?") 116 | if answer == QMessageBox.Yes: 117 | layer1 = self.inputDialog(1, "Layer 1", "Enter the name of your first/base layer: ") 118 | while ((layer1[1] == True) and (len(QgsProject.instance().mapLayersByName(layer1[0])) == 0)): 119 | self.information("Error", "There is no layer named " + layer1[0] + "!") 120 | layer1 = self.inputDialog(1, "Layer 1", "Enter the name of your first/base layer: ") 121 | if (layer1[1] == True): 122 | layer2 = self.inputDialog(1, "Layer 2", "Enter the name of your second/overlay layer: ") 123 | while ((layer2[1] == True) and (len(QgsProject.instance().mapLayersByName(layer2[0])) == 0)): 124 | self.information("Error", "There is no layer named " + layer2[0] + "!") 125 | layer2 = self.inputDialog(1, "Layer 2", "Enter the name of your second/overlay layer: ") 126 | if (layer2[1] == True): 127 | param = { 'INPUT' : QgsProject.instance().mapLayersByName(layer1[0])[0], 'OVERLAY' : QgsProject.instance().mapLayersByName(layer2[0])[0], 'OUTPUT' : 'memory:' } 128 | algoOutput = processing.run("qgis:union", param) 129 | unionResult = QgsProject.instance().addMapLayer(algoOutput['OUTPUT']) 130 | outputName = self.inputDialog(1, "Layer Name", "Name the output union layer: ") 131 | if (outputName[1] == True): 132 | unionResult.setName(outputName[0]) 133 | 134 | def perform_intersection(self): 135 | answer = self.question("Intersect Layers", "Would you like to intersect 2 layers?") 136 | if answer == QMessageBox.Yes: 137 | layer1 = self.inputDialog(1, "Layer 1", "Enter the name of your first/base layer: ") 138 | while ((layer1[1] == True) and (len(QgsProject.instance().mapLayersByName(layer1[0])) == 0)): 139 | self.information("Error", "There is no layer named " + layer1[0] + "!") 140 | layer1 = self.inputDialog(1, "Layer 1", "Enter the name of your first/base layer: ") 141 | if (layer1[1] == True): 142 | layer2 = self.inputDialog(1, "Layer 2", "Enter the name of your second/overlay layer: ") 143 | while ((layer2[1] == True) and (len(QgsProject.instance().mapLayersByName(layer2[0])) == 0)): 144 | self.information("Error", "There is no layer named " + layer2[0] + "!") 145 | layer2 = self.inputDialog(1, "Layer 2", "Enter the name of your second/overlay layer: ") 146 | if (layer2[1] == True): 147 | param = { 'INPUT' : QgsProject.instance().mapLayersByName(layer1[0])[0], 'OVERLAY' : QgsProject.instance().mapLayersByName(layer2[0])[0], 'INPUT_FIELDS' : [], 'OVERLAY_FIELDS' : [], 'OUTPUT' : 'memory:' } 148 | algoOutput = processing.run("qgis:intersection", param) 149 | intersectResult = QgsProject.instance().addMapLayer(algoOutput['OUTPUT']) 150 | outputName = self.inputDialog(1, "Layer Name", "Name the output intersected layer: ") 151 | if (outputName[1] == True): 152 | intersectResult.setName(outputName[0]) 153 | 154 | def query_features(self): 155 | bslash = '"' 156 | answer = self.question("Query Features", "Would you like to query any features?") 157 | if answer == QMessageBox.Yes: 158 | baseLayer = self.inputDialog(1, "Base Layer", "Enter the name of the layer to be queried: ") 159 | while ((baseLayer[1] == True) and (len(QgsProject.instance().mapLayersByName(baseLayer[0])) == 0)): 160 | self.information("Error", "There is no layer named " + baseLayer[0] + "!") 161 | baseLayer = self.inputDialog(1, "Base Layer", "Enter the name of your base layer: ") 162 | if (baseLayer[1] != False): 163 | self.information("Instructions", "The query input is sensitive, please input \" before and after your attributes, example: [" + bslash + "ffh_typ_nr" + bslash +" = 1 or " + bslash +"geschuetzt_biotop" + bslash + " = 1]") 164 | query = self.inputDialog(1, "Query", "Enter your query (input-sensitive, please type " + bslash + " before and after your attributes): ") 165 | print(query) 166 | if (query[1] == True): 167 | query = QgsExpression(query[0]) 168 | baseLayer = QgsProject.instance().mapLayersByName(baseLayer[0])[0] 169 | it = baseLayer.getFeatures(QgsFeatureRequest(query)) 170 | ids = [i.id() for i in it] 171 | baseLayer.selectByIds(ids) 172 | valuable = baseLayer.materialize(QgsFeatureRequest().setFilterFids(baseLayer.selectedFeatureIds())) 173 | QgsProject.instance().addMapLayer(valuable) 174 | outputName = self.inputDialog(1, "Output Name", "Name the output queried layer: ") 175 | if (outputName[1] == True): 176 | valuable.setName(outputName[0]) 177 | 178 | 179 | """Method to run the script in the order of the workflow.""" 180 | 181 | def run_script(iface): 182 | project = HabitatAnalyzer(iface) 183 | if (project.welcome() == QMessageBox.Yes): 184 | print("Continuing") 185 | project.load_layers("Environment") 186 | project.load_layers("Autobahn") 187 | project.buffer_creation() 188 | project.perform_union() 189 | project.perform_union() 190 | project.perform_intersection() 191 | project.query_features() 192 | print("End") 193 | else: 194 | print("Stopping") 195 | 196 | 197 | """Automatically run script""" 198 | run_script(iface) 199 | 200 | 201 | """Disclaimer: As this is a simple and rater straightforward workflow, there wasn't much error checking involved. For the more obvious loops or decision forks that lead to potential errors, I created some basic exception handling, such that the script doesn't go into a loop or crash the program. Example: giving a non .gpkg file as an input to be added (technically, you can add .shp and other similar files, but we want to encourage the use of .gpkg, thus we only allow .gpkg files to pass the check)""" -------------------------------------------------------------------------------- /Scripts/Master Script Straightforward.py: -------------------------------------------------------------------------------- 1 | """This is the master script for the GeoPython Conference 2018""" 2 | 3 | """Import some key tools""" 4 | from PyQt5.QtGui import * 5 | from PyQt5.QtWidgets import * 6 | from PyQt5.QtCore import Qt 7 | from qgis.core import QgsVectorLayer, QgsMapSettings, QgsProject, QgsExpression, QgsFeatureRequest, QgsSymbol, QgsSimpleFillSymbolLayer, QgsRendererCategory, QgsCategorizedSymbolRenderer, QgsLayerTreeNode 8 | from qgis.gui import QgsMapToolEmitPoint 9 | from qgis.gui import QgsMapTool 10 | from qgis.utils import iface 11 | from qgis import core 12 | from random import random, randrange 13 | import processing 14 | 15 | """ 16 | 1. Create project file / Show the land use 17 | a. ask for envrironment.gpkg 18 | b. set CRS and unit system 19 | c. save project (if possible) 20 | d. set symbologyExport 21 | 22 | Prompt the user of the script and have option to cancel 23 | Be more verbal about the steps that are happening 24 | Double check if inputs are correct 25 | 26 | """ 27 | """QMessageBox creates a message pop-up whereas QFileDialog creates a file selection dialog. Find out more uses and options in the documentations""" 28 | 29 | envInput = QFileDialog.getOpenFileName(QFileDialog(), "Environment Shapefile Selection", "\\svm-c113.hsr.ch\zkang\Desktop\QGIS-Steilkurs_MSE_Maerz_2017\QGIS-Steilkurs_MSE_Maerz_2017\daten_autobahn") 30 | envEnv = envInput[0] 31 | env = iface.addVectorLayer(envEnv, 'Environment', 'ogr') 32 | env.setName("Environment") 33 | 34 | """Now, change the stylization of the envrionment layer""" 35 | working_map = iface.activeLayer() 36 | renderer = working_map.renderer() 37 | symbol = renderer.symbol() 38 | symbol.setColor(QColor(0, 200, 220, 135)) 39 | symbol.setOpacity(.5) 40 | working_map.triggerRepaint() 41 | iface.layerTreeView().refreshLayerSymbology(working_map.id()) 42 | 43 | """Next, we add the line file of the Autobahn, set it to red and then create a buffer around it to represent its physical form""" 44 | atbnInput = QFileDialog.getOpenFileName(QFileDialog(), "Autobahn Shapefile Selection", "\\svm-c113.hsr.ch\zkang\Desktop\QGIS-Steilkurs_MSE_Maerz_2017\QGIS-Steilkurs_MSE_Maerz_2017\daten_autobahn") 45 | atbnAtbn = atbnInput[0] 46 | atbn = iface.addVectorLayer(atbnAtbn, 'Autobahn', 'ogr') 47 | 48 | atbn_map = iface.activeLayer() 49 | renderer = atbn_map.renderer() 50 | symbol = renderer.symbol() 51 | symbol.setColor(QColor(255, 0, 0, 255)) 52 | atbn_map.triggerRepaint() 53 | iface.layerTreeView().refreshLayerSymbology(atbn_map.id()) 54 | 55 | param = { 'INPUT' : atbn_map, 'DISTANCE' : 20, 'SEGMENTS' : 5, 'END_CAP_STYLE' : 0, 'JOIN_STYLE' : 0, 'MITER_LIMIT' : 2, 'DISSOLVE' : False, 'OUTPUT' : 'memory:' } 56 | styles = processing.run("qgis:buffer", param) 57 | autobahnSpace = QgsProject.instance().addMapLayer(styles['OUTPUT']) 58 | layer = iface.activeLayer() 59 | atbn20 = layer 60 | layer.setName("Autobahn 20") 61 | renderer = atbn20.renderer() 62 | symbol = renderer.symbol() 63 | symbol.setColor(QColor(58, 26, 52)) 64 | 65 | """Next, we add 2 more buffers, 1 100m away from the autobahn, and the other 300m away from the autobahn. These are used to illustrate that the impact of constructing an autobahn is far more than just the physical space that it uses.""" 66 | 67 | atbn_map = iface.activeLayer() 68 | param = { 'INPUT' : atbn_map, 'DISTANCE' : 100, 'SEGMENTS' : 5, 'END_CAP_STYLE' : 0, 'JOIN_STYLE' : 0, 'MITER_LIMIT' : 2, 'DISSOLVE' : False, 'OUTPUT' : 'memory:' } 69 | styles = processing.run("qgis:buffer", param) 70 | autobahnBuffer1 = QgsProject.instance().addMapLayer(styles['OUTPUT']) 71 | layer = iface.activeLayer() 72 | layer.setName("Autobahn 100") 73 | QgsProject.instance().layerTreeRoot().findLayer(layer).setItemVisibilityChecked(False) 74 | 75 | atbn_map = iface.activeLayer() 76 | param = { 'INPUT' : atbn_map, 'DISTANCE' : 200, 'SEGMENTS' : 5, 'END_CAP_STYLE' : 0, 'JOIN_STYLE' : 0, 'MITER_LIMIT' : 2, 'DISSOLVE' : False, 'OUTPUT' : 'memory:' } 77 | styles = processing.run("qgis:buffer", param) 78 | autobahnBuffer1 = QgsProject.instance().addMapLayer(styles['OUTPUT']) 79 | layer = iface.activeLayer() 80 | layer.setName("Autobahn 300") 81 | QgsProject.instance().layerTreeRoot().findLayer(layer).setItemVisibilityChecked(False) 82 | 83 | 84 | """Now that we have the 3 files buffered from the red Autobahn line file, let's perform an Union on them""" 85 | 86 | autobahn20 = QgsProject.instance().mapLayersByName("Autobahn 20")[0] 87 | autobahn100 = QgsProject.instance().mapLayersByName("Autobahn 100")[0] 88 | autobahn300 = QgsProject.instance().mapLayersByName("Autobahn 300")[0] 89 | 90 | param = { 'INPUT' : autobahn20, 'OVERLAY' : autobahn100, 'OUTPUT': 'memory:' } 91 | styles = processing.run("qgis:union", param) 92 | autobahnUnion1 = QgsProject.instance().addMapLayer(styles['OUTPUT']) 93 | impactAreaMinor = iface.activeLayer() 94 | impactAreaMinor.setName("Impact Area 1") 95 | QgsProject.instance().layerTreeRoot().findLayer(impactAreaMinor).setItemVisibilityChecked(False) 96 | 97 | 98 | impactArea1 = QgsProject.instance().mapLayersByName("Impact Area 1")[0] 99 | 100 | param = { 'INPUT' : impactArea1, 'OVERLAY' : autobahn300, 'OUTPUT': 'memory:' } 101 | styles = processing.run("qgis:union", param) 102 | autobahnUnion1 = QgsProject.instance().addMapLayer(styles['OUTPUT']) 103 | impactAreaMajor = iface.activeLayer() 104 | impactAreaMajor.setName("Impact Area") 105 | 106 | """We take the intersection of the impact area and the environment to cut off the excess parts""" 107 | param = { 'INPUT' : impactAreaMajor, 'OVERLAY' : env, 'INPUT_FIELDS' : [], 'OVERLAY_FIELDS' : [], 'OUTPUT' : 'memory:' } 108 | styles = processing.run("qgis:intersection", param) 109 | impactIntersected = QgsProject.instance().addMapLayer(styles['OUTPUT']) 110 | impactIntersected.setName("Impact Area Intersected") 111 | renderer = impactIntersected.renderer() 112 | symbol = renderer.symbol() 113 | symbol.setColor(QColor(90, 190, 150, 205)) 114 | symbol.setOpacity(.8) 115 | impactIntersected.triggerRepaint() 116 | iface.layerTreeView().refreshLayerSymbology(impactIntersected.id()) 117 | 118 | 119 | """Next, we are going to select the notable/important habitats by passing through a query on the attribute of the environment layer""" 120 | 121 | expr = QgsExpression("\"ffh_typ_nr\"=1 or \"geschuetzt_biotop\" = 1 or \"bedeutend_gruenland_typ\" = 1") 122 | it = env.getFeatures(QgsFeatureRequest(expr)) 123 | ids = [i.id() for i in it] 124 | env.selectByIds(ids) 125 | valuable = env.materialize(QgsFeatureRequest().setFilterFids(env.selectedFeatureIds())) 126 | QgsProject.instance().addMapLayer(valuable) 127 | valuable.setName("Valuable") 128 | empty = [] 129 | env.selectByIds(empty) 130 | 131 | 132 | """Now, we intersect the valuable habitats and non-valuable habitats against the impact zone to sieve out what habitats are actually affected by the construction of the autobahn""" 133 | 134 | expr2 = QgsExpression("\"ffh_typ_nr\"=1") 135 | it = valuable.getFeatures(QgsFeatureRequest(expr2)) 136 | ids = [i.id() for i in it] 137 | valuable.selectByIds(ids) 138 | valuableIntersected = valuable.materialize(QgsFeatureRequest().setFilterFids(valuable.selectedFeatureIds())) 139 | """QgsProject.instance().addMapLayer(valuableIntersected)""" 140 | param = { 'INPUT' : valuableIntersected, 'OVERLAY' : impactAreaMajor, 'INPUT_FIELDS' : [], 'OVERLAY_FIELDS' : [], 'OUTPUT' : 'memory:' } 141 | styles = processing.run("qgis:intersection", param) 142 | valuableIntersected = QgsProject.instance().addMapLayer(styles['OUTPUT']) 143 | valuableIntersected.setName("Valuable Intersected") 144 | """valuableIntersected = iface.activeLayer()""" 145 | valuable.selectByIds(empty) 146 | 147 | 148 | expr3 = QgsExpression("\"ffh_typ_nr\"=0") 149 | it = valuable.getFeatures(QgsFeatureRequest(expr3)) 150 | ids = [i.id() for i in it] 151 | valuable.selectByIds(ids) 152 | nValuableIntersected = valuable.materialize(QgsFeatureRequest().setFilterFids(valuable.selectedFeatureIds())) 153 | """QgsProject.instance().addMapLayer(nValuableIntersected)""" 154 | nValuableIntersected.setName("Non-Valuable Intersected") 155 | param = { 'INPUT' : nValuableIntersected, 'OVERLAY' : impactAreaMajor, 'INPUT_FIELDS' : [], 'OVERLAY_FIELDS' : [], 'OUTPUT' : 'memory:' } 156 | styles = processing.run("qgis:intersection", param) 157 | nValuableIntersected = QgsProject.instance().addMapLayer(styles['OUTPUT']) 158 | nValuableIntersected.setName("Non-Valuable Intersected") 159 | valuable.selectByIds(empty) 160 | 161 | 162 | """Now, we stylize the map layer by category for easy readability""" 163 | 164 | fni = valuableIntersected.fields().indexFromName('ffh_typ_text') 165 | unique_values = valuableIntersected.dataProvider().uniqueValues(fni) 166 | 167 | categories = [] 168 | count = 0 169 | iteration = 1 170 | 171 | for unique_value in unique_values: 172 | count += 1 173 | 174 | for unique_value in unique_values: 175 | symbol = QgsSymbol.defaultSymbol(layer.geometryType()) 176 | layer_style = {} 177 | increase = 256 / count 178 | layer_style['color'] = '%d, %d, %d' % (0, (256 - (iteration * (increase/2))), 0) 179 | """layer_style['color'] = '%d, %d, %d' % (randrange(0,256), randrange(0,256), randrange(0,256))""" 180 | layer_style['outline'] = '#000000' 181 | symbol_layer = QgsSimpleFillSymbolLayer.create(layer_style) 182 | 183 | if symbol_layer is not None: 184 | symbol.changeSymbolLayer(0, symbol_layer) 185 | 186 | category = QgsRendererCategory(unique_value, symbol, str(unique_value)) 187 | categories.append(category) 188 | 189 | iteration += 1 190 | 191 | renderer = QgsCategorizedSymbolRenderer('ffh_typ_text', categories) 192 | 193 | if renderer is not None: 194 | valuableIntersected.setRenderer(renderer) 195 | valuableIntersected.triggerRepaint() 196 | 197 | """We do the same for the non-valuable habitats""" 198 | 199 | fni = nValuableIntersected.fields().indexFromName('bfn_biotop_text') 200 | unique_values = nValuableIntersected.dataProvider().uniqueValues(fni) 201 | 202 | categories = [] 203 | count = 0 204 | iteration = 1 205 | 206 | for unique_value in unique_values: 207 | count += 1 208 | 209 | for unique_value in unique_values: 210 | symbol = QgsSymbol.defaultSymbol(layer.geometryType()) 211 | layer_style = {} 212 | increase = 256 / count 213 | layer_style['color'] = '%d, %d, %d' % ((210 - (iteration * (increase/2.5))), (222 - (iteration * (increase/1.25))), 0) 214 | """layer_style['color'] = '%d, %d, %d' % (randrange(0,256), randrange(0,256), randrange(0,256))""" 215 | layer_style['outline'] = '#000000' 216 | symbol_layer = QgsSimpleFillSymbolLayer.create(layer_style) 217 | 218 | if symbol_layer is not None: 219 | symbol.changeSymbolLayer(0, symbol_layer) 220 | 221 | category = QgsRendererCategory(unique_value, symbol, str(unique_value)) 222 | categories.append(category) 223 | 224 | iteration += 1 225 | 226 | renderer = QgsCategorizedSymbolRenderer('bfn_biotop_text', categories) 227 | 228 | if renderer is not None: 229 | nValuableIntersected.setRenderer(renderer) 230 | nValuableIntersected.triggerRepaint() 231 | """QgsProject.instance().removeMapLayer(valuable) 232 | QgsProject.instance().removeMapLayer(impactAreaMinor) 233 | QgsProject.instance().removeMapLayer(QgsProject.instance().mapLayersByName("Autobahn 20")[0]) 234 | QgsProject.instance().removeMapLayer(QgsProject.instance().mapLayersByName("Autobahn 100")[0]) 235 | QgsProject.instance().removeMapLayer(QgsProject.instance().mapLayersByName("Autobahn 300")[0])""" 236 | QgsProject.instance().layerTreeRoot().findLayer(impactAreaMinor).setItemVisibilityChecked(False) 237 | QgsProject.instance().layerTreeRoot().findLayer(valuable).setItemVisibilityChecked(False) 238 | QgsProject.instance().layerTreeRoot().findLayer(impactAreaMajor).setItemVisibilityChecked(False) 239 | 240 | root = QgsProject.instance().layerTreeRoot() 241 | myalayer = root.findLayer(atbn.id()) 242 | myblayer = root.findLayer(atbn20.id()) 243 | myClone2 = myblayer.clone() 244 | myClone = myalayer.clone() 245 | parent = myalayer.parent() 246 | parent.insertChildNode(0, myClone) 247 | parent.insertChildNode(1, myClone2) 248 | parent.removeChildNode(myalayer) 249 | parent.removeChildNode(myblayer) 250 | iface.mapCanvas().refresh() 251 | 252 | bmInput = QFileDialog.getOpenFileName(QFileDialog(), "Raster Basemap Selection", "\\svm-c113.hsr.ch\zkang\Desktop\QGIS-Steilkurs_MSE_Maerz_2017\QGIS-Steilkurs_MSE_Maerz_2017\daten_autobahn") 253 | bmBm = bmInput[0] 254 | bm = iface.addRasterLayer(bmBm, 'Raster Basemap') 255 | bm.setName("Basemap") 256 | bm.renderer().setOpacity(0.25) 257 | 258 | myclayer = root.findLayer(bm.id()) 259 | myClone3 = myclayer.clone() 260 | parent.insertChildNode(12, myClone3) 261 | parent.removeChildNode(myclayer) 262 | iface.mapCanvas().refresh() 263 | 264 | """ Can follow the code here: https://gis.stackexchange.com/questions/175068/apply-symbol-to-each-feature-categorized-symbol 265 | 266 | 1. Count the number of different attributes using for loop 267 | 2. 256 divide by number - that will be the increase per attribute 268 | 3. In another attribute for loop, for each attribute, the color = x + increase 269 | """ 270 | -------------------------------------------------------------------------------- /Scripts/Master Script with Info.py: -------------------------------------------------------------------------------- 1 | """This is the master script for the GeoPython Conference 2018""" 2 | 3 | """Import some key tools""" 4 | from PyQt5.QtGui import * 5 | from PyQt5.QtWidgets import * 6 | from PyQt5.QtCore import Qt 7 | from qgis.core import QgsVectorLayer, QgsMapSettings, QgsProject, QgsExpression, QgsFeatureRequest, QgsSymbol, QgsSimpleFillSymbolLayer, QgsRendererCategory, QgsCategorizedSymbolRenderer, QgsLayerTreeNode 8 | from qgis.gui import QgsMapToolEmitPoint 9 | from qgis.gui import QgsMapTool 10 | from qgis.utils import iface 11 | from qgis import core 12 | from random import random, randrange 13 | import processing 14 | 15 | """ 16 | 1. Create project file / Show the land use 17 | a. ask for envrironment.gpkg 18 | b. set CRS and unit system 19 | c. save project (if possible) 20 | d. set symbologyExport 21 | 22 | Prompt the user of the script and have option to cancel 23 | Be more verbal about the steps that are happening 24 | Double check if inputs are correct 25 | 26 | """ 27 | """QMessageBox creates a message pop-up whereas QFileDialog creates a file selection dialog. Find out more uses and options in the documentations""" 28 | 29 | runScript = QMessageBox.question(iface.mainWindow(), 'Habitat Analyzer', 'Do you want to run the script?', QMessageBox.Yes, QMessageBox.No) 30 | 31 | if runScript == QMessageBox.Yes: 32 | QMessageBox.information(iface.mainWindow(), "Habitat Analyzer", "Welcome to Habitat Analyzer") 33 | 34 | QMessageBox.information(iface.mainWindow(), "File Select", "Select your Environment layer from a Geopackage") 35 | envInput = QFileDialog.getOpenFileName(QFileDialog(), "Environment Layer Selection", "\\svm-c113.hsr.ch\zkang\Desktop\QGIS-Steilkurs_MSE_Maerz_2017\QGIS-Steilkurs_MSE_Maerz_2017\daten_autobahn") 36 | envPath = envInput[0] 37 | env = iface.addVectorLayer(envPath, 'Environment', 'ogr') 38 | env.setName("Environment") 39 | 40 | """Setting CRS of Environment layer""" 41 | my_crs = core.QgsCoordinateReferenceSystem(31467, core.QgsCoordinateReferenceSystem.EpsgCrsId) 42 | QgsMapSettings().setDestinationCrs(my_crs) 43 | iface.mapCanvas().refresh() 44 | 45 | """Now, change the stylization of the envrionment layer""" 46 | QMessageBox.information(iface.mainWindow(), "", "Setting the layer color to RGB 200, 220, 135 and opacity to 0.5") 47 | envL = iface.activeLayer() 48 | renderer = envL.renderer() 49 | symbol = renderer.symbol() 50 | symbol.setColor(QColor(0, 200, 220, 135)) 51 | symbol.setOpacity(.5) 52 | envL.triggerRepaint() 53 | iface.layerTreeView().refreshLayerSymbology(envL.id()) 54 | 55 | """Next, we add the line file of the Autobahn, set it to red and then create a buffer around it to represent its physical form""" 56 | QMessageBox.information(iface.mainWindow(), "File Select", "Select your Autobahn layer from a Geopackage") 57 | atbnInput = QFileDialog.getOpenFileName(QFileDialog(), "Autobahn Layer Selection", "\\svm-c113.hsr.ch\zkang\Desktop\QGIS-Steilkurs_MSE_Maerz_2017\QGIS-Steilkurs_MSE_Maerz_2017\daten_autobahn") 58 | atbnPath = atbnInput[0] 59 | atbn = iface.addVectorLayer(atbnPath, 'Autobahn', 'ogr') 60 | 61 | """Now, change the stylization of the autobahn layer""" 62 | QMessageBox.information(iface.mainWindow(), "", "Setting the color of the Autobahn line to Red") 63 | atbnL = iface.activeLayer() 64 | renderer = atbnL.renderer() 65 | symbol = renderer.symbol() 66 | symbol.setColor(QColor(255, 0, 0, 255)) 67 | atbnL.triggerRepaint() 68 | iface.layerTreeView().refreshLayerSymbology(atbnL.id()) 69 | 70 | 71 | """Now, we run the QGIS algorithm, buffer, on the Autobahn to recreate an actual physical representation of the autobahn with 20m radius""" 72 | QMessageBox.information(iface.mainWindow(), "Autobahn 20", "Creating Buffer 1: Actual physical representation of Autobahn") 73 | param = { 'INPUT' : atbnL, 'DISTANCE' : 20, 'SEGMENTS' : 5, 'END_CAP_STYLE' : 0, 'JOIN_STYLE' : 0, 'MITER_LIMIT' : 2, 'DISSOLVE' : False, 'OUTPUT' : 'memory:' } 74 | styles = processing.run("qgis:buffer", param) 75 | autobahnSpace = QgsProject.instance().addMapLayer(styles['OUTPUT']) 76 | layer = iface.activeLayer() 77 | atbn20 = layer 78 | layer.setName("Autobahn 20") 79 | QMessageBox.information(iface.mainWindow(), "", "Setting color of the Autobahn 20 to RGB 58, 26, 52") 80 | renderer = atbn20.renderer() 81 | symbol = renderer.symbol() 82 | symbol.setColor(QColor(58, 26, 52)) 83 | 84 | """Next, we add 2 more buffers, 1 100m away from the autobahn, and the other 300m away from the autobahn. These are used to illustrate that the impact of constructing an autobahn is far more than just the physical space that it uses.""" 85 | 86 | QMessageBox.information(iface.mainWindow(), "Autobahn 100", "Creating Buffer 2: 100m radius from Autobahn 20") 87 | atbn_map = iface.activeLayer() 88 | param = { 'INPUT' : atbn_map, 'DISTANCE' : 100, 'SEGMENTS' : 5, 'END_CAP_STYLE' : 0, 'JOIN_STYLE' : 0, 'MITER_LIMIT' : 2, 'DISSOLVE' : False, 'OUTPUT' : 'memory:' } 89 | styles = processing.run("qgis:buffer", param) 90 | autobahnBuffer1 = QgsProject.instance().addMapLayer(styles['OUTPUT']) 91 | layer = iface.activeLayer() 92 | layer.setName("Autobahn 100") 93 | QMessageBox.information(iface.mainWindow(), "", "Unchecking Autobahn 100 as it is an intermediate file") 94 | QgsProject.instance().layerTreeRoot().findLayer(layer).setItemVisibilityChecked(False) 95 | 96 | QMessageBox.information(iface.mainWindow(), "Autobahn 300", "Creating Buffer 3: 200m radius from Autobahn 100") 97 | atbn_map = iface.activeLayer() 98 | param = { 'INPUT' : atbn_map, 'DISTANCE' : 200, 'SEGMENTS' : 5, 'END_CAP_STYLE' : 0, 'JOIN_STYLE' : 0, 'MITER_LIMIT' : 2, 'DISSOLVE' : False, 'OUTPUT' : 'memory:' } 99 | styles = processing.run("qgis:buffer", param) 100 | autobahnBuffer1 = QgsProject.instance().addMapLayer(styles['OUTPUT']) 101 | layer = iface.activeLayer() 102 | layer.setName("Autobahn 300") 103 | QMessageBox.information(iface.mainWindow(), "", "Unchecking Autobahn 300 as it is an intermediate file") 104 | QgsProject.instance().layerTreeRoot().findLayer(layer).setItemVisibilityChecked(False) 105 | 106 | 107 | """Now that we have the 3 files buffered from the red Autobahn line file, let's perform an Union on them""" 108 | 109 | QMessageBox.information(iface.mainWindow(), "Impact Area", "Performing Unions on the 3 Buffers to aggregate total impact area of Autobahn construction") 110 | autobahn20 = QgsProject.instance().mapLayersByName("Autobahn 20")[0] 111 | autobahn100 = QgsProject.instance().mapLayersByName("Autobahn 100")[0] 112 | autobahn300 = QgsProject.instance().mapLayersByName("Autobahn 300")[0] 113 | 114 | QMessageBox.information(iface.mainWindow(), "Impact Area Minor", "Creating first union of inner buffers") 115 | param = { 'INPUT' : autobahn20, 'OVERLAY' : autobahn100, 'OUTPUT': 'memory:' } 116 | styles = processing.run("qgis:union", param) 117 | autobahnUnion1 = QgsProject.instance().addMapLayer(styles['OUTPUT']) 118 | impactAreaMinor = iface.activeLayer() 119 | impactAreaMinor.setName("Impact Area 1") 120 | QMessageBox.information(iface.mainWindow(), "", "Unchecking Impact Area Minor as it is an intermediate file") 121 | QgsProject.instance().layerTreeRoot().findLayer(impactAreaMinor).setItemVisibilityChecked(False) 122 | 123 | 124 | impactArea1 = QgsProject.instance().mapLayersByName("Impact Area 1")[0] 125 | QMessageBox.information(iface.mainWindow(), "Impact Area Major", "Creating the total aggregated impact area") 126 | param = { 'INPUT' : impactArea1, 'OVERLAY' : autobahn300, 'OUTPUT': 'memory:' } 127 | styles = processing.run("qgis:union", param) 128 | autobahnUnion1 = QgsProject.instance().addMapLayer(styles['OUTPUT']) 129 | impactAreaMajor = iface.activeLayer() 130 | impactAreaMajor.setName("Impact Area") 131 | 132 | """We take the intersection of the impact area and the environment to cut off the excess parts""" 133 | QMessageBox.information(iface.mainWindow(), "Impacted Habitats", "Running an intersection between the impact area and environment area to determine the habitats within the impact") 134 | param = { 'INPUT' : impactAreaMajor, 'OVERLAY' : env, 'INPUT_FIELDS' : [], 'OVERLAY_FIELDS' : [], 'OUTPUT' : 'memory:' } 135 | styles = processing.run("qgis:intersection", param) 136 | impactIntersected = QgsProject.instance().addMapLayer(styles['OUTPUT']) 137 | impactIntersected.setName("Impact Area Intersected") 138 | QMessageBox.information(iface.mainWindow(), "", "Setting the color of the impacted habitats to RGB 90, 190, 150 and opacity to 0.8") 139 | renderer = impactIntersected.renderer() 140 | symbol = renderer.symbol() 141 | symbol.setColor(QColor(90, 190, 150, 205)) 142 | symbol.setOpacity(.8) 143 | impactIntersected.triggerRepaint() 144 | iface.layerTreeView().refreshLayerSymbology(impactIntersected.id()) 145 | 146 | 147 | """Next, we are going to select the notable/important habitats by passing through a query on the attribute of the environment layer""" 148 | 149 | QMessageBox.information(iface.mainWindow(), "", "Selecting protected and valuable habitats using a query") 150 | expr = QgsExpression("\"ffh_typ_nr\"=1 or \"geschuetzt_biotop\" = 1 or \"bedeutend_gruenland_typ\" = 1") 151 | it = env.getFeatures(QgsFeatureRequest(expr)) 152 | ids = [i.id() for i in it] 153 | env.selectByIds(ids) 154 | valuable = env.materialize(QgsFeatureRequest().setFilterFids(env.selectedFeatureIds())) 155 | QgsProject.instance().addMapLayer(valuable) 156 | valuable.setName("Valuable") 157 | empty = [] 158 | env.selectByIds(empty) 159 | 160 | 161 | """Now, we intersect the valuable habitats and non-valuable habitats against the impact zone to sieve out what habitats are actually affected by the construction of the autobahn""" 162 | 163 | QMessageBox.information(iface.mainWindow(), "", "Intersecting the selected features against impact area to get the valuable habitats that are impacted") 164 | expr2 = QgsExpression("\"ffh_typ_nr\"=1") 165 | it = valuable.getFeatures(QgsFeatureRequest(expr2)) 166 | ids = [i.id() for i in it] 167 | valuable.selectByIds(ids) 168 | valuableIntersected = valuable.materialize(QgsFeatureRequest().setFilterFids(valuable.selectedFeatureIds())) 169 | """QgsProject.instance().addMapLayer(valuableIntersected)""" 170 | param = { 'INPUT' : valuableIntersected, 'OVERLAY' : impactAreaMajor, 'INPUT_FIELDS' : [], 'OVERLAY_FIELDS' : [], 'OUTPUT' : 'memory:' } 171 | styles = processing.run("qgis:intersection", param) 172 | valuableIntersected = QgsProject.instance().addMapLayer(styles['OUTPUT']) 173 | valuableIntersected.setName("Valuable Intersected") 174 | """valuableIntersected = iface.activeLayer()""" 175 | valuable.selectByIds(empty) 176 | 177 | 178 | QMessageBox.information(iface.mainWindow(), "", "Doing the same for the non valuable habitats") 179 | expr3 = QgsExpression("\"ffh_typ_nr\"=0") 180 | it = valuable.getFeatures(QgsFeatureRequest(expr3)) 181 | ids = [i.id() for i in it] 182 | valuable.selectByIds(ids) 183 | nValuableIntersected = valuable.materialize(QgsFeatureRequest().setFilterFids(valuable.selectedFeatureIds())) 184 | """QgsProject.instance().addMapLayer(nValuableIntersected)""" 185 | nValuableIntersected.setName("Non-Valuable Intersected") 186 | param = { 'INPUT' : nValuableIntersected, 'OVERLAY' : impactAreaMajor, 'INPUT_FIELDS' : [], 'OVERLAY_FIELDS' : [], 'OUTPUT' : 'memory:' } 187 | styles = processing.run("qgis:intersection", param) 188 | nValuableIntersected = QgsProject.instance().addMapLayer(styles['OUTPUT']) 189 | nValuableIntersected.setName("Non-Valuable Intersected") 190 | valuable.selectByIds(empty) 191 | 192 | 193 | """Now, we stylize the map layer by category for easy readability""" 194 | 195 | QMessageBox.information(iface.mainWindow(), "", "Now we stylize the map for better readability") 196 | QMessageBox.information(iface.mainWindow(), "", "We categorize by color: valuable habitats in green and non-valuable habitats in brown") 197 | QMessageBox.information(iface.mainWindow(), "", "Different types of habitats are categorized by a different shade or gradient of color") 198 | fni = valuableIntersected.fields().indexFromName('ffh_typ_text') 199 | unique_values = valuableIntersected.dataProvider().uniqueValues(fni) 200 | 201 | categories = [] 202 | count = 0 203 | iteration = 1 204 | 205 | for unique_value in unique_values: 206 | count += 1 207 | 208 | for unique_value in unique_values: 209 | symbol = QgsSymbol.defaultSymbol(layer.geometryType()) 210 | layer_style = {} 211 | increase = 256 / count 212 | layer_style['color'] = '%d, %d, %d' % (0, (256 - (iteration * (increase/2))), 0) 213 | """layer_style['color'] = '%d, %d, %d' % (randrange(0,256), randrange(0,256), randrange(0,256))""" 214 | layer_style['outline'] = '#000000' 215 | symbol_layer = QgsSimpleFillSymbolLayer.create(layer_style) 216 | 217 | if symbol_layer is not None: 218 | symbol.changeSymbolLayer(0, symbol_layer) 219 | 220 | category = QgsRendererCategory(unique_value, symbol, str(unique_value)) 221 | categories.append(category) 222 | 223 | iteration += 1 224 | 225 | renderer = QgsCategorizedSymbolRenderer('ffh_typ_text', categories) 226 | 227 | if renderer is not None: 228 | valuableIntersected.setRenderer(renderer) 229 | valuableIntersected.triggerRepaint() 230 | 231 | """We do the same for the non-valuable habitats""" 232 | 233 | fni = nValuableIntersected.fields().indexFromName('bfn_biotop_text') 234 | unique_values = nValuableIntersected.dataProvider().uniqueValues(fni) 235 | 236 | categories = [] 237 | count = 0 238 | iteration = 1 239 | 240 | for unique_value in unique_values: 241 | count += 1 242 | 243 | for unique_value in unique_values: 244 | symbol = QgsSymbol.defaultSymbol(layer.geometryType()) 245 | layer_style = {} 246 | increase = 256 / count 247 | layer_style['color'] = '%d, %d, %d' % ((210 - (iteration * (increase/2.5))), (222 - (iteration * (increase/1.25))), 0) 248 | """layer_style['color'] = '%d, %d, %d' % (randrange(0,256), randrange(0,256), randrange(0,256))""" 249 | layer_style['outline'] = '#000000' 250 | symbol_layer = QgsSimpleFillSymbolLayer.create(layer_style) 251 | 252 | if symbol_layer is not None: 253 | symbol.changeSymbolLayer(0, symbol_layer) 254 | 255 | category = QgsRendererCategory(unique_value, symbol, str(unique_value)) 256 | categories.append(category) 257 | 258 | iteration += 1 259 | 260 | renderer = QgsCategorizedSymbolRenderer('bfn_biotop_text', categories) 261 | 262 | if renderer is not None: 263 | nValuableIntersected.setRenderer(renderer) 264 | nValuableIntersected.triggerRepaint() 265 | """QgsProject.instance().removeMapLayer(valuable) 266 | QgsProject.instance().removeMapLayer(impactAreaMinor) 267 | QgsProject.instance().removeMapLayer(QgsProject.instance().mapLayersByName("Autobahn 20")[0]) 268 | QgsProject.instance().removeMapLayer(QgsProject.instance().mapLayersByName("Autobahn 100")[0]) 269 | QgsProject.instance().removeMapLayer(QgsProject.instance().mapLayersByName("Autobahn 300")[0])""" 270 | QgsProject.instance().layerTreeRoot().findLayer(impactAreaMinor).setItemVisibilityChecked(False) 271 | QgsProject.instance().layerTreeRoot().findLayer(valuable).setItemVisibilityChecked(False) 272 | QgsProject.instance().layerTreeRoot().findLayer(impactAreaMajor).setItemVisibilityChecked(False) 273 | 274 | QMessageBox.information(iface.mainWindow(), "", "Now that the stylization is completed, we rearrange the layers for better visibility") 275 | 276 | root = QgsProject.instance().layerTreeRoot() 277 | myalayer = root.findLayer(atbn.id()) 278 | myblayer = root.findLayer(atbn20.id()) 279 | myClone2 = myblayer.clone() 280 | myClone = myalayer.clone() 281 | parent = myalayer.parent() 282 | parent.insertChildNode(0, myClone) 283 | parent.insertChildNode(1, myClone2) 284 | parent.removeChildNode(myalayer) 285 | parent.removeChildNode(myblayer) 286 | iface.mapCanvas().refresh() 287 | 288 | QMessageBox.information(iface.mainWindow(), "", "Lastly, we add a Basemap if it exists") 289 | 290 | reply = QMessageBox.question(iface.mainWindow(), 'Raster Basemap', 'Do you have a raster basemap?', QMessageBox.Yes, QMessageBox.No) 291 | 292 | if reply == QMessageBox.Yes: 293 | QMessageBox.information(iface.mainWindow(), "File Select", "Select your raster basemap file") 294 | bmInput = QFileDialog.getOpenFileName(QFileDialog(), "Raster Basemap Selection", "\\svm-c113.hsr.ch\zkang\Desktop\QGIS-Steilkurs_MSE_Maerz_2017\QGIS-Steilkurs_MSE_Maerz_2017\daten_autobahn") 295 | bmBm = bmInput[0] 296 | bm = iface.addRasterLayer(bmBm, 'Raster Basemap') 297 | bm.setName("Basemap") 298 | bm.renderer().setOpacity(0.25) 299 | 300 | myclayer = root.findLayer(bm.id()) 301 | myClone3 = myclayer.clone() 302 | parent.insertChildNode(12, myClone3) 303 | parent.removeChildNode(myclayer) 304 | iface.mapCanvas().refresh() 305 | 306 | """ Can follow the code here: https://gis.stackexchange.com/questions/175068/apply-symbol-to-each-feature-categorized-symbol 307 | 308 | 1. Count the number of different attributes using for loop 309 | 2. 256 divide by number - that will be the increase per attribute 310 | 3. In another attribute for loop, for each attribute, the color = x + increase 311 | """ 312 | else: 313 | QMessageBox.information(iface.mainWindow(), "End", "Script will not run") 314 | 315 | -------------------------------------------------------------------------------- /Scripts/Models/Workshop Graphic Modeler Example.model3: -------------------------------------------------------------------------------- 1 | 2 | 22 | 23 | 31 | 32 | 37 | 38 | 43 | 44 | 49 | 50 | 55 | 56 | 61 | 62 | 67 | 68 | 69 | 70 | 88 | 89 | 97 | 98 | 103 | 104 | 109 | 110 | 116 | 117 | 122 | 123 | 128 | 129 | 134 | 135 | 136 | 137 | 155 | 156 | 164 | 165 | 170 | 171 | 176 | 177 | 183 | 184 | 189 | 190 | 195 | 196 | 201 | 202 | 203 | 204 | 222 | 223 | 232 | 233 | 238 | 239 | 244 | 245 | 250 | 251 | 252 | 253 | 271 | 272 | 281 | 282 | 288 | 289 | 290 | 291 | 309 | 310 | 319 | 320 | 326 | 327 | 328 | 329 | 330 | 338 | 345 | 349 | 356 | 367 | 378 | 389 | 400 | 411 | 422 | 423 | 430 | 436 | 437 | 438 | -------------------------------------------------------------------------------- /Scripts/README.md: -------------------------------------------------------------------------------- 1 | These scripts are the suggested solutions for the problem tasks. 2 | As mentioned and emphasized, there is no "one way" to do things when it comes to programming and coding. 3 | What matters is the computational thinking and logic we apply to create our source code such that it is: 4 | * Clean 5 | * Easy to maintain 6 | * Error free 7 | * Reusable 8 | 9 | In other words, focus more on the good practices of programming, and use these scripts as guidelines or models to try to emulate. 10 | You may end up with a different code and even better code, so feel free and dare to try out your own code and create your own features. 11 | There is also a vast community out there who would be willing and happy to help if you come into an obstacle or if you do not know how to solve a certain difficult question. 12 | At the same time, always remember to Google and try to figure out on your own before asking another person! 13 | 14 | Have fun programming and godspeed! 15 | 16 | |Script Name|Description| 17 | |---|---| 18 | |Tasks 1-4.2|Reference script for Tasks 1 to 4.2| 19 | |Task 5|Reference script for Task 5 - rewriting into functions definition| 20 | |Master Script Straightforward|Reference script that automates the entire workflow (like a Processing algorithm) 21 | |Master Script with Info|Reference script that gives information on what is happening| 22 | |Master Script Model|Reference script that is interactive, and has basic exception and error handling| 23 | -------------------------------------------------------------------------------- /Scripts/Task 5.py: -------------------------------------------------------------------------------- 1 | """ 2 | This is the suggested solution for the Processing Framework: Automating Tasks with Pythong workshop for the GeoPython Conference 2018 3 | Author: Kang Zi Jing 4 | GitHub repository: [link] 5 | 6 | This are the function definitions that follow the problem tasks. To use: run this script on your QGIS Python console and call the functions with the respective parameters. 7 | This source code is written without a Class definition as I believe that not more than 1 Environment layer would be analyzed per project, but if needed, feel free to edit the code to be a Class definition for better encapsulation and modularity. If you are looking for the Master Script, Interactable Script, or the straightforward solutions (what to type on the console, which is better for beginners), check the GitHub repository again. 8 | If you are experienced in Python or other programming languages and familiar with methon calls and definition, feel free to skip this script and go into the bonus scripts. 9 | """ 10 | 11 | """ Import data libraries """ 12 | from qgis import core 13 | from PyQt5.QtWidgets import * 14 | from qgis.utils import iface 15 | from qgis.core import QgsProject 16 | import processing 17 | 18 | 19 | """ Quality of Life Function(s) 20 | Defined to make life easier than calling the entire method of a class """ 21 | def get_layer(layerName): 22 | """ returns the vector layer object of the name in string pass as parameter 23 | basically a short version to write QgsProject.instance().mapLayersByName(layerName)[0] """ 24 | return QgsProject.instance().mapLayersByName(layerName)[0] 25 | 26 | 27 | """ Task 1. Adding Geopackage as Layers into QGIS """ 28 | 29 | 30 | def add_layer(layerName): 31 | layerPath = QFileDialog.getOpenFileName(QFileDialog(), "Geopackage Select", "C:\\")[0] 32 | layer = iface.addVectorLayer(layerPath, "", "ogr") 33 | layer.setName(layerName) 34 | """ Note that after this function is called, you have to assign the layers to variables so that you can pass them into the next few functions. Of course, there are ways to go about doing this so that you do not need to repetitively assign new layers, but we shall not explore that in this script. """ 35 | 36 | 37 | """ Task 2. Adding Buffers """ 38 | 39 | 40 | def add_buffer(vLayer, dist, outputName): 41 | param = { 'INPUT' : vLayer, 'DISTANCE' : dist, 'SEGMENTS' : 5, 'END_CAP_STYLE' : 0, 'JOIN_STYLE' : 0, 'MITER_LIMIT' : 2, 'DISSOLVE' : False, 'OUTPUT' : 'memory:' } 42 | algoOutput = processing.run("qgis:buffer", param) 43 | bufferResult = QgsProject.instance().addMapLayer(algoOutput['OUTPUT']) 44 | bufferResult.setName(outputName) 45 | """ Once again, as this script's aim is to explore the modularity of functions, there's no automation in parsing through the resultant layers. For that, you can check the following script. 46 | 47 | Another way which may simplify things than declaring every variable is to parse the results like this: 48 | 49 | atbn = get_layer("Autobahn") 50 | add_buffer(atbn, 20, "Autobahn 20") 51 | add_buffer(get_layer("Autobahn 20")[0], 100, "Autobahn 100") 52 | add_buffer(get_layer("Autobahn 100"), 200, "Autobahn 300") 53 | """ 54 | 55 | """ Task 3. Performing Unions """ 56 | 57 | 58 | def perform_union(layer1, layer2, outputName): 59 | param = { 'INPUT' : layer1, 'OVERLAY' : layer2, 'OUTPUT' : 'memory:' } 60 | algoOutput = processing.run("qgis:union", param) 61 | unionResult = QgsProject.instance().addMapLayer(algoOutput['OUTPUT']) 62 | unionResult.setName(outputName) 63 | 64 | 65 | """ Task 4. Calling Intersections """ 66 | 67 | 68 | def call_intersection(layer, overlay, outputName): 69 | param = param = { 'INPUT' : layer, 'OVERLAY' : overlay, 'INPUT_FIELDS' : [], 'OVERLAY_FIELDS' : [], 'OUTPUT' : 'memory:' } 70 | intxnResult = QgsProject.instance().addMapLayer(processing.run("qgis:intersection", param)['OUTPUT']) 71 | intxnResult.setName(outputName) 72 | 73 | 74 | """ Task 5. Query Features """ 75 | 76 | 77 | def query_features(layer, expr, outputName): 78 | querySelect = layer.getFeatures(QgsFeatureRequest(expr)) 79 | ids = [i.id() for i in layer.getFeatures(QgsFeatureRequest(expr))] 80 | layer.selectByIds(ids) 81 | result = layer.materialize(QgsFeatureRequest().setFilterFids(layer.selectedFeatureIds())) 82 | QgsProject.instance().addMapLayer(result) 83 | layer.selectByIds([]) 84 | result.setName(outputName) -------------------------------------------------------------------------------- /Scripts/Tasks 1-4.2.py: -------------------------------------------------------------------------------- 1 | """ 2 | This is the solution for the Processing Framework: Automating Tasks with Pythong workshop for the GeoPython Conference 2018 3 | Author: Kang Zi Jing 4 | GitHub repository: [link] 5 | 6 | This covers the solution up till Task 4.2. These lines of code are what you should enter into your QGIS Python Console to follow the problem tasks. 7 | This source code is intentionally written with bad practice and non-reusability and non-modularity as it seeks to help entry-level Python users to learn the language. If you are looking for the Master Script, Interactable Script, or solution to Task 4.2 onwards which uses more reusable code through defining method calls, check the GitHub repository again. 8 | If you are experienced in Python or other programming languages and familiar with methon calls and definition, feel free to skip this script. 9 | """ 10 | 11 | """ Import data libraries """ 12 | from qgis import core 13 | from PyQt5.QtWidgets import * 14 | from qgis.utils import iface 15 | from qgis.core import QgsProject 16 | import processing 17 | 18 | 19 | """ Task 1. Adding Geopackae as Layers into QGIS """ 20 | 21 | 22 | """ 1.2. Creating a Dialog Box to ask for User Input on File to Add """ 23 | envPath = QFileDialog.getOpenFileName(QFileDialog(), "Environment Layer Select", "C:\\")[0] 24 | 25 | """ 1.3. Adding Vector Layers into QGIS """ 26 | env = iface.addVectorLayer(envPath, "", "ogr") 27 | env.setName("Environment") 28 | 29 | atbnPath = QFileDialog.getOpenFileName(QFileDialog(), "Autobahn Layer Select", "C:\\")[0] 30 | atbn = iface.addVectorLayer(atbnPath, "", "ogr") 31 | atbn.setName("Autobahn") 32 | 33 | 34 | """ Task 2. Adding Buffers to Autobahn Layer """ 35 | 36 | 37 | """ 2.3. Creating a Buffer with a Standalone Script """ 38 | """ This line can be ignored since we previously already declared \atbn\ but if not, we can declare it again with: 39 | atbn = QgsProject.instance().mapLayersByName("Autobahn")[0] """ 40 | param = { 'INPUT' : atbn, 'DISTANCE' : 20, 'SEGMENTS' : 5, 'END_CAP_STYLE' : 0, 'JOIN_STYLE' : 0, 'MITER_LIMIT' : 2, 'DISSOLVE' : False, 'OUTPUT' : 'memory:' } 41 | algoOutput = processing.run("qgis:buffer", param) 42 | autobahn20 = QgsProject.instance().addMapLayer(algoOutput['OUTPUT']) 43 | autobahn20.setName("Autobahn 20") 44 | 45 | """ 2.4. Creating 2 more Buffers """ 46 | param = { 'INPUT' : autobahn20, 'DISTANCE' : 100, 'SEGMENTS' : 5, 'END_CAP_STYLE' : 0, 'JOIN_STYLE' : 0, 'MITER_LIMIT' : 2, 'DISSOLVE' : False, 'OUTPUT' : 'memory:' } 47 | algoOutput = processing.run("qgis:buffer", param) 48 | autobahn100 = QgsProject.instance().addMapLayer(algoOutput['OUTPUT']) 49 | autobahn100.setName("Autobahn 100") 50 | 51 | param = { 'INPUT' : autobahn100, 'DISTANCE' : 200, 'SEGMENTS' : 5, 'END_CAP_STYLE' : 0, 'JOIN_STYLE' : 0, 'MITER_LIMIT' : 2, 'DISSOLVE' : False, 'OUTPUT' : 'memory:' } 52 | algoOutput = processing.run("qgis:buffer", param) 53 | autobahn300 = QgsProject.instance().addMapLayer(algoOutput['OUTPUT']) 54 | autobahn300.setName("Autobahn 300") 55 | 56 | 57 | """ Task 3. Performing Union on the Buffer Areas """ 58 | param = { 'INPUT' : autobahn20, 'OVERLAY' : autobahn100, 'OUTPUT' : 'memory:' } 59 | algoOutput = processing.run("qgis:union", param) 60 | innerImpactArea = QgsProject.instance().addMapLayer(algoOutput['OUTPUT']) 61 | innerImpactArea.setName("Inner Impact Area") 62 | 63 | param = { 'INPUT' : innerImpactArea, 'OVERLAY' : autobahn300, 'OUTPUT' : 'memory:' } 64 | algoOutput = processing.run("qgis:union", param) 65 | impactArea = QgsProject.instance().addMapLayer(algoOutput['OUTPUT']) 66 | impactArea.setName("Impact Area") 67 | 68 | 69 | """ Task 4. Refining Code """ 70 | 71 | 72 | """ 4.1. Performing Intersection on Environment and Impact Area """ 73 | def intersect_layers(layer1, layer2, outputName): 74 | param = param = { 'INPUT' : layer1, 'OVERLAY' : layer2, 'INPUT_FIELDS' : [], 'OVERLAY_FIELDS' : [], 'OUTPUT' : 'memory:' } 75 | intxnOp = QgsProject.instance().addMapLayer(processing.run("qgis:intersection", param)['OUTPUT']) 76 | intxnOp.setName(outputName) 77 | 78 | """ This is an example of defining a method or function. This encourages the reusability of code as it can work with any form of inputs and outputs you can specify. All you need to do is to declare your variables before passing them through the method as \layer1\, 'layer2\ and \outputName\, which are the parameters you defined for the method. """ 79 | 80 | outputName = "Intersected" 81 | 82 | intersect_layers(env, impactArea, outputName) 83 | intersected = QgsProject.instance().mapLayersByName(outputName) 84 | 85 | """ 4.2. Method Definition for Previous Tasks 86 | The suggested solution for Task 4.2 onwards would be in another script as we try to refine and clean up the code by introducing reusability and modularity though method definitions """ -------------------------------------------------------------------------------- /Workflow/Highway Construction Workflow English.doc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geometalab/GeoPythonConf2018-QGIS-Processing-Workshop/c74abbd235a9795c8dacbec10259c6fd07f27f6f/Workflow/Highway Construction Workflow English.doc -------------------------------------------------------------------------------- /Workflow/readme.md: -------------------------------------------------------------------------------- 1 | This folder contains the workflow file. 2 | 3 | The workflow is based on Task 6 of the course “Introduction to GIS and Digital Cartography” by Claas Leiner, University of Kassel, 2010. 4 | Adapted to a class for Vector Analysis by Stefan Keller, FS 2017 5 | Translated and adapted for QGIS 3.0 and the GeoPython Conference by Kang Zi Jing, 2018 6 | -------------------------------------------------------------------------------- /Workshop Slides/GeoPython Conference 2018.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geometalab/GeoPythonConf2018-QGIS-Processing-Workshop/c74abbd235a9795c8dacbec10259c6fd07f27f6f/Workshop Slides/GeoPython Conference 2018.pdf -------------------------------------------------------------------------------- /Workshop Slides/Slides Images/Buffer Log Example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geometalab/GeoPythonConf2018-QGIS-Processing-Workshop/c74abbd235a9795c8dacbec10259c6fd07f27f6f/Workshop Slides/Slides Images/Buffer Log Example.png -------------------------------------------------------------------------------- /Workshop Slides/Slides Images/Graphic Modeler Example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geometalab/GeoPythonConf2018-QGIS-Processing-Workshop/c74abbd235a9795c8dacbec10259c6fd07f27f6f/Workshop Slides/Slides Images/Graphic Modeler Example.png -------------------------------------------------------------------------------- /Workshop Slides/Slides Images/Graphic Modeler.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geometalab/GeoPythonConf2018-QGIS-Processing-Workshop/c74abbd235a9795c8dacbec10259c6fd07f27f6f/Workshop Slides/Slides Images/Graphic Modeler.png -------------------------------------------------------------------------------- /Workshop Slides/Slides Images/History Tool.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geometalab/GeoPythonConf2018-QGIS-Processing-Workshop/c74abbd235a9795c8dacbec10259c6fd07f27f6f/Workshop Slides/Slides Images/History Tool.png -------------------------------------------------------------------------------- /Workshop Slides/Slides Images/Processing Toolbox.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geometalab/GeoPythonConf2018-QGIS-Processing-Workshop/c74abbd235a9795c8dacbec10259c6fd07f27f6f/Workshop Slides/Slides Images/Processing Toolbox.png -------------------------------------------------------------------------------- /Workshop Slides/Slides Images/Scripts Tool 2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geometalab/GeoPythonConf2018-QGIS-Processing-Workshop/c74abbd235a9795c8dacbec10259c6fd07f27f6f/Workshop Slides/Slides Images/Scripts Tool 2.png -------------------------------------------------------------------------------- /Workshop Slides/Slides Images/Scripts Tool.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geometalab/GeoPythonConf2018-QGIS-Processing-Workshop/c74abbd235a9795c8dacbec10259c6fd07f27f6f/Workshop Slides/Slides Images/Scripts Tool.png -------------------------------------------------------------------------------- /Workshop Slides/Slides Images/Task 1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geometalab/GeoPythonConf2018-QGIS-Processing-Workshop/c74abbd235a9795c8dacbec10259c6fd07f27f6f/Workshop Slides/Slides Images/Task 1.png -------------------------------------------------------------------------------- /Workshop Slides/Slides Images/Task 3 Example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geometalab/GeoPythonConf2018-QGIS-Processing-Workshop/c74abbd235a9795c8dacbec10259c6fd07f27f6f/Workshop Slides/Slides Images/Task 3 Example.png -------------------------------------------------------------------------------- /Workshop Slides/Slides Images/Task 3.1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geometalab/GeoPythonConf2018-QGIS-Processing-Workshop/c74abbd235a9795c8dacbec10259c6fd07f27f6f/Workshop Slides/Slides Images/Task 3.1.png -------------------------------------------------------------------------------- /Workshop Slides/Slides Images/Task 3.2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geometalab/GeoPythonConf2018-QGIS-Processing-Workshop/c74abbd235a9795c8dacbec10259c6fd07f27f6f/Workshop Slides/Slides Images/Task 3.2.png -------------------------------------------------------------------------------- /Workshop Slides/Slides Images/Task 4 Example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geometalab/GeoPythonConf2018-QGIS-Processing-Workshop/c74abbd235a9795c8dacbec10259c6fd07f27f6f/Workshop Slides/Slides Images/Task 4 Example.png -------------------------------------------------------------------------------- /Workshop Slides/Slides Images/Task 4.1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geometalab/GeoPythonConf2018-QGIS-Processing-Workshop/c74abbd235a9795c8dacbec10259c6fd07f27f6f/Workshop Slides/Slides Images/Task 4.1.png -------------------------------------------------------------------------------- /Workshop Slides/Slides Images/Task 4.2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geometalab/GeoPythonConf2018-QGIS-Processing-Workshop/c74abbd235a9795c8dacbec10259c6fd07f27f6f/Workshop Slides/Slides Images/Task 4.2.png -------------------------------------------------------------------------------- /Workshop Slides/Slides Images/Task 5.1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geometalab/GeoPythonConf2018-QGIS-Processing-Workshop/c74abbd235a9795c8dacbec10259c6fd07f27f6f/Workshop Slides/Slides Images/Task 5.1.png -------------------------------------------------------------------------------- /Workshop Slides/Slides Images/Task 5.2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geometalab/GeoPythonConf2018-QGIS-Processing-Workshop/c74abbd235a9795c8dacbec10259c6fd07f27f6f/Workshop Slides/Slides Images/Task 5.2.png -------------------------------------------------------------------------------- /Workshop Slides/Slides Images/Task 6.1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geometalab/GeoPythonConf2018-QGIS-Processing-Workshop/c74abbd235a9795c8dacbec10259c6fd07f27f6f/Workshop Slides/Slides Images/Task 6.1.png -------------------------------------------------------------------------------- /Workshop Slides/Slides Images/Task 6.2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geometalab/GeoPythonConf2018-QGIS-Processing-Workshop/c74abbd235a9795c8dacbec10259c6fd07f27f6f/Workshop Slides/Slides Images/Task 6.2.png -------------------------------------------------------------------------------- /Workshop Slides/Slides Images/Task 7.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geometalab/GeoPythonConf2018-QGIS-Processing-Workshop/c74abbd235a9795c8dacbec10259c6fd07f27f6f/Workshop Slides/Slides Images/Task 7.png -------------------------------------------------------------------------------- /Workshop Slides/Slides Images/readme: -------------------------------------------------------------------------------- 1 | Images used in the workshop slides 2 | -------------------------------------------------------------------------------- /Workshop Slides/readme.md: -------------------------------------------------------------------------------- 1 | This folder contains the slides (and images in the slides) as presented on the workshop 2 | --------------------------------------------------------------------------------