Friday, 10 August 2012

PostGIS and NAD27 coordinate transformations gotcha

I have not yet seen any PostGIS documentation explaining details of NAD27 transformation.
This is a hughe PostGIS pitfall so keep reading!

PostGIS relies on Proj4 library to perform coordinate transformations.
Accurate data transformation to and from North American Datum 1927 (NAD27) requires an appropriate datum grid shift file. Datum grid shift files usually are not part of standard proj4 library, on Linux freely distributable grid files are usually part of package proj-data or proj-nad depending on platform.
The problem is that PostGIS does not use files from the common proj4 data folder (on Ubuntu  /usr/share/proj).
A copy of all shift files must be placed in $POSTGRES_HOME/contrib/postgis/proj folder.
You can also find download links to additional grid shift files for various countries on proj4 website: http://trac.osgeo.org/proj/

This is a hughe pitfall because PostGIS will give no warning about missing grid files, function ST_Transform() will silently fall back to using much simpler calculations and therefore introduce transformation inaccuracies. If you are working with surveying data then this is crucial!

As soon as grid files are placed in proj folder PostGIS will quietly start taking advantage of them. Some tweaking might be required if you are working with other country datums. Here is some basic explanation of how Proj4 nadgrids work:
http://trac.osgeo.org/proj/wiki/GenParms#nadgrids-GridBasedDatumAdjustments


Ubuntu Quirks

Default Keyboard Layout

I had installed Latvian keyboard and my Ubuntu/Kubuntu and could not revert to English (UK) no matter what I did. Terminals like Alt-F2 would still be running Latvian locale. This command helped me to wipe out original settings and reinstall keyboard layout:
sudo dpkg-reconfigure keyboard-configuration

Overlay Scrollbars

I hate overlay scrollbars which were introduced in Ubuntu 11.04. Gmail has them. They are just silly. They are invisible when inactive and if you have a long document it's very difficult to hit the scrollbar right. So much pissing around just to scroll something! This command helped me to roll back to classic scrollbar:

sudo echo "export LIBOVERLAY_SCROLLBAR=0">/etc/X11/Xsession.d/80overlayscrollbars

Wednesday, 8 August 2012

Skincare for climbers

My friend recently asked me a question:
"What is you suggestion for skin pain in climbing? Every time I climb, my finger skin get scaly and brittle so that it starts to become unbearable to keep a hold for longer than a couple of seconds. I always have to stop climbing because of this shit and not because I'm pumped or tired."

Here is what you can do...

Making your finger skin tough

You will have to gradually grow and toughen your finger skin by climbing regularly for 2 to 4 weeks. This requires 2-4 sessions per week. 
During this time you should spend most of the time on easy-ish problems. This is about getting some mileage under your belt. Therefore climbing routes would be the best but short and frequent boulder sessions will do too.
At the end of this period you will acquire essential calluses and your fingertips will desensitize and therefore will be more resistant to pain.

During the session

If you want your skin to last and become tougher then do plenty of easy (for you) problems with varied holds.
Certainly warm up, get your fingers warm before doing hard stuff. Warm fingers are essential for feeling the holds better and applying just the right amount of force.
If your fingertips are sore then try climbing problems with slopers or pinches, simply avoid fingery and sharp stuff. Choose different style problem that does not hurt and work on mileage, endurance or something else.
Try to take holds as static and accurate as you can, be smooth and fluid. Let your body and muscle do the work, not the fingers! Don't slap for holds and avoid sliding off. Try not to overgrip or overcrimp holds!

When pain has arrived and is almost unbearable

Instead of doing long problems you can move on to working one particular hard move that might not be hard on fingers but imposes different kind of challenge (splits, core strength, balance etc).

Take care and stay healthy

Always stop climbing before you damage your fingertips permanently. Watch out for those red spots on your fingertips, that's a bad sign! Stop right there.
Use "Climb On" and/or some nourishing hand cream after the climb.
Buy and drink fish oil capsules - those help your nails/hair and skin to grow.

Maintenance

Don't forget to climb at least 2 times a week to maintain thickness and in-sensitiveness of your finger skin!


Good luck my friend!

Monday, 2 July 2012

GDAL usage examples

Some examples of how to use GDAL utility.

Georeference an image:
gdalwarp -te 385300 254100 385400 254200 in.tif out.tif

Export JPEG with RGB channels:
gdal_translate -ot byte -of JPEG -expand rgb in.tif rgb_out.jpg

Force to create TFW for this JPEG file (now it is georeferenced), although previous example also created TFW file by default:
gdal_translate -ot byte -of JPEG -expand rgb -co TFW=YES in.tif jpeg_with_tfw_out.jpg

