Related Plugins and Tags

QGIS Planet

Remote debugging QGIS plugins using PyCharm

Wow it's been a long time since I posted anything here....but I'm back with another (hopefully) useful howto. Over the last six months or so I have made a rather dramatic shift away from using VIM as my primary development environment for everything to using IDE's for my python development work. I spent the first 4 or so of those months using Eclipse PyDev which is excellent but has certain issues, particularly from a QGIS context. Most of the issues relate to my not being able to get it to reliably recognise the QGIS API after adding the QGIS python directories to the package search path and the lack of decent refactoring tools. In my java programming days of yore, I used to love the refactoring tools that Eclipse provided, but unfortunately these are not carried through to PyDev.

Lately I have been using PyCharm which is a dedicated python IDE also written in Java (ironic). I'm not going to attempt to review all of PyCharm here (Guido van Rossum already did that but bear in mind the review is two years old and the software has surely advanced a lot since then). I will say there are two things that I find not as pleasant to use in PyCharm (compared to PyDev) - its PyLint and PEP8 checkers. In the projects I work on we follow PEP8 very strictly and not having a proper integrated tool for this is a real PITA. There are work arounds however so it is not a lost cause, but it would be nice if the developers took this a little more seriously:

On the other hand, I simply do not see the value of highlighting PEP 8 violations in the editor, especially in the middle of code modifications. We'd rather spend our time implementing inspections that report actual problems with the code, and not formatting nit-picks. - Dmitry Jemerov

One other big downside to PyCharm is that it is not open source software which goes against the grain somewhat. They do however provide free licensing to those using it for bona fide open source development work, so don't let the price tag deter you if you are planning to use if for a FOSS project.

Read on to see how I use PyCharm for QGIS development...

PyCharm for QGIS remote debugging

Why use PyCharm? Well it happens to be a really nice platform for QGIS python / python plugin development. For this article I am going to focus on the steps needed to remote debug python scripts / plugins running inside QGIS. The process is conceptually the same as remote debugging using Eclipse/PyDev - which I have blogged about previously. I am going to start with the assumption that you have your PyCharm set up and your plugin basics in place and now you are at the point where you wish to debug your software while it is running in QGIS. Let me prefix this by saying that I very seldom need to use this technique since our code is heavily tested (by means of a python test suite) so in most cases I can just debug a particular test directly without needing to remotely attach to a python process in QGIS. So the first thing you need to do is set up a python debug server (provided as part of PyCharm). To do this,  choose edit configurations from the task list:

Create a new run configuration

Next click on the little '+' icon and choose python remote debug:

image1

Set the following options:

  • Local host name: localhost
  • Port: 53100

Note that you can use any high port that you like (assuming it is unused).

You will notice that on the dialog it gives you some handy hints as to what needs to be inserted into your code in order to enable the trace point.

Creating the debug server run configuration

The next thing you need to do is add a couple of lines to the module that you wish to debug (this is also described in the above dialog). First, in your imports add this:

from pydev import pydevd

And then in the place where you wish execution to halt, add this line:

pydevd.settrace('192.168.1.62',
                port=53100,
                stdoutToServer=True,
                stderrToServer=True)

You can also try using 'localhost' instead of your IP address.

The last thing you need to have in place before you can test is pydevd needs to be in your PYTHONPATH in the context of the running plugin. In my case I simply extracted the pydevd egg supplied in the root of the PyCharm installation into my plugin directory:

cp ~/apps/pycharm-2.5.2/pycharm-debug.egg .
unzip pycharm-debug.egg

There are a number of other ways you could do this, for example by changing your code to add the pydev directory into sys.path.

Ok now you are all set. One thing to remember is that the settrace line is just the initial breakpoint - you can set additional breakpoints in your code using normal PyCharm debugging techniques. Now launch your PyCharm debug server configuration by clicking the little run icon next to it (highlighted in red below):

Start the debug server

After this you will see some output like this in the PyCharm run panel:

Starting debug server at port 53100
Waiting for connection...

