Adding a new derived variable

Every derived variable is implemented as a subclass of MDerivedDataFieldProcessor. Each processor declares the CF standard name of the output variable, the list of required input variable names (optionally qualified with a level type), and a compute() method that fills the output grid.

All processors are registered in MDerivedMetVarsDataSource::MDerivedMetVarsDataSource() in src/data/derivedvars/derivedmetvarsdatasource.cpp.

For a list of existing derived variables and user-facing configuration, see Derived Variables.

Choosing C++ or Python

Two implementation paths exist:

  • C++ (MDerivedDataFieldProcessor) – runs directly on Met.3D’s own grids, with no external dependencies. This is generally the preferred approach, especially for anything performance critical.

  • Python (MPythonDerivedProcessor) – hands the data to Python (e.g. MetPy) as an xarray.Dataset. Convenient for reusing existing library functions, at the cost of the round-trip to export Met.3D’s native grids via NetCDF to Python and parsing the result back, and (often) the cost of a slower algorithm compared to a native C++ one. Prefer Python for prototyping or when a well-tested library function already exists.

Both are registered the same way and are interchangeable from the user’s point of view.

Adding a C++ derived variable

  1. Subclass MDerivedDataFieldProcessor in src/data/derivedvars/derivedmetvars_standard.h/.cpp (or a new file):

    class MMyNewVariableProcessor : public MDerivedDataFieldProcessor
    {
    public:
        MMyNewVariableProcessor();
        void compute(const QList<MDataLease<MStructuredGrid>>& inputGrids,
                     MStructuredGrid *derivedGrid) override;
    };
    
  2. Implement the constructor to declare the output standard name, the required inputs, and the output unit:

    MMyNewVariableProcessor::MMyNewVariableProcessor()
        : MDerivedDataFieldProcessor(
              "wind_speed",                        // output CF standard name
              QStringList() << "eastward_wind"     // required inputs (CF standard names)
                            << "northward_wind")
    {
        outputUnit = "m s-1";                      // the unit compute() produces
    }
    
    • The output name should be a valid CF standard name where one exists, so the variable integrates cleanly (unit reporting, NetCDF export, input mappings).

    • Set the outputUnit to the unit your compute() actually produces. It is reported to Met.3D as the variable’s unit. There is no automatic unit checking or conversion, see Units. The unit currently solely is for display and as metadata.

    • Output level types. When calling the constructor only with two arguments, the derived variable will be available for all level types, thus for SINGLE_LEVEL, PRESSURE_LEVELS_3D, AUXILIARY_PRESSURE_3D and HYBRID_SIGMA_PRESSURE_3D. The derived variable will take the level type of its first input variable. Pass a third argument to restrict the available level types, for example if the result is a vertically integrated value, or the implementation is only implemented for a specific level type (see Output level types and 2-D fields):

    MMyNewVariableProcessor::MMyNewVariableProcessor()
        : MDerivedDataFieldProcessor(
              "my_new_variable",
              QStringList() << "air_temperature/HYBRID_SIGMA_PRESSURE_3D"
                            << "surface_air_pressure/SURFACE_2D",
              {SURFACE_2D})   // 2-D output from 3-D inputs
    {
        outputUnit = "1"; // unitless
    }
    

    The /HYBRID_SIGMA_PRESSURE_3D and /SURFACE_2D suffixes on the inputs are level-type qualifiers; their full syntax is described in Declaring and resolving inputs.

  3. Implement compute(). The inputGrids list matches the declared input order, and derivedGrid is pre-initialized with the geometry and metadata of the first input grid. Write the results into derivedGrid.

    Important

    If one of the input grids does not exist (e.g., data not available for the requested time step), the processor is not invoked and a grid of level type EMPTY_LEVELS_3D is passed down the pipeline.

    However, if all grids are available, individual grid cells may be M_MISSING_VALUE, which need to be handled. Do not perform computations using grid cells with missing values (e.g., interpolation), instead propagate the missing value to the output grid.

    void MMyNewVariableProcessor::compute(
            const QList<MDataLease<MStructuredGrid>>& inputGrids,
            MStructuredGrid *derivedGrid)
    {
        const auto& uGrid = inputGrids.at(0);
        const auto& vGrid = inputGrids.at(1);
    
        for (unsigned int n = 0; n < derivedGrid->getNumValues(); ++n)
        {
            const float u = uGrid->getValue(n);
            const float v = vGrid->getValue(n);
    
            // Propagate missing values instead of computing on them.
            if (u == M_MISSING_VALUE || v == M_MISSING_VALUE)
            {
                derivedGrid->setValue(n, M_MISSING_VALUE);
                continue;
            }
            derivedGrid->setValue(n, std::sqrt(u * u + v * v));
        }
    }
    
  4. Register the processor in MDerivedMetVarsDataSource::MDerivedMetVarsDataSource() in derivedmetvarsdatasource.cpp:

    registerDerivedDataFieldProcessor(new MMyNewVariableProcessor());
    

