File: gdalalg_raster_reclassify.cpp

package info (click to toggle)
gdal 3.12.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 92,396 kB
  • sloc: cpp: 1,224,305; ansic: 206,456; python: 26,284; java: 6,001; xml: 4,769; sh: 3,869; cs: 2,513; yacc: 1,306; makefile: 214
file content (217 lines) | stat: -rw-r--r-- 7,481 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
/******************************************************************************
 *
 * Project:  GDAL
 * Purpose:  "reclassify" step of "raster pipeline"
 * Author:   Daniel Baston
 *
 ******************************************************************************
 * Copyright (c) 2025, ISciences LLC
 *
 * SPDX-License-Identifier: MIT
 ****************************************************************************/

#include "gdalalg_raster_reclassify.h"

#include "cpl_vsi_virtual.h"
#include "gdal_priv.h"
#include "gdal_utils.h"
#include "../frmts/vrt/vrtdataset.h"
#include "../frmts/vrt/vrtreclassifier.h"

#include <array>

//! @cond Doxygen_Suppress

#ifndef _
#define _(x) (x)
#endif

/************************************************************************/
/*    GDALRasterReclassifyAlgorithm::GDALRasterReclassifyAlgorithm()    */
/************************************************************************/

GDALRasterReclassifyAlgorithm::GDALRasterReclassifyAlgorithm(
    bool standaloneStep)
    : GDALRasterPipelineStepAlgorithm(NAME, DESCRIPTION, HELP_URL,
                                      standaloneStep)
{
    AddArg("mapping", 'm',
           _("Reclassification mappings (or specify a @<filename> to point to "
             "a file containing mappings"),
           &m_mapping)
        .SetRequired();
    AddOutputDataTypeArg(&m_type);
}

/************************************************************************/
/*              GDALRasterReclassifyValidateMappings                    */
/************************************************************************/

static bool GDALReclassifyValidateMappings(GDALDataset &input,
                                           const std::string &mappings,
                                           GDALDataType eDstType)
{
    int hasNoData;
    std::optional<double> noData =
        input.GetRasterBand(1)->GetNoDataValue(&hasNoData);
    if (!hasNoData)
    {
        noData.reset();
    }

    gdal::Reclassifier reclassifier;
    return reclassifier.Init(mappings.c_str(), noData, eDstType) == CE_None;
}

/************************************************************************/
/*              GDALRasterReclassifyCreateVRTDerived                    */
/************************************************************************/

static std::unique_ptr<GDALDataset>
GDALReclassifyCreateVRTDerived(GDALDataset &input, const std::string &mappings,
                               GDALDataType eDstType)
{
    CPLXMLTreeCloser root(CPLCreateXMLNode(nullptr, CXT_Element, "VRTDataset"));

    const auto nX = input.GetRasterXSize();
    const auto nY = input.GetRasterYSize();

    for (int iBand = 1; iBand <= input.GetRasterCount(); ++iBand)
    {
        const GDALDataType srcType =
            input.GetRasterBand(iBand)->GetRasterDataType();
        const GDALDataType bandType =
            eDstType == GDT_Unknown ? srcType : eDstType;
        const GDALDataType xferType = GDALDataTypeUnion(srcType, bandType);

        CPLXMLNode *band =
            CPLCreateXMLNode(root.get(), CXT_Element, "VRTRasterBand");
        CPLAddXMLAttributeAndValue(band, "subClass", "VRTDerivedRasterBand");
        CPLAddXMLAttributeAndValue(band, "dataType",
                                   GDALGetDataTypeName(bandType));

        CPLXMLNode *pixelFunctionType =
            CPLCreateXMLNode(band, CXT_Element, "PixelFunctionType");
        CPLCreateXMLNode(pixelFunctionType, CXT_Text, "reclassify");
        CPLXMLNode *arguments =
            CPLCreateXMLNode(band, CXT_Element, "PixelFunctionArguments");
        CPLAddXMLAttributeAndValue(arguments, "mapping", mappings.c_str());

        CPLXMLNode *sourceTransferType =
            CPLCreateXMLNode(band, CXT_Element, "SourceTransferType");
        CPLCreateXMLNode(sourceTransferType, CXT_Text,
                         GDALGetDataTypeName(xferType));
    }

    auto ds = std::make_unique<VRTDataset>(nX, nY);
    if (ds->XMLInit(root.get(), "") != CE_None)
    {
        return nullptr;
    };

    for (int iBand = 1; iBand <= input.GetRasterCount(); ++iBand)
    {
        auto poSrcBand = input.GetRasterBand(iBand);
        auto poDstBand =
            cpl::down_cast<VRTDerivedRasterBand *>(ds->GetRasterBand(iBand));
        GDALCopyNoDataValue(poDstBand, poSrcBand);
        poDstBand->AddSimpleSource(poSrcBand);
    }

    GDALGeoTransform gt;
    if (input.GetGeoTransform(gt) == CE_None)
        ds->SetGeoTransform(gt);
    ds->SetSpatialRef(input.GetSpatialRef());

    return ds;
}