Next fire up your copy of QGIS and open the plugin that will trigger your settrace. When the trace point is hit, PyCharm will enter debug mode and highlight the trace line in blue like this:

PyCharm debugging a remote process

Now you can step through your code, inspect variables and generally have a productive time understanding your code. I'll hopefully post a follow up article on how to set up PyCharm for QGIS development in the future! Happy hacking!

Installing PostGIS 2.0 on ubuntu

PostGIS 2.0 is out and the awesomness continues! You can install PostGIS 2.0 on Ubuntu using packages which is exactly what I am going to show you here. Read on for details on how to get up and running and do your first simple raster analysis! Note: You should make good backups first!   Before we... Read more »

Quick Tip: Build the latest QGIS nightly build as a standalone installer for Windows

I’m running a training course next week and will be basing it on the nightly build of QGIS, so I wanted to quickly build an installer for use on the course. I simply ran these commands (starting in a checkout of the Quantum GIS source code). sudo apt-get install nsis cd ms-windows/osgeo4w ./creatensis.pl qgis-dev cd... Read more »

Report back from the QGIS hackfest in Lyon, April 2012

Its been two weeks now since I returned from the QGIS Hackfest in Lyond, France, but I haven’t had the time to write up my experiences yet….until now. Read on for more! It was the first time that the hackfest (which is a twice yearly event) has been held in France. Lyon is a lovely... Read more »

Specifying options in the QGIS GDAL Tools

You probably looked at the GDAL Tools (under the raster menu in QGIS) and  blissfully ignored that ‘Creation Options’ panel that appears near the bottom of some dialogs. This is definately a power user feature, but a very handy one. In this quick article I will show you how to compress the rasters you create... Read more »

A python layer action to open a wikipedia page in QGIS