Output level types and 2-D fields

The output takes the vertical level type of its first input field unless you restrict it. Passing a single supported level type is the mechanism for producing a 2-D field from 3-D inputs: when a processor supports exactly one output level type, Met.3D creates the result grid with that type instead of copying it from the first input grid.

Units

Met.3D performs no automatic unit validation or conversion. You are responsible for:

  • knowing the units of the input grids (document them) and converting as needed – e.g. grids store pressure in hPa, so multiply by 100 for Pa, and use grid->getPressure(k, j, i) to obtain the physical pressure at a cell;

  • setting outputUnit to the unit your compute() actually produces.

outputUnit is what Met.3D reports (via getUnitOfResult()) and writes on export.

Declaring and resolving inputs

Required inputs are given as CF standard names. Each entry may carry up to three /-separated qualifiers:

standard_name/LEVELTYPE/initOffsetSeconds/validOffsetSeconds
  • Level type – force the input to a specific level type (e.g. surface_air_pressure/SURFACE_2D), independent of the output level type. The wildcard /ANY selects the first level type on which the variable is available.

  • Init-time offset – a signed number of seconds added to INIT_TIME (standard_name//-43200 requests the field from the forecast 12 h earlier; leave the level-type field empty to skip it).

  • Valid-time offset – a signed number of seconds added to VALID_TIME in the fourth field (standard_name///-21600 requests the field 6 h earlier).

Two further resolution rules apply to every input:

  • Name mapping – the standard name is translated to the actual variable name in the dataset through the user-configured mapping. This user-configured mapping is part of the dataset configuration file and can be viewed via the table in the Add dataset dialog or in the configuration file via the key inputVarsForDerivedVars. If the user maps the output standard name directly to a predefined dataset variable, the mapping takes precedence and the processor is not registered at all.

  • Recursively derived inputs – an input may itself be a derived variable. getSourceOfInputVariable() resolves it to whichever source provides it, including this derived-variable source again, so derived variables can be built on top of other derived variables.

Processing information

The data source automatically records the input variables it used as the source variables attribute on the output grid. Override addProcessingInformation(MStructuredGrid*) in your processor to attach further attributes (parameters, method notes, …); these are written to exported NetCDF files.

Adding a Python-based derived variable

Python-derived variables call MetPy (or arbitrary Python code) through Met.3D’s Python interface. Data is exchanged as an xarray.Dataset via an in-memory NetCDF buffer.

  1. Add an endpoint type. In src/data/derivedvars/pythonderivedprocessor.h, add a value to the EndpointType enum before INVALID:

    enum EndpointType
    {
        METPY_PV_BAROCLINIC = 0,
        // ... existing values ...
        MY_NEW_ENDPOINT = N,  // next available index
        INVALID
    };
    
  2. Expose the value to Python. In src/system/mpyinterfacebindings.cpp, add a .value() line to the pybind11 enum block:

    .value("MY_NEW_ENDPOINT", PyEndpoint::MY_NEW_ENDPOINT)
    
  3. Register the processor. In MPythonDerivedProcessor::registerProcessorsTo() in pythonderivedprocessor.cpp:

    auto myProcessor = new MPythonDerivedProcessor(
        "my_new_variable_metpy",
        {"air_pressure", "air_temperature"},  // required inputs, in order
        PyEndpoint::MY_NEW_ENDPOINT);
    dataSource->registerDerivedDataFieldProcessor(myProcessor);
    
  4. Add the Python function. In src/python/interface/python_endpoints.py:

    def my_new_variable(dataset, in_grid_names, out_grid_name):
        import metpy.calc as mpcalc
        from metpy.units import units
        p = dataset[in_grid_names[0]] * units('Pa')
        t = dataset[in_grid_names[1]] * units('K')
        dataset[out_grid_name] = mpcalc.some_function(p, t)
        return dataset
    
  5. Dispatch the function. In invoke_python_endpoint() in python_endpoints.py:

    elif func == derived_var_bindings.EndpointType.MY_NEW_ENDPOINT:
        return my_new_variable(dataset, in_grid_names, out_grid_name)
    

Build options and experimental variables

Some processors are only compiled in when the corresponding CMake option is set (see the options table in CMake options):

  • ENABLE_EXPERIMENTAL_DERIVEDVARS – enables derived variables that are not yet well tested. Register such processors in the experimental block of MDerivedMetVarsDataSource::MDerivedMetVarsDataSource().

  • ENABLE_FORTRAN / ENABLE_LAGRANTO_DERIVATIVES – required for derivatives computed through the bundled Fortran LAGRANTO code.

Note

If you have implemented a derived variable that you think would be useful to other Met.3D users, we would be happy to include it in the main codebase. Please consider submitting a merge request on GitLab. If you do so, make sure to compare your implementation against a reference (ground truth), you handle missing values, and take care of data boundaries.