/************************************************************************/
/*           GDALRasterReclassifyAlgorithm::RunStep()                   */
/************************************************************************/

bool GDALRasterReclassifyAlgorithm::RunStep(GDALPipelineStepRunContext &)
{
    const auto poSrcDS = m_inputDataset[0].GetDatasetRef();
    CPLAssert(poSrcDS);
    CPLAssert(m_outputDataset.GetName().empty());
    CPLAssert(!m_outputDataset.GetDatasetRef());

    // Already validated by argument parser
    const GDALDataType eDstType =
        m_type.empty() ? GDT_Unknown : GDALGetDataTypeByName(m_type.c_str());

    const auto nErrorCount = CPLGetErrorCounter();
    if (!m_mapping.empty() && m_mapping[0] == '@')
    {
        auto f =
            VSIVirtualHandleUniquePtr(VSIFOpenL(m_mapping.c_str() + 1, "r"));
        if (!f)
        {
            ReportError(CE_Failure, CPLE_FileIO, "Cannot open %s",
                        m_mapping.c_str() + 1);
            return false;
        }

        m_mapping.clear();
        try
        {
            constexpr int MAX_CHARS_PER_LINE = 1000 * 1000;
            constexpr size_t MAX_MAPPING_SIZE = 10 * 1000 * 1000;
            while (const char *line =
                       CPLReadLine2L(f.get(), MAX_CHARS_PER_LINE, nullptr))
            {
                while (isspace(*line))
                {
                    line++;
                }

                if (line[0])
                {
                    if (!m_mapping.empty())
                    {
                        m_mapping.append(";");
                    }

                    const char *comment = strchr(line, '#');
                    if (!comment)
                    {
                        m_mapping.append(line);
                    }
                    else
                    {
                        m_mapping.append(line,
                                         static_cast<size_t>(comment - line));
                    }
                    if (m_mapping.size() > MAX_MAPPING_SIZE)
                    {
                        ReportError(CE_Failure, CPLE_AppDefined,
                                    "Too large mapping size");
                        return false;
                    }
                }
            }
        }
        catch (const std::exception &)
        {
            ReportError(CE_Failure, CPLE_OutOfMemory,
                        "Out of memory while ingesting mapping file");
        }
    }
    if (nErrorCount == CPLGetErrorCounter())
    {
        if (!GDALReclassifyValidateMappings(*poSrcDS, m_mapping, eDstType))
        {
            return false;
        }

        m_outputDataset.Set(
            GDALReclassifyCreateVRTDerived(*poSrcDS, m_mapping, eDstType));
    }
    return m_outputDataset.GetDatasetRef() != nullptr;
}

GDALRasterReclassifyAlgorithmStandalone::
    ~GDALRasterReclassifyAlgorithmStandalone() = default;

//! @endcond