Correct georeferenced tif by modifying coordinate information:
gdal_translate -a_ullr 385300 254200 385400 254100 -ot byte -of GTiff -co TFW=YES -co NBITS=1 -co COMPRESS=LZW in.tif out.tif

Export regular geotiff (this is a large file):
gdal_translate -ot byte -of GTiff -expand rgb in.tif expanded_geotiff_out.tif

Create LZW copressed geotiff:
gdal_translate -ot byte -of GTiff -co COMPRESS=LZW in.tif compressed_geotiff_out.tif

Export LZW compressed and 1 bit geotiff:
gdal_translate -ot byte -of GTiff -co NBITS=1 -co COMPRESS=LZW in.tif one_bit_geotiff_out.tif

ZLEVEL=9 - set compression level for DEFLATE:
gdal_translate -ot byte -of GTiff -co NBITS=1 -co COMPRESS=DEFLATE -co ZLEVEL=9 in.tif gtiff_with_custom_compress_out.tif

Tiled tiff file:
gdal_translate -ot byte -of GTiff -co NBITS=1 -co COMPRESS=DEFLATE -co ZLEVEL=9 -co TILED=YES in.tif tiled_geotiff_out.tif

Friday, 29 June 2012

Geodesy

Coordinate Reference System (CRS)

A coordinate reference system  is a coor-dinate system which is referenced to the earth. CRS is one part of SRS. 

Spatial Reference System (SRS)

A reference system that defines coordinate reference system, datum using ellipsoid and either a geocentric, geographic or projection coordinate system.


Geographic Coordinate System (GCS)

A geographic coordinate system (GCS) uses a three-dimensional spherical surface to define locations on the earth. A GCS is often incorrectly called a datum, but a datum is only one part of a GCS. A GCS includes an angular unit of measure, a prime meridian, and a datum (based on a spheroid).

Geoid

Geoid is gravitational surface of the earth which approximetes mean sea level.

Ellipsoid

Ellipsoid is locally best fitting elliptic 3D approximation of the earth's surface.

In geodesy only 2 axis (in equatorial radii?) are considered:
  • semi-major axis (a)
  • semi-minor axis (b)
In geodesy though ellipsoid is quite often described with these two paramters:
  • semi-major axis (a)
  • inverse flattening 1/f where f is a ratio of:
    f = (semi-major - semi-minor)/semi-major axis )
the third axis (c or Z) is ignored.

Spheroid

Spheroid  is a type of ellipsoid where semi-minor axis = sami-major axis (a =b).
Oblate spheroid is a spheorid where c < a, the Earth is an oblate spheroid.

Geodetic Datums

A geodetic datum defines the position and orientation of the reference ellipsoid relative to the centre of the earth, and the meridian used as zero longitude – the prime meridian. 

In short, datum is the shift of a spheroid, it is a point where spheroid touches the surface of the earth. Each spheroid has several datums.


Geodetic datum transformations include:
  • shifts: dX, dY, dZ
  • scaling
  • rotations: X, Y, Z

Spatial Reference System usually has:

  • SRS name
  • unit type
  • mapping projection parameters:
    • projection name
    • latitude of origin
    • central meridian
    • scale factor
    • false easting
    • false northing
  • geographic CRS parameters:
    • CRS name
    • datum name
    • Pprime meridian related info:
      • name
      • longitude
    • spheroid related info:
      • name
      • semi-major axis
      • semi-minor axis
      • inverse flattening


Tuesday, 5 October 2010

How to aggregate arrays into an array in PostgreSQL

I had to aggregate a bunch of text into a nested array using PostgreSQL 8.3.x but I found no existing solution. Creating this aggregate function worked for me.

First, create function for concatenating two arrays:


CREATE OR REPLACE FUNCTION array_to_array_cat(anyarray, anyarray)
RETURNS anyarray AS
$BODY$
select $1 || $2;
$BODY$
LANGUAGE sql IMMUTABLE



Then create aggregate function that is based on array concatenation function:


CREATE AGGREGATE array_to_array_agg(anyarray) (
SFUNC = array_to_array_cat,
STYPE = anyarray
);



Now, let's test it.
Array concatenation function:


SELECT array_to_array_cat(ARRAY[[1,2,3]], ARRAY[[7,8,9]]); --"{{1,2,3},{7,8,9}}"

SELECT array_to_array_cat(ARRAY[['foo','bar']], ARRAY[['ice','cream']]); --"{{foo,bar},{ice,cream}}"


Aggregate arrays from a column in a nested array from 'mytable':


