# [GRASS-dev] Compute mahalanobis distance using Scipy

Paulo van Breugel p.vanbreugel at gmail.com
Fri Jan 30 08:44:10 PST 2015

``` On Fri, 30 Jan 2015 10:59 Moritz Lennert <mlennert at club.worldonline.be>
wrote:

On 29/01/15 18:30, Paulo van Breugel wrote:
> I would like to compute a raster layer with for each raster cell the
> mahalanobis distance to the centre of the environmental space// formed
> by all reference data points (raster cells). In R this can be done as
> explained here .
>
> . I would like to do this using python only (no dependency on R). I came
> up with the following, which works, but is very slow. I guess this is
> because it loops over every raster cell to compute the mahalanobis
> distance? Any idea how this can be done faster (I am very new to python,
> so bear with me if I am making stupid mistakes)

There's probably ways to accelerate this in Python (maybe you can try
rewriting your for-loops as map() calls), but on the Wikipedia page on
mahalanobis distance that you reference , it says that:

"Along each principal component axis, it measures the number of standard
deviations from P to the mean of D. If each of these axes is rescaled to
have unit variance, then Mahalanobis distance corresponds to standard
Euclidean distance in the transformed space."

Couldn't you use i.pca to calculate principal components and then
calculate distances of points in that space ?

Just brainstorming...

Interesting thought. I will see if I can work that one out. Thanks!

Moritz

 http:// <http://en.wikipedia.org/wiki/Mahalanobis_distance>
en.wikipedia.org <http://en.wikipedia.org/wiki/Mahalanobis_distance>/wiki/
<http://en.wikipedia.org/wiki/Mahalanobis_distance>Mahalanobis
<http://en.wikipedia.org/wiki/Mahalanobis_distance>_distance
<http://en.wikipedia.org/wiki/Mahalanobis_distance>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/grass-dev/attachments/20150130/2fcc2953/attachment.html>
```