Skip to content

Gridpp in C plus plus

Thomas Nipen edited this page Dec 15, 2022 · 14 revisions

Example code

To use gridpp in C++, include the header file. Have a look at the API documentation (https://metno.github.io/gridpp/) for available functions.

#include <gridpp.h>
#include <iostream>
using namespace gridpp;

int main(void) {

    // Define a 3x2 coarse-scale grid and create some fake temperature data on this grid
    gridpp::vec2 coarse_lats = gridpp::init_vec2(3, 2);
    gridpp::vec2 coarse_lons = gridpp::init_vec2(3, 2);
    gridpp::vec2 coarse_temperature = gridpp::init_vec2(3, 2);
    for(int y = 0; y < coarse_lats.size(); y++) {
        for(int x = 0; x < coarse_lats[y].size(); x++) {
            coarse_lats[y][x] = y;
            coarse_lons[y][x] = x;
            coarse_temperature[y][x] = 2 * y * y + x * x;
        }
    }
    gridpp::Grid coarse_grid = gridpp::Grid(coarse_lats, coarse_lons);

    // Define a 16x11 desired-fine scale grid that is located within the 3x2 grid
    gridpp::vec2 fine_lats = gridpp::init_vec2(11, 6);
    gridpp::vec2 fine_lons = gridpp::init_vec2(11, 6);
    for(int y = 0; y < fine_lats.size(); y++) {
        for(int x = 0; x < fine_lats[y].size(); x++) {
            fine_lats[y][x] = y / 5.0;
            fine_lons[y][x] = x / 5.0;
        }
    }
    gridpp::Grid fine_grid = gridpp::Grid(fine_lats, fine_lons);

    // Perform interpolation from the coarse grid to the fine grid
    gridpp::vec2 fine_temperature = gridpp::bilinear(coarse_grid, fine_grid, coarse_temperature);

    // Print out the temperatures on the two grids
    std::cout << "Coarse scale temperature" << std::endl;
    for(int y = 0; y < coarse_temperature.size(); y++) {
        for(int x = 0; x < coarse_temperature[y].size(); x++) {
            std::cout << " " << coarse_temperature[y][x];
        }
        std::cout << std::endl;
    }
    std::cout << "Fine scale temperature" << std::endl;
    for(int y = 0; y < fine_temperature.size(); y++) {
        for(int x = 0; x < fine_temperature[y].size(); x++) {
            std::cout << " " << fine_temperature[y][x];
        }
        std::cout << std::endl;
    }
}

Compiling and running

Save the code as example.cpp and compile the program by linking with the gridpp library:

g++ example.cpp -l gridpp -fopenmp -o example

Run the example program like this:

./example

Coarse scale temperature
 0 1
 2 3
 8 9
Fine scale temperature
 0 0.2 0.4 0.6 0.8 1
 0.4 0.6 0.8 1 1.2 1.4
 0.8 1 1.2 1.4 1.6 1.8
 1.2 1.4 1.6 1.8 2 2.2
 1.6 1.8 2 2.2 2.4 2.6
 2 2.2 2.4 2.6 2.8 3
 3.2 3.4 3.6 3.8 4 4.2
 4.4 4.6 4.8 5 5.2 5.4
 5.6 5.8 6 6.2 6.4 6.6
 6.8 7 7.2 7.4 7.6 7.8
 8 8.2 8.4 8.6 8.8 9

Clone this wiki locally