SELECT array_to_array_agg(ARRAY[[col_a::varchar, col_b::varchar, col_c::varchar, col_d::varchar]])
FROM mytable;



Might return something like:
"{{c.1270,1270,SAC,"Description of SAC"},{1672,1672,HTR,"Description of HTR"}}"

N.B. This will work only if nested arrays have equal number of elements!

Tuesday, 10 August 2010

How to convert an array to a table?

This little function can explode array item into a table item

CREATE OR REPLACE FUNCTION explode_array(in_array anyarray)
RETURNS SETOF anyelement AS
$BODY$
select ($1)[s] from generate_series(1,array_upper($1, 1)) as s;
$BODY$
LANGUAGE 'sql' IMMUTABLE
COST 100
ROWS 1000;


Example use:

=> select explode_array(array[1,2,3]);
explode_array
---------------
1
2
3
(3 rows)

ALTER TABLE ADD COLUMN IF NOT EXISTS OR ADD COLUMN WITH incremental suffix IF EXISTS

A generic way to add a new column in PostgreSQL 8.3 from plpgsql by incrementing column suffix in a case when column already exists.

DECLARE
query TEXT :='';
suffix INTEGER :=0;
recs INTEGER :=0;
BEGIN

LOOP
suffix = suffix + 1;
EXECUTE 'SELECT count(*) FROM information_schema.columns
WHERE table_schema||$$.$$||table_name = $$'||mytablename||'$$
AND column_name = $$mycolumn'||suffix||'$$' INTO recs;
RAISE INFO 'recs %!', recs;
IF recs = 0 THEN
EXECUTE 'ALTER TABLE '||tablename||' ADD COLUMN class'||suffix||' INTEGER';
RAISE INFO 'Column mycolumn% was added!', suffix;
EXIT;
END IF;
END LOOP;

Saturday, 28 November 2009

Funny clouds

Can you see Britain in these clouds?

Google Wave

Yes, I do think that Google Wave will take over the world...
Once mature it will be a fantastic tool!
https://wave.google.com

Wednesday, 25 November 2009

Meklē ĢIS/kartogrāfa darbu Lielbritānijā?

Ja meklējat ĢIS/kartogrāfa darbu Lielbritānijā, tad vislabākais darba sludinājumu resurss, manuprāt, ir GIS-JOBS liste, kurai var piereģistrēties iekš http://www.jiscmail.ac.uk
Šeit būs jāpiereģistrē savs e-pasts un jāseko uz e-pastu izsūtītajiem sludinājumiem ik dienas, kur
atrodami darbi gan caur aģentūrām, gan no iespējamajiem darba devējiem 'pa tiešo'.

Atšķirībā no Latvijas...
Lielbritānijā, piesakoties uz darbu, ir pieņemts iesniegt ne tikai CV, bet arī 'covering letter', kas ir tāda kā motivācijas vēstule par un ap to, kāpēc jūs būtu tas labākais kandidāts konkrētajam darbam.
Otrkārt, būs nepieciešamas divas atskausmes no iepriekšējiem darba devējiem vai citiem 'labiem ļaudīm'. Atsauksmes (references) vajadzēs tad un tikai tad, ja jau tiksiet pieņemts konrētajā darbā. Tādēļ iekš CV beigās raksta "References available upon request" un savus atsauksmju devējus netraumē, kamēr nav konkrēta vajadzība...
Bet pirms tiksiet pieņemts darbā (un pirms jebkādas references tiks pieprasītas) noteikti būs darba intervija, kas varētu norisināties gan aci pret aci, gan telefoniski.
Un visbeidzot, bruņojieties ar pacietību un biezu ādu - atbildi/lēmumu var nākties gaidīt nedēļām vai pat mēnešiem.

Lai veicas!

Thursday, 29 October 2009

Kā skatīties ESRI Virtual Campus video uz Linux?

ESRI ik pa laikam izdod dažādas video apmācības savām ĢIS aplikācijām, daudzas no šīm apmacībām ir visai lietderīgas un bezmaksas, un tās var noskatīties ESRI Virtual Campus mājaslapā online režīmā: ttp://training.esri.com/gateway/index.cfm
Iepriekš būs nepieciešams piereģistrēties (bezmaksas), bet tā jau mūsdienās ir ierasta lieta...
Šīs video prezentācijas, lūk, ir kaut kādā mistiskā Microsoft Media formātā, ko Mozilla uz Kubuntu tā vienkāši nespēja atkodēt, tāpēc nācās nedzaudz izpētīt šo 'problēmu'.