One of the really cool features in QGIS that doesn’t get much press is the ability to run actions based on a feature selection. Under 1.7.4 this works by using the identify tool and then choosing an action from the action list in the identified feature(s) attributes. A new improvement in QGIS master (and should... Read more »

Another bash one-liner – load all natural earth layers into postgis in one go

Having a good world dataset is kind of essential for most GIS users to have as a standard reference dataset, give context to maps and so on. Anita Graser’s recent blog post about the Natural Earth Data project added another nice dataset to my world dataset collection. The Natural Earth Data set (I got the... Read more »

Comparing and browsing previous git states

Here is a quick handy tip if you are using GIT and want to be able to quickly diff or checkout the code base from a week, month etc. ago. You can use the git reflog to do this: @{1.hour.ago} @{1.minute.ago} @{1.hour.ago} @{1.day.ago} @{yesterday} @{1.week.ago} @{1.month.ago} @{1.year.ago} So for example to enter a detached state... Read more »

A good quality world borders dataset

Some time ago I spent at least a day trying to find a good quality, free world political borders and coastlines dataset. Each product I found had some limitation – incomplete coverage or poor resolution. Today by happenstance a client pointed me to quite a good one. The site hosting the dataset is www.gadm.org. These folks... Read more »

Contrast and cartography – gdal_lightner

If you work with raster data in GIS you straddle a kind of wierd world where you deal with imagery but you cannot really manipulate the imagery as you would say with the GIMP or Photoshop. Conversely, if you ever tried to open a large GIS raster dataset with the GIMP you may have noticed... Read more »

Publishing multiple projects with QGIS Server

You know the drill right? You just made a beautiful map for your boss using QGIS Server. Then he walks into your office and says ‘Kiepie, I need another one in a different CRS’. Your heart drops in your chest and your jaw drops to the desk. You can’t do that using QGIS without publishing... Read more »

Simple binary raster reclassification in QGIS

The Raster Calculator in QGIS allows you to run any expression on a raster or collection of rasters. While it is definitely useful, exactly how to phrase your expression in order to reclassify a raster is not always clear. Let’s say you have a raster with values between 0 and 255, and you want everything [...]

Creating coloured rasters with GDAL

One of the most popular posts on my blog ever is my article about creating GDAL hillshades: ‘A workflow for creating beautiful relief shaded DEMS using GDAL‘. In the techniques outlined in the aforementioned article, colours are assigned across a continuum to and superimposed on top of a hillshaded model. The GDAL tools in QGIS [...]

Creating coloured rasters with GDAL

One of the most popular posts on my blog ever is my article about creating GDAL hillshades: 'A workflow for creating beautiful relief shaded DEMS using GDAL'. In the techniques outlined in the aforementioned article, colours are assigned across a continuum to and superimposed on top of a hillshaded model. The GDAL tools in QGIS have come along nicely thanks to the work of Guiseppe Sucameli - to the point that you can pretty much do the workflow from the aforementioned article within the QGIS gui environment now (barring some simple text file editing activities).

Sometimes one wants to simply assign arbitrary colours to pixel values of a raster to create a colour map. You can do this with QGIS, but the results are not persistent in the dataset, which I needed because I wanted to create my own colour map and then merge that raster with a shaded relief model. There was one extra requirement I had - I wanted to create my colour map based on polygonal areas at the beginning of my workflow. In this article I describe how I went about creating a hillshaded relief model using a polygonal overlay to define my height classes. I'm also going to show the mis-steps I took to give you a more realistic view of the process of doing such work. Read on for details...

Rasterizing the vector layer

My polygon vector file represents five height classes stored in an attribute called 'minhoyde':

0
500
1000
1500
2000

So to make a raster from this polygon layer, I used the Raster -> Conversion -> Rasterize command in QGIS to create and run this command:

gdal_rasterize -a minhoyde -ts 59620 74579 -l hoyde /tmp/hoyde.shp /tmp/hoyde.tif

This process took rather a long time - as you can see I was generating a fairly large raster and the dataset had a lot of complex polygons to process. If I was smart at that point I would have added these options to the rasterize command before running it:

-co COMPRESS=DEFLATE -co PREDICTOR=2 -co ZLEVEL=9 -ot Int16

The first three options would have made for a more optimally compressed file (see Rudi's previous article on this). The last option asks GDAL to output a 16bit integer file - as it turned out, the default in the absence of this is to generate a Float64 file which is massive. Since I missed that step the first go around (and consequently landed up with a 34G file), I used the gdal_translate tool (Raster -> Conversion -> Translate in QGIS) to do this as a separate step:

gdal_translate -of GTiff -co COMPRESS=DEFLATE -co PREDICTOR=2 -co ZLEVEL=9 -ot Int16  hoyde.tif hoyde2.tif

After doing this my output file shrunk to a much more managable 18mb.

Refining the rasterization process

After loading up the layer in QGIS, I realised I made two important mistakes:

  1. I could have saved my output file as type Byte, possibly resulting in an even smaller dataset.
  2. I should have specified a nodata value (255 would have been a good choice given point 1 above).

This is a normal part of iterative development work - I was trying to create a new workflow and making a few wrong turns is inevitable. So here was the complete revised gdal_rasterize command which I ran:

gdal_rasterize -of GTiff -co COMPRESS=DEFLATE -co PREDICTOR=2 -co ZLEVEL=9 \
  -ot Byte  -a_nodata 255 -a minhoyde -ts 59620 74579 -l hoyde /tmp/hoyde.shp /tmp/hoyde.tif

The first interesting thing I noticed when generating the raster was that the output size was no different from the Int16 version I created earlier. Also, you may have been worried reading the above about how gdal would map data values ranging from 0-2000 onto a Byte data set (which should only support pixel values from 0-255). Well take a look at this gdalinfo snippet:

Band 1 Block=59620x1 Type=Byte, ColorInterp=Gray
  Min=0.000 Max=2000.000
  Minimum=0.000, Maximum=2000.000, Mean=59.377, StdDev=208.406
  NoData Value=255
  Metadata:
    STATISTICS_MAXIMUM=2000
    STATISTICS_MEAN=59.377337101373
    STATISTICS_MINIMUM=0
    STATISTICS_STDDEV=208.40576721446

you can see that gdal still shows the correct range of values event though it is a byte dataset. If you open the file we have produced in QGIS, it will look something like this:

Our rasterized polygon layer (click for larger image)

Now if we wanted to we could assign a colour pallette to it in QGIS by setting theLayer -> Properties -> Symbology Tab -> Colour Map option to 'ColourMap' and then defining a colour for each unique value on the ColourMap tab. To illustrate, I have done this to replicate the look I am aiming for when I generate my colours layer in the next step.

Assigning a colour map to our rasterized polygons in QGIS (click for larger image)

When you assign a colour map in QGIS, other applications are not aware of this colour mapping, so what we are aiming to do in this tutorial is to embed the colour map into the image using GDAL, which I show in the next step.

Generating a colour relief map

The next step in the process was to assign colours to the rasterized polygon map. To do this, I basically treat the rasterized polygon layer as if it was a DEM and use the gdaldem colour-relief tool to assign colours to it. Before I could do this, I needed to understand the values that had been assigned for the different height classes during the rasterization process above. Doing this was a simple matter of opening my 'hoyde' dataset (the rasterized polygon layer created above) in QGIS and clicking around until I had identified the various unique values the dataset contains. In the process I generated a little table like this in  text editor:

#HoydeRaster HoydeVector
#0                        0
#244                   500
#232                   1000
#220                   1500
#208                   2000

Now that I know which pixel values represent which heights, I can assign colour values (which were supplied by my client) to each height class by creating a colour lookup file that looks like this (saved as colours.txt):

0 255 242 175
244 235 210 134
232 211 187 131
220 168 163 135
208 255 255 255

The first column is the pixel value and the subsequent columns represent RGB values. Good now everything is in place and I can generate my coloured raster using Raster -> Analysis -> Dem from withing QGIS:

Generating our colours layer using gdaldem color-relief (click for larger image)

Or run from the command line:

gdaldem color-relief /home/web/utno/qgis-web-client/data/hoyde.tif \
 /home/web/utno/qgis-web-client/data/colours.txt \
 /home/web/utno/qgis-web-client/data/colours.tif \
-alpha -of GTiff -co COMPRESS=DEFLATE -co PREDICTOR=2 -co ZLEVEL=9

After this command ran, I had a new tif image called 'colours.tif' - which we can then use as a basis for hsv_merge.py.

Merging the shade model and the colour model

The last step in the process is to merge the colour model with our hillshade. This process is the same as described in my previous article - basically you need to download the hsv_merge.py script and run it from the command line) like this:

hsv_merge.py colours.tif norge_hillshade_shpclip.tif colour_relief.tif

Afterwards you should have a generated file called colour_relief.tif which is a composite of the hillshade and the colour map. Here is what it looked like for me when I was done. I put a few vector layers over the top for extra credits :-)

Our rasterized vector layer merged with the hillshade (click for larger image)

Managing the output file size

Although we are pretty much done with our workflow, it would be worth your while to try to optimise the output file size a little (in my case the output above was 17GB). Firstly the image we created is an RGB image - but it is a good condidate for conversion to a palletted image using the gdal 'rgb2pct.py' application. Also we could try adding some compression options to the created pct file to make it smaller still. In QGIS you can do this using Raster -> Conversion -> RGB to PCT and filling in the dialog as shown in my example below:

Converting an RGB to Palletted Image (click for larger image)

Or on the command line:

rgb2pct.py colour_relief.tif colour_relief_pct.tif

That reduced my file down from 17GB to 4.2GB. As a final step I used gdal_translate to compress the tif (once again, see Rudi's previous article on what these options mean).

gdal_translate -of GTiff -co COMPRESS=DEFLATE -co PREDICTOR=2 -co ZLEVEL=9 colour_relief_pct.tif colour_relief_pct_compress.tif

This resulted in a file size of  324MB - much more acceptible. Unfortunately that wasn't quite the end of the story for this job. As I mentioned, doing this kind of work is a lot about trial and error. In this case converting the RBG image to a PCT caused the resulting images to have quite a grainy appearance.

Artifacts in palletted image mean that despite the smaller file size I wont use it (click for larger image)

I actually quite liked it as it looks a bit 'arty' but on the sum of it, the smooth tones of the original colour chaded DEM looked better to me so I used the translate step above directly on the original to compress it (forgoing the reduced colour pallette).

Compressing the output image (click for larger image)

Or from the command line (I've added a few more options to the command line version below, dropping the alpha channel):

gdal_translate -of GTiff -b 1 -b 2 -b 3 -co COMPRESS=DEFLATE \
-co PREDICTOR=2 -co ZLEVEL=9 colour_relief.tif colour_relief_compress.tif

This resulted in a file size of  1024MB with a much better fidelity to the original. For performance reasons, you will probably want to forgo disk space a little and build pyramids / overviews for the final raster too. A final step you may want to do is to apply a Mask to the output layer - which is left as an exercise to the reader - I've described the process also quite well in my original article. Note that you can now do the masking procedure from within QGIS using the raster tools using gdalwarp with the cutline option.

Conclusion

There is no excuse for having an ugly looking map on your FOSSGIS desktop :-) GDAL and QGIS give you all the tools you need to make something beautiful and to be flexible about how you produce it. I'm not quite done with my workflow yet as I actually intend to merge other thematic layers (landuse in particular) into the colour shaded map so that I can have a single raster backdrop which depicts both landuse and height classes. But hopefully the above procedure will give you some ideas about alternative ways in which to generate shading classes for your hillshade / dem. For example you could use flood risk polygons, demographic data or other polygonal datasets you have kicking around to colour your hillshade with.

Producing a raster backdrop in this way can offer some nice rendering performance gains and help you to simplify your projects. Ultimately this work is going to be published on the web so I am trying to speed things up a little and also work around a banding issue in QGIS's print composer when you work with semi-transparent raster data.

Addendum

One extra step that I performed that may be worth a mention was to use gdal sieve to remove 'salt and pepper' effect that was caused by small tranparent pixels being introduced between the polygons in the rasterization process. Example usage:

gdal_sieve.py -st 2 -of GTiff /home/web/utno/qgis-web-client/data/mask2.tif \
 /home/web/utno/qgis-web-client/data/mask3.tif

Quick Git tip: blast from the past

This has been happening to me often lately: “Rats, this function is broken when I try to do XYZ. But why? I know it worked last week before I started messing around with it. I wasn’t testing the currently broken aspect of it in the interim, though, and I can’t remember what it looked like [...]

Vector transparency plugin for QGIS

Yesterday I wrote a new little plugin for QGIS. It is available here: http://plugins.qgis.org/plugins/VectorTransparency/ or if you prefer to get it from GIT then here: https://github.com/timlinux/VectorTransparency. You can also get the plugin by adding the new QGIS official repository (which will be available by default from QGIS 1.8 onwards) to your repository list: http://plugins.qgis.org/plugins/plugins.xml The plugin is very [...]

Remote debugging QGIS python plugins with PyDev

In two previous articles (one one using Eclipse to build QGIS, and the other on using Eclipse as a Django development platform), I mentioned I would delve a little into using the Eclipse environment as a platform for QGIS Plugin Development. In particular we are interested in using Eclipse as a remote debugging platform. What [...]

Upgrading a database to PostGIS 2

Recently I needed the function ST_Split for various and sundry reasons, only to discover that I couldn’t use it in my database. The reason was that ST_Split is a new function introduced in Postgis 2.0, and the database was still in 1.5.3. Obviously, time for an upgrade. I began following the upgrade process, which I’ll [...]

A nice QGIS tutorial by Lex Berman

Lex Berman from Harvard just dropped me a nice email with a link to an interactive QGIS tutorial he has created. The tutorial is one of the nicest I have seen – each section is detailed with text, screenshots and howto videos.  I thought I would make a quick post about it here so the [...]

A nice QGIS tutorial by Lex Berman

Lex Berman from Harvard just dropped me a nice email with a link to aninteractive QGIS tutorial he has created. The tutorial is one of the nicest I have seen - each section is detailed with text, screenshots and howto videos.  I thought I would make a quick post about it here so the rest of the world can enjoy it too!

Lex's cool online tutorial (click to visit the site)

Back to Top

Sustaining Members