Search code examples
juliainterpolationlinear-interpolation

Interpolation on irregular grids


Is it possible to perform 2D interpolation in Julia where one of the coordinates is irregular? Take the following example, where x is irregular, but y is regular:

x = [0.5 2 3 4.;
     0.6 1 3 4.;
     0.7 2 3 5.;
     0.8 2 3 4.;]

y = [1;
     2;
     3;
     4;]

z = [1. 2. 1. 2.;
     1. 2. 1. 2.;
     1. 2. 3. 2.;
     1. 2. 2. 2.;]

I have tried the following with the Dierckx-package, but it results in an error:

Spline2D(x, y, z)

Similarly, it seems like the Interpolations-package doesn't handle irregular grids yet.


Solution

  • Try the following (install Surrogates package if necessary):

    using Surrogates
    
    x = [0.5 2 3 4.;
         0.6 1 3 4.;
         0.7 2 3 5.;
         0.8 2 3 4.;]
    
    y = [1;
         2;
         3;
         4;]
    z = [1. 2. 1. 2.;
         1. 2. 1. 2.;
         1. 2. 3. 2.;
         1. 2. 2. 2.;]
    
    points = collect(zip(repeat(1.0*y; outer=4), vec(x)));
    vals = vec(z);
    
    ks = Kriging(points, vals, [0.0, 0.0], [-5.0, 5.0]);
    

    Now ks is an interpolation object which can accessed by calling it with a point argument e.g. ks((xcoord, ycoord)).

    For example:

    julia> using UnicodePlots
    
    julia> contourplot(0.0:0.1:5.0, 0.0:0.1:5.0, (x,y)->ks((x,y));
             colorbar=false, canvas=DotCanvas)
         ┌────────────────────────────────────────┐ 
       5 │        :           ........    :.      │ 
         │       :'         :''       '.   :     .│ 
         │. ...''           :          ':  :    :'│ 
         │'''      ......   :.          :  :   :  │ 
         │       .'      :.  :.         :  :   '. │ 
         │      :         '.  '.        :  '.   ':│ 
         │     :.          :   ':..   .:    :.    │ 
         │      ':...     .:      '''''      ':   │ 
         │           ''''''                    '':│ 
         │                                        │ 
         │                                        │ 
         │                          ..............│ 
         │.           .........'''''              │ 
         │ '''''''''''' ....                      │ 
       0 │    ...'''''''    '''''''''....'''''''''│ 
         └────────────────────────────────────────┘ 
          0                                      5  
    
    

    This method uses Kriging which is an interpolation method. More information available in Wikipedia.