Ja nu kāds ir nonācis līdzīgā situācijā, tad rekomendēju uzinstalēt sekojošas 'paciņas':
  • w32codecs (satur mistiskos Windows kodekus. Par to, kā to izdarīt, ir rakstīts te: http://ohioloco.ubuntuforums.org/showpost.php?p=3203196&postcount=11)
  • mozilla-mplayer (plugins Mozillai)
  • gnome-mplayer (ja nav jau...)
  • MediaPlayerConnectivity https://addons.mozilla.org/en-US/firefox/addon/446 (add-ons Mozillai, lai varētu smalkāk norādīt, kurš pleijeris jāizmanto konkrētajam video, jo pēc noklusējuma nekas prāt nesanāca)
Palaižot video uz Mozillas apakšējā paneļa būs redzama trekna, melna, uz leju vērsta bulta. Uz tās vajag klikšķināt un atvērt konfiguracijas iestādījumus. Atzīmējam, ka vēlamies skatīties "Windows Media" formātu ar "/usr/bin/gnome-mplayer". Tomer video pats par sevi neatvērsies vajadzīgajā pleijerī, tapēc klikšķinam atkal uz tās melnās bultas un izvēlamies "List all media links to page". Jaunajā 'lodziņā' klikšķinam uz dotā linka un beidzot varam ieraudzīt video...

Principā, galvenais bija nokļūt pie šī 'īstā' linka. Iespējams, pie tā var tikt arī ar ātrākām un vienkāršākām metodēm. Ja links ir zināms, tad video vienkārši var palaist ierakstot konsolē kaut ko tamlīdzīgu:

$ gnome-mplayer mms://198.102.62.80/ts_WhatsNewServer92/ts_WhatsNewServer921.asf

Var arī mēģināt izvēleties citu pleijeri.

Thursday, 10 September 2009

How to convert RPM to DEB

Use alien to convert *.rpm files to *.deb files:
$ sudo apt-get install alien
$ sudo alien -d pgDesigner-1.2.10.src.rpm

Tuesday, 8 September 2009

The best way to duplicate Postgres database

I had to copy Postgres database from a development server to the live server and I found this command line based method the most convenient:

$ pg_dump -h myhost.com -U username --clean --oids --verbose mydatabase 2>dump.log | psql -h livehost.com -U username mylivedatabase>>dump.log 2>&1
$ tail -f dump.log


I couldn't do this in a 'single transaction' mode because I don't have superuser privileges.
So I filtered all informative an error messages to follow the process. Database (schem + data) dump with redirection right into another databse proved to be the quickest as no disk space was required for dump files.

Friday, 28 August 2009

No newline symbols in my shell script, please....

You can make Bash shell to print everything out in one long line:

while read EachLine; do
echo -ne $EachLine'" "'
done

Wednesday, 19 August 2009

Pamata lietas, kas jāzin, dzīvojot Lielbritānijā

Tiem, kas plāno pārvākties uz dzīvi Lielbritānijā, parasti interesē, kāda ir minimālā alga, kāds ir nodokļu maksāšanas princips, kādi un cik lieli tad ir šie nodokļi, kā notiek nodokļu atmaksa, kāda ir veselības aprūpes sistēma, kādi pabalsti pieejami utml. jaunajā valstī.
Lielbritānijas valdībai ir lieliska mājaslapa http://www.direct.gov.uk/en/index.htm , kur var atrast visdetālāko informāciju par tamlīdzīgām lietām. Šī valdības mājaslapa bus Jūsu pirmais palīdzības punkts atbilžu meklējumos.

Dažas svarīgākās lietas.

Katram nodokļu maksātājam ir jāizņem National Insurance (NI) numurs, ko izsniedz vietējais Job Center Plus. Šeit tiks prasīti pierādījumi par to, ka aktīvi meklējat darbu (atteikuma vēstules no darba sludinājiem vai darba līgums) un UK dzīvesvietas pierādījums (to apstiprinās uz Jūsu vārda un UK adreses izrakstīts rēķins, bet ne kurš katrs!).

Dzīvesvietas pierādījumu nav tik viegli iegūt, īpaši, ja īrējat istabiņu no kāda vai mitinaties pie draugiem. Viens variants ir iegādāties TV licenci, ko tad izrakstīs uz Jūsu vārda un izvēlēto adresi. Citas mahinācijas varētu arī būt iespējamas, bet dotajā brīdī ir man nezināmas.
Kā cits dzīvesvietas pierādījums var kalpot ikmenēša izraksts no UK bankas, bet atvērt bankas kontu UK arīdzen nav tik viegli. Pirmkārt jau atkal tiks prasīts pierādījums par dzīvesvietu (dažas bankas pieņem TV licenci, citas nē). Visprimitīvāko kontu teju jebkurā bankā var atvērt bez makasa, bet 'nervu čakaris' pirms tam garantēts.

Tiem, kas īrēs dzīvokli vai māju būs jamaksā Council Tax, kura izrakstu var izmantot kā vēl vienu dzīvesvietas pierādījumu. Council Tax vidējais apmērs ir 1000GBP gada par 1-2 istabu mītni, 1500GBP par 3istabu mītni, taču tas svārstās atkarība no pašvaldības. Tiem, kas īrē istabu Council Tax nebūs jāmaksa, jo tas visticamāk būs jau iekļauts īres cenā. Pilna laika studentiem (studē UK augstskolā) arī Council Tax nav jāmaksā... Council Tax nosedz vairakas lietas no kurām viena ir veselības aprūpe (General Practitioner, NHS). Noskaidrojiet savu tuvāko General Practitioner un dodieties piereģistrēties, veselības aprūpe pamatā un principā ir bez maksas.

Istabas īre Lielbritanijā vidēji svārstās no 160-300GBP menesī atkarībā no dzīves vietas novietojuma un telpas izmēriem. Dzīvokļa īre (bez Council Tax) izmaksā sākot no ~350GBP (studio flat) ... 450GBP(1 guļamistabas + 1 dzīvojamās istabas)....600GBP(2 guļamistabas + 1 dzīvojamā istaba) utt. mēnesī. Protams, cenas var svārstīties atkarībā no ģeogrāfiskā novietojuma. Dažkārt var noīret ļoti lētus mitekļus pilsētu nostūros ar ne visai labu reputāciju. Gan der paturēt prātā, ka Jūs tiksiet tiesāti pēc tā, kurā rajonā dzīvosiet, var gadīties, ka tik dēļ savas dzīves vietas adreses Jums iecerētais darbs tiks noraidīts...

Kā atrast GIS darbu Lielbritānijā

Labākais veids, kā atrast ar ĢIS saistītu darbu Lielbritānijā, ir piereģistrējot savu e-pastu 'ĢIS-JOBS' listē šajā mājaslapā http://www.jiscmail.ac.uk/
Uz reģistrēto e-pastu ik dienu tiks izsūtīti jaunākie ĢIS darbu sludinājumi. Šeit darbs tiek piedāvāts dažāda līmeņa speciālistiem un sludinājumus izsūta gan darbā rekrutēšanas aģentūras/aģenti, gan potenciālie darba devēji paši bez starpniekiem. Tādējādi darbu var atrast pat neatrodies Lielbritānijā. Sekmīgajiem kandidātiem jābūt gataviem ierasties uz darba interviju, dažkārt intervija var būt arī telefoniska. Tāpat Lielbritanijā ir pieņemts uzrādīt 2 atsauksmes (refernces) no iepriekšējiem darba devējiem (pasniedzejiem vai tamlīdzīgi).
Kopā ar Curriculum Vitae (CV) UK ir pieņemts iesniegt 'Cover Letter', kas ir tāda kā motivācijas vēstule konkrētajam darba sludinajumam.

How to reverse engineer PostgreSQL database

On Ubuntu/Kubuntu download postgresql-autodoc module:

$ sudo apt-get install postgresql-autodoc
or install it from source:
$ wget http://www.rbt.ca/autodoc/binaries/postgresql_autodoc-1.40.tar.gz
$ tar -xvfz postgresql_autodoc-1.40.tar.gz
$ cd postgresql_autodoc
$ sudo make install


Now run postgresql-autodoc with an appropriate database connection:
$ postgresql_autodoc -h localhost -p 5432 -d lasma -U lasma

This will generate a bunch of files containing your database schema.
Further you may use GraphViz dot utility to make a neat diagram in vector or raster format.
$ sudo apt-get install graphviz
$ dot -Tdia -o output_lasma.dia lasma.dot #output dia diagram
$ dot -Tpng -o output_lasma.png lasma.dot #output png image

Thursday, 16 July 2009

String formatting with Python

Replacing a string:
$ python
>>> name = u'Lāsma'
>>> letter = 'Dear customer,\n Our customer service is the best.'
>>> letter = letter.replace('customer', name, 1) #replace only the first 'customer'
>>> print letter
Dear Lasma,
Our customer service is the best.
>>>


Dictionary based string formatting:
$ python
>>>name = u'Lāsma'
>>>sentence = 'My name is %(name)s"
>>>print sentence % vars()
My name is Lāsma
>>>

Thursday, 9 July 2009

Down them all!

Use wget recursively to download all files from one web page with a single Linux command:
$ wget -r http://download.geonames.org/export/dump