Line data Source code
1 : /******************************************************************************
2 : *
3 : * Project: GDAL
4 : * Purpose: "gdal raster calc" subcommand
5 : * Author: Daniel Baston
6 : *
7 : ******************************************************************************
8 : * Copyright (c) 2025, ISciences LLC
9 : *
10 : * SPDX-License-Identifier: MIT
11 : ****************************************************************************/
12 :
13 : #include "gdalalg_raster_calc.h"
14 :
15 : #include "../frmts/vrt/gdal_vrt.h"
16 : #include "../frmts/vrt/vrtdataset.h"
17 :
18 : #include "cpl_float.h"
19 : #include "cpl_vsi_virtual.h"
20 : #include "gdal_priv.h"
21 : #include "gdal_utils.h"
22 : #include "vrtdataset.h"
23 :
24 : #include <algorithm>
25 : #include <optional>
26 :
27 : //! @cond Doxygen_Suppress
28 :
29 : #ifndef _
30 : #define _(x) (x)
31 : #endif
32 :
33 : struct GDALCalcOptions
34 : {
35 : GDALDataType dstType{GDT_Unknown};
36 : bool checkCRS{true};
37 : bool checkExtent{true};
38 : };
39 :
40 242 : static bool MatchIsCompleteVariableNameWithNoIndex(const std::string &str,
41 : size_t from, size_t to)
42 : {
43 242 : if (to < str.size())
44 : {
45 : // If the character after the end of the match is:
46 : // * alphanumeric or _ : we've matched only part of a variable name
47 : // * [ : we've matched a variable that already has an index
48 : // * ( : we've matched a function name
49 308 : if (std::isalnum(str[to]) || str[to] == '_' || str[to] == '[' ||
50 108 : str[to] == '(')
51 : {
52 93 : return false;
53 : }
54 : }
55 149 : if (from > 0)
56 : {
57 : // If the character before the start of the match is alphanumeric or _,
58 : // we've matched only part of a variable name.
59 91 : if (std::isalnum(str[from - 1]) || str[from - 1] == '_')
60 : {
61 3 : return false;
62 : }
63 : }
64 :
65 146 : return true;
66 : }
67 :
68 : /**
69 : * Add a band subscript to all instances of a specified variable that
70 : * do not already have such a subscript. For example, "X" would be
71 : * replaced with "X[3]" but "X[1]" would be left untouched.
72 : */
73 146 : static std::string SetBandIndices(const std::string &origExpression,
74 : const std::string &variable, int band,
75 : bool &expressionChanged)
76 : {
77 146 : std::string expression = origExpression;
78 146 : expressionChanged = false;
79 :
80 146 : std::string::size_type seekPos = 0;
81 146 : auto pos = expression.find(variable, seekPos);
82 352 : while (pos != std::string::npos)
83 : {
84 206 : auto end = pos + variable.size();
85 :
86 206 : if (MatchIsCompleteVariableNameWithNoIndex(expression, pos, end))
87 : {
88 : // No index specified for variable
89 220 : expression = expression.substr(0, pos + variable.size()) + '[' +
90 330 : std::to_string(band) + ']' + expression.substr(end);
91 110 : expressionChanged = true;
92 : }
93 :
94 206 : seekPos = end;
95 206 : pos = expression.find(variable, seekPos);
96 : }
97 :
98 146 : return expression;
99 : }
100 :
101 72 : static bool PosIsAggregateFunctionArgument(const std::string &expression,
102 : size_t pos)
103 : {
104 : // If this position is a function argument, we should be able to
105 : // scan backwards for a ( and find only variable names, literals or commas.
106 72 : while (pos != 0)
107 : {
108 64 : const char c = expression[pos];
109 64 : if (c == '(')
110 : {
111 24 : pos--;
112 24 : break;
113 : }
114 40 : if (!(isspace(c) || isalnum(c) || c == ',' || c == '.' || c == '[' ||
115 : c == ']' || c == '_'))
116 : {
117 4 : return false;
118 : }
119 36 : pos--;
120 : }
121 :
122 : // Now what we've found the (, the preceding characters should be an
123 : // aggregate function name
124 32 : if (pos < 2)
125 : {
126 8 : return false;
127 : }
128 :
129 24 : if (STARTS_WITH_CI(expression.c_str() + (pos - 2), "avg") ||
130 20 : STARTS_WITH_CI(expression.c_str() + (pos - 2), "sum") ||
131 52 : STARTS_WITH_CI(expression.c_str() + (pos - 2), "min") ||
132 8 : STARTS_WITH_CI(expression.c_str() + (pos - 2), "max"))
133 : {
134 20 : return true;
135 : }
136 :
137 4 : return false;
138 : }
139 :
140 : /**
141 : * Replace X by X[1],X[2],...X[n]
142 : */
143 : static std::string
144 32 : SetBandIndicesFlattenedExpression(const std::string &origExpression,
145 : const std::string &variable, int nBands)
146 : {
147 32 : std::string expression = origExpression;
148 :
149 32 : std::string::size_type seekPos = 0;
150 32 : auto pos = expression.find(variable, seekPos);
151 68 : while (pos != std::string::npos)
152 : {
153 36 : auto end = pos + variable.size();
154 :
155 72 : if (MatchIsCompleteVariableNameWithNoIndex(expression, pos, end) &&
156 36 : PosIsAggregateFunctionArgument(expression, pos))
157 : {
158 20 : std::string newExpr = expression.substr(0, pos);
159 68 : for (int i = 1; i <= nBands; ++i)
160 : {
161 48 : if (i > 1)
162 28 : newExpr += ',';
163 48 : newExpr += variable;
164 48 : newExpr += '[';
165 48 : newExpr += std::to_string(i);
166 48 : newExpr += ']';
167 : }
168 20 : const size_t oldExprSize = expression.size();
169 20 : newExpr += expression.substr(end);
170 20 : expression = std::move(newExpr);
171 20 : end += expression.size() - oldExprSize;
172 : }
173 :
174 36 : seekPos = end;
175 36 : pos = expression.find(variable, seekPos);
176 : }
177 :
178 32 : return expression;
179 : }
180 :
181 : struct SourceProperties
182 : {
183 : int nBands{0};
184 : int nX{0};
185 : int nY{0};
186 : bool hasGT{false};
187 : GDALGeoTransform gt{};
188 : std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser> srs{
189 : nullptr};
190 : std::vector<std::optional<double>> noData{};
191 : GDALDataType eDT{GDT_Unknown};
192 : };
193 :
194 : static std::optional<SourceProperties>
195 156 : UpdateSourceProperties(SourceProperties &out, const std::string &dsn,
196 : const GDALCalcOptions &options)
197 : {
198 312 : SourceProperties source;
199 156 : bool srsMismatch = false;
200 156 : bool extentMismatch = false;
201 156 : bool dimensionMismatch = false;
202 :
203 : {
204 : std::unique_ptr<GDALDataset> ds(
205 156 : GDALDataset::Open(dsn.c_str(), GDAL_OF_RASTER));
206 :
207 156 : if (!ds)
208 : {
209 0 : CPLError(CE_Failure, CPLE_AppDefined, "Failed to open %s",
210 : dsn.c_str());
211 0 : return std::nullopt;
212 : }
213 :
214 156 : source.nBands = ds->GetRasterCount();
215 156 : source.nX = ds->GetRasterXSize();
216 156 : source.nY = ds->GetRasterYSize();
217 156 : source.noData.resize(source.nBands);
218 :
219 156 : if (options.checkExtent)
220 : {
221 150 : ds->GetGeoTransform(source.gt);
222 : }
223 :
224 156 : if (options.checkCRS && out.srs)
225 : {
226 57 : const OGRSpatialReference *srs = ds->GetSpatialRef();
227 57 : srsMismatch = srs && !srs->IsSame(out.srs.get());
228 : }
229 :
230 : // Store the source data type if it is the same for all bands in the source
231 156 : bool bandsHaveSameType = true;
232 412 : for (int i = 1; i <= source.nBands; ++i)
233 : {
234 256 : GDALRasterBand *band = ds->GetRasterBand(i);
235 :
236 256 : if (i == 1)
237 : {
238 156 : source.eDT = band->GetRasterDataType();
239 : }
240 200 : else if (bandsHaveSameType &&
241 100 : source.eDT != band->GetRasterDataType())
242 : {
243 0 : source.eDT = GDT_Unknown;
244 0 : bandsHaveSameType = false;
245 : }
246 :
247 : int success;
248 256 : double noData = band->GetNoDataValue(&success);
249 256 : if (success)
250 : {
251 17 : source.noData[i - 1] = noData;
252 : }
253 : }
254 : }
255 :
256 156 : if (source.nX != out.nX || source.nY != out.nY)
257 : {
258 3 : dimensionMismatch = true;
259 : }
260 :
261 156 : if (source.gt.xorig != out.gt.xorig || source.gt.xrot != out.gt.xrot ||
262 156 : source.gt.yorig != out.gt.yorig || source.gt.yrot != out.gt.yrot)
263 : {
264 6 : extentMismatch = true;
265 : }
266 156 : if (source.gt.xscale != out.gt.xscale || source.gt.yscale != out.gt.yscale)
267 : {
268 : // Resolutions are different. Are the extents the same?
269 9 : double xmaxOut =
270 9 : out.gt.xorig + out.nX * out.gt.xscale + out.nY * out.gt.xrot;
271 9 : double yminOut =
272 9 : out.gt.yorig + out.nX * out.gt.yrot + out.nY * out.gt.yscale;
273 :
274 9 : double xmax = source.gt.xorig + source.nX * source.gt.xscale +
275 9 : source.nY * source.gt.xrot;
276 9 : double ymin = source.gt.yorig + source.nX * source.gt.yrot +
277 9 : source.nY * source.gt.yscale;
278 :
279 : // Max allowable extent misalignment, expressed as fraction of a pixel
280 9 : constexpr double EXTENT_RTOL = 1e-3;
281 :
282 9 : if (std::abs(xmax - xmaxOut) >
283 15 : EXTENT_RTOL * std::abs(source.gt.xscale) ||
284 6 : std::abs(ymin - yminOut) > EXTENT_RTOL * std::abs(source.gt.yscale))
285 : {
286 6 : extentMismatch = true;
287 : }
288 : }
289 :
290 156 : if (options.checkExtent && extentMismatch)
291 : {
292 2 : CPLError(CE_Failure, CPLE_AppDefined,
293 : "Input extents are inconsistent.");
294 2 : return std::nullopt;
295 : }
296 :
297 154 : if (!options.checkExtent && dimensionMismatch)
298 : {
299 1 : CPLError(CE_Failure, CPLE_AppDefined,
300 : "Inputs do not have the same dimensions.");
301 1 : return std::nullopt;
302 : }
303 :
304 : // Find a common resolution
305 153 : if (source.nX > out.nX)
306 : {
307 1 : auto dx = CPLGreatestCommonDivisor(out.gt.xscale, source.gt.xscale);
308 1 : if (dx == 0)
309 : {
310 0 : CPLError(CE_Failure, CPLE_AppDefined,
311 : "Failed to find common resolution for inputs.");
312 0 : return std::nullopt;
313 : }
314 1 : out.nX = static_cast<int>(
315 1 : std::round(static_cast<double>(out.nX) * out.gt.xscale / dx));
316 1 : out.gt.xscale = dx;
317 : }
318 153 : if (source.nY > out.nY)
319 : {
320 1 : auto dy = CPLGreatestCommonDivisor(out.gt.yscale, source.gt.yscale);
321 1 : if (dy == 0)
322 : {
323 0 : CPLError(CE_Failure, CPLE_AppDefined,
324 : "Failed to find common resolution for inputs.");
325 0 : return std::nullopt;
326 : }
327 1 : out.nY = static_cast<int>(
328 1 : std::round(static_cast<double>(out.nY) * out.gt.yscale / dy));
329 1 : out.gt.yscale = dy;
330 : }
331 :
332 153 : if (srsMismatch)
333 : {
334 1 : CPLError(CE_Failure, CPLE_AppDefined,
335 : "Input spatial reference systems are inconsistent.");
336 1 : return std::nullopt;
337 : }
338 :
339 152 : return source;
340 : }
341 :
342 : /** Create XML nodes for one or more derived bands resulting from the evaluation
343 : * of a single expression
344 : *
345 : * @param pszVRTFilename VRT filename
346 : * @param root VRTDataset node to which the band nodes should be added
347 : * @param bandType the type of the band(s) to create
348 : * @param nXOut Number of columns in VRT dataset
349 : * @param nYOut Number of rows in VRT dataset
350 : * @param expression Expression for which band(s) should be added
351 : * @param dialect Expression dialect
352 : * @param flatten Generate a single band output raster per expression, even if
353 : * input datasets are multiband.
354 : * @param noDataText nodata value to use for the created band, or "none", or ""
355 : * @param pixelFunctionArguments Pixel function arguments.
356 : * @param sources Mapping of source names to DSNs
357 : * @param sourceProps Mapping of source names to properties
358 : * @param fakeSourceFilename If not empty, used instead of real input filenames.
359 : * @return true if the band(s) were added, false otherwise
360 : */
361 : static bool
362 116 : CreateDerivedBandXML(const char *pszVRTFilename, CPLXMLNode *root, int nXOut,
363 : int nYOut, GDALDataType bandType,
364 : const std::string &expression, const std::string &dialect,
365 : bool flatten, const std::string &noDataText,
366 : const std::vector<std::string> &pixelFunctionArguments,
367 : const std::map<std::string, std::string> &sources,
368 : const std::map<std::string, SourceProperties> &sourceProps,
369 : const std::string &fakeSourceFilename)
370 : {
371 116 : int nOutBands = 1; // By default, each expression produces a single output
372 : // band. When processing the expression below, we may
373 : // discover that the expression produces multiple bands,
374 : // in which case this will be updated.
375 :
376 255 : for (int nOutBand = 1; nOutBand <= nOutBands; nOutBand++)
377 : {
378 : // Copy the expression for each output band, because we may modify it
379 : // when adding band indices (e.g., X -> X[1]) to the variables in the
380 : // expression.
381 143 : std::string bandExpression = expression;
382 :
383 143 : CPLXMLNode *band = CPLCreateXMLNode(root, CXT_Element, "VRTRasterBand");
384 143 : CPLAddXMLAttributeAndValue(band, "subClass", "VRTDerivedRasterBand");
385 143 : if (bandType == GDT_Unknown)
386 : {
387 103 : bandType = GDT_Float64;
388 : }
389 143 : CPLAddXMLAttributeAndValue(band, "dataType",
390 : GDALGetDataTypeName(bandType));
391 :
392 143 : std::optional<double> dstNoData;
393 143 : bool autoSelectNoDataValue = false;
394 143 : if (noDataText.empty())
395 : {
396 138 : autoSelectNoDataValue = true;
397 : }
398 5 : else if (noDataText != "none")
399 : {
400 : char *end;
401 5 : dstNoData = CPLStrtod(noDataText.c_str(), &end);
402 5 : if (end != noDataText.c_str() + noDataText.size())
403 : {
404 0 : CPLError(CE_Failure, CPLE_AppDefined,
405 : "Invalid NoData value: %s", noDataText.c_str());
406 0 : return false;
407 : }
408 : }
409 :
410 327 : for (const auto &[source_name, dsn] : sources)
411 : {
412 188 : auto it = sourceProps.find(source_name);
413 188 : CPLAssert(it != sourceProps.end());
414 188 : const auto &props = it->second;
415 :
416 188 : bool expressionAppliedPerBand = false;
417 188 : if (dialect == "builtin")
418 : {
419 42 : expressionAppliedPerBand = !flatten;
420 : }
421 : else
422 : {
423 146 : const int nDefaultInBand = std::min(props.nBands, nOutBand);
424 :
425 146 : if (flatten)
426 : {
427 32 : bandExpression = SetBandIndicesFlattenedExpression(
428 32 : bandExpression, source_name, props.nBands);
429 : }
430 :
431 : bandExpression =
432 292 : SetBandIndices(bandExpression, source_name, nDefaultInBand,
433 146 : expressionAppliedPerBand);
434 : }
435 :
436 188 : if (expressionAppliedPerBand)
437 : {
438 134 : if (nOutBands <= 1)
439 : {
440 93 : nOutBands = props.nBands;
441 : }
442 41 : else if (props.nBands != 1 && props.nBands != nOutBands)
443 : {
444 3 : CPLError(CE_Failure, CPLE_AppDefined,
445 : "Expression cannot operate on all bands of "
446 : "rasters with incompatible numbers of bands "
447 : "(source %s has %d bands but expected to have "
448 : "1 or %d bands).",
449 3 : source_name.c_str(), props.nBands, nOutBands);
450 4 : return false;
451 : }
452 : }
453 :
454 : // Create a source for each input band that is used in
455 : // the expression.
456 513 : for (int nInBand = 1; nInBand <= props.nBands; nInBand++)
457 : {
458 328 : CPLString inBandVariable;
459 328 : if (dialect == "builtin")
460 : {
461 72 : if (!flatten && props.nBands >= 2 && nInBand != nOutBand)
462 11 : continue;
463 : }
464 : else
465 : {
466 : inBandVariable.Printf("%s[%d]", source_name.c_str(),
467 256 : nInBand);
468 256 : if (bandExpression.find(inBandVariable) ==
469 : std::string::npos)
470 : {
471 79 : continue;
472 : }
473 : }
474 :
475 : const std::optional<double> &srcNoData =
476 238 : props.noData[nInBand - 1];
477 :
478 238 : CPLXMLNode *source = CPLCreateXMLNode(
479 : band, CXT_Element,
480 238 : srcNoData.has_value() ? "ComplexSource" : "SimpleSource");
481 238 : if (!inBandVariable.empty())
482 : {
483 177 : CPLAddXMLAttributeAndValue(source, "name",
484 : inBandVariable.c_str());
485 : }
486 :
487 : CPLXMLNode *sourceFilename =
488 238 : CPLCreateXMLNode(source, CXT_Element, "SourceFilename");
489 238 : if (fakeSourceFilename.empty())
490 : {
491 330 : std::string osSourceFilename = dsn;
492 165 : bool bRelativeToVRT = false;
493 165 : if (pszVRTFilename[0])
494 : {
495 16 : std::tie(osSourceFilename, bRelativeToVRT) =
496 32 : VRTSimpleSource::ComputeSourceNameAndRelativeFlag(
497 48 : CPLGetPathSafe(pszVRTFilename).c_str(), dsn);
498 : }
499 165 : CPLAddXMLAttributeAndValue(sourceFilename, "relativeToVRT",
500 : bRelativeToVRT ? "1" : "0");
501 165 : CPLCreateXMLNode(sourceFilename, CXT_Text,
502 : osSourceFilename.c_str());
503 : }
504 : else
505 : {
506 73 : CPLCreateXMLNode(sourceFilename, CXT_Text,
507 : fakeSourceFilename.c_str());
508 : }
509 :
510 : CPLXMLNode *sourceBand =
511 238 : CPLCreateXMLNode(source, CXT_Element, "SourceBand");
512 238 : CPLCreateXMLNode(sourceBand, CXT_Text,
513 476 : std::to_string(nInBand).c_str());
514 :
515 238 : if (srcNoData.has_value())
516 : {
517 : CPLXMLNode *srcNoDataNode =
518 17 : CPLCreateXMLNode(source, CXT_Element, "NODATA");
519 : std::string srcNoDataText =
520 34 : CPLSPrintf("%.17g", srcNoData.value());
521 17 : CPLCreateXMLNode(srcNoDataNode, CXT_Text,
522 : srcNoDataText.c_str());
523 :
524 17 : if (autoSelectNoDataValue && !dstNoData.has_value())
525 : {
526 8 : dstNoData = srcNoData;
527 : }
528 : }
529 :
530 238 : if (fakeSourceFilename.empty())
531 : {
532 : CPLXMLNode *srcRect =
533 165 : CPLCreateXMLNode(source, CXT_Element, "SrcRect");
534 165 : CPLAddXMLAttributeAndValue(srcRect, "xOff", "0");
535 165 : CPLAddXMLAttributeAndValue(srcRect, "yOff", "0");
536 165 : CPLAddXMLAttributeAndValue(
537 330 : srcRect, "xSize", std::to_string(props.nX).c_str());
538 165 : CPLAddXMLAttributeAndValue(
539 330 : srcRect, "ySize", std::to_string(props.nY).c_str());
540 :
541 : CPLXMLNode *dstRect =
542 165 : CPLCreateXMLNode(source, CXT_Element, "DstRect");
543 165 : CPLAddXMLAttributeAndValue(dstRect, "xOff", "0");
544 165 : CPLAddXMLAttributeAndValue(dstRect, "yOff", "0");
545 165 : CPLAddXMLAttributeAndValue(dstRect, "xSize",
546 330 : std::to_string(nXOut).c_str());
547 165 : CPLAddXMLAttributeAndValue(dstRect, "ySize",
548 330 : std::to_string(nYOut).c_str());
549 : }
550 : }
551 :
552 185 : if (dstNoData.has_value())
553 : {
554 17 : if (!GDALIsValueExactAs(dstNoData.value(), bandType))
555 : {
556 1 : CPLError(
557 : CE_Failure, CPLE_AppDefined,
558 : "Band output type %s cannot represent NoData value %g",
559 1 : GDALGetDataTypeName(bandType), dstNoData.value());
560 1 : return false;
561 : }
562 :
563 : CPLXMLNode *noDataNode =
564 16 : CPLCreateXMLNode(band, CXT_Element, "NoDataValue");
565 : CPLString dstNoDataText =
566 32 : CPLSPrintf("%.17g", dstNoData.value());
567 16 : CPLCreateXMLNode(noDataNode, CXT_Text, dstNoDataText.c_str());
568 : }
569 : }
570 :
571 : CPLXMLNode *pixelFunctionType =
572 139 : CPLCreateXMLNode(band, CXT_Element, "PixelFunctionType");
573 : CPLXMLNode *arguments =
574 139 : CPLCreateXMLNode(band, CXT_Element, "PixelFunctionArguments");
575 :
576 139 : if (dialect == "builtin")
577 : {
578 28 : CPLCreateXMLNode(pixelFunctionType, CXT_Text, expression.c_str());
579 : }
580 : else
581 : {
582 111 : CPLCreateXMLNode(pixelFunctionType, CXT_Text, "expression");
583 111 : CPLAddXMLAttributeAndValue(arguments, "dialect", "muparser");
584 : // Add the expression as a last step, because we may modify the
585 : // expression as we iterate through the bands.
586 111 : CPLAddXMLAttributeAndValue(arguments, "expression",
587 : bandExpression.c_str());
588 : }
589 :
590 139 : if (!pixelFunctionArguments.empty())
591 : {
592 16 : const CPLStringList args(pixelFunctionArguments);
593 16 : for (const auto &[key, value] : cpl::IterateNameValue(args))
594 : {
595 8 : CPLAddXMLAttributeAndValue(arguments, key, value);
596 : }
597 : }
598 : }
599 :
600 112 : return true;
601 : }
602 :
603 122 : static bool ParseSourceDescriptors(const std::vector<std::string> &inputs,
604 : std::map<std::string, std::string> &datasets,
605 : std::string &firstSourceName,
606 : bool requireSourceNames)
607 : {
608 281 : for (size_t iInput = 0; iInput < inputs.size(); iInput++)
609 : {
610 164 : const std::string &input = inputs[iInput];
611 164 : std::string name;
612 :
613 164 : const auto pos = input.find('=');
614 164 : if (pos == std::string::npos)
615 : {
616 61 : if (requireSourceNames && inputs.size() > 1)
617 : {
618 1 : CPLError(CE_Failure, CPLE_AppDefined,
619 : "Inputs must be named when more than one input is "
620 : "provided.");
621 1 : return false;
622 : }
623 60 : name = "X";
624 60 : if (iInput > 0)
625 : {
626 2 : name += std::to_string(iInput);
627 : }
628 : }
629 : else
630 : {
631 103 : name = input.substr(0, pos);
632 : }
633 :
634 : // Check input name is legal
635 347 : for (size_t i = 0; i < name.size(); ++i)
636 : {
637 187 : const char c = name[i];
638 187 : if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
639 : {
640 : // ok
641 : }
642 20 : else if (c == '_' || (c >= '0' && c <= '9'))
643 : {
644 19 : if (i == 0)
645 : {
646 : // Reserved constants in MuParser start with an underscore
647 2 : CPLError(
648 : CE_Failure, CPLE_AppDefined,
649 : "Name '%s' is illegal because it starts with a '%c'",
650 : name.c_str(), c);
651 2 : return false;
652 : }
653 : }
654 : else
655 : {
656 1 : CPLError(CE_Failure, CPLE_AppDefined,
657 : "Name '%s' is illegal because character '%c' is not "
658 : "allowed",
659 : name.c_str(), c);
660 1 : return false;
661 : }
662 : }
663 :
664 : std::string dsn =
665 160 : (pos == std::string::npos) ? input : input.substr(pos + 1);
666 :
667 160 : if (!dsn.empty() && dsn.front() == '[' && dsn.back() == ']')
668 : {
669 : dsn = "{\"type\":\"gdal_streamed_alg\", \"command_line\":\"gdal "
670 0 : "raster pipeline " +
671 2 : CPLString(dsn.substr(1, dsn.size() - 2))
672 2 : .replaceAll('\\', "\\\\")
673 2 : .replaceAll('"', "\\\"") +
674 1 : "\"}";
675 : }
676 :
677 160 : if (datasets.find(name) != datasets.end())
678 : {
679 1 : CPLError(CE_Failure, CPLE_AppDefined,
680 : "An input with name '%s' has already been provided",
681 : name.c_str());
682 1 : return false;
683 : }
684 159 : datasets[name] = std::move(dsn);
685 :
686 159 : if (iInput == 0)
687 : {
688 118 : firstSourceName = std::move(name);
689 : }
690 : }
691 :
692 117 : return true;
693 : }
694 :
695 90 : static bool ReadFileLists(const std::vector<GDALArgDatasetValue> &inputDS,
696 : std::vector<std::string> &inputFilenames)
697 : {
698 212 : for (const auto &dsVal : inputDS)
699 : {
700 122 : const auto &input = dsVal.GetName();
701 122 : if (!input.empty() && input[0] == '@')
702 : {
703 : auto f =
704 2 : VSIVirtualHandleUniquePtr(VSIFOpenL(input.c_str() + 1, "r"));
705 2 : if (!f)
706 : {
707 0 : CPLError(CE_Failure, CPLE_FileIO, "Cannot open %s",
708 0 : input.c_str() + 1);
709 0 : return false;
710 : }
711 6 : while (const char *filename = CPLReadLineL(f.get()))
712 : {
713 4 : inputFilenames.push_back(filename);
714 4 : }
715 : }
716 : else
717 : {
718 120 : inputFilenames.push_back(input);
719 : }
720 : }
721 :
722 90 : return true;
723 : }
724 :
725 : /** Creates a VRT datasource with one or more derived raster bands containing
726 : * results of an expression.
727 : *
728 : * To make this work with muparser (which does not support vector types), we
729 : * do a simple parsing of the expression internally, transforming it into
730 : * multiple expressions with explicit band indices. For example, for a two-band
731 : * raster "X", the expression "X + 3" will be transformed into "X[1] + 3" and
732 : * "X[2] + 3". The use of brackets is for readability only; as far as the
733 : * expression engine is concerned, the variables "X[1]" and "X[2]" have nothing
734 : * to do with each other.
735 : *
736 : * @param pszVRTFilename VRT filename
737 : * @param inputs A list of sources, expressed as NAME=DSN
738 : * @param expressions A list of expressions to be evaluated
739 : * @param dialect Expression dialect
740 : * @param flatten Generate a single band output raster per expression, even if
741 : * input datasets are multiband.
742 : * @param noData NoData values to use for output bands, or "none", or ""
743 : * @param pixelFunctionArguments Pixel function arguments.
744 : * @param options flags controlling which checks should be performed on the inputs
745 : * @param[out] maxSourceBands Maximum number of bands in source dataset(s)
746 : * @param fakeSourceFilename If not empty, used instead of real input filenames.
747 : *
748 : * @return a newly created VRTDataset, or nullptr on error
749 : */
750 122 : static std::unique_ptr<GDALDataset> GDALCalcCreateVRTDerived(
751 : const char *pszVRTFilename, const std::vector<std::string> &inputs,
752 : const std::vector<std::string> &expressions, const std::string &dialect,
753 : bool flatten, const std::string &noData,
754 : const std::vector<std::vector<std::string>> &pixelFunctionArguments,
755 : const GDALCalcOptions &options, int &maxSourceBands,
756 : const std::string &fakeSourceFilename = std::string())
757 : {
758 122 : if (inputs.empty())
759 : {
760 0 : return nullptr;
761 : }
762 :
763 244 : std::map<std::string, std::string> sources;
764 244 : std::string firstSource;
765 122 : bool requireSourceNames = dialect != "builtin";
766 122 : if (!ParseSourceDescriptors(inputs, sources, firstSource,
767 : requireSourceNames))
768 : {
769 5 : return nullptr;
770 : }
771 :
772 : // Use the first source provided to determine properties of the output
773 117 : const char *firstDSN = sources[firstSource].c_str();
774 :
775 117 : maxSourceBands = 0;
776 :
777 : // Read properties from the first source
778 234 : SourceProperties out;
779 : {
780 : std::unique_ptr<GDALDataset> ds(
781 117 : GDALDataset::Open(firstDSN, GDAL_OF_RASTER));
782 :
783 117 : if (!ds)
784 : {
785 0 : CPLError(CE_Failure, CPLE_AppDefined, "Failed to open %s",
786 : firstDSN);
787 0 : return nullptr;
788 : }
789 :
790 117 : out.nX = ds->GetRasterXSize();
791 117 : out.nY = ds->GetRasterYSize();
792 117 : out.nBands = 1;
793 117 : out.srs.reset(ds->GetSpatialRef() ? ds->GetSpatialRef()->Clone()
794 : : nullptr);
795 117 : out.hasGT = ds->GetGeoTransform(out.gt) == CE_None;
796 : }
797 :
798 234 : CPLXMLTreeCloser root(CPLCreateXMLNode(nullptr, CXT_Element, "VRTDataset"));
799 :
800 117 : maxSourceBands = 0;
801 :
802 : // Collect properties of the different sources, and verity them for
803 : // consistency.
804 234 : std::map<std::string, SourceProperties> sourceProps;
805 269 : for (const auto &[source_name, dsn] : sources)
806 : {
807 : // TODO avoid opening the first source twice.
808 156 : auto props = UpdateSourceProperties(out, dsn, options);
809 156 : if (props.has_value())
810 : {
811 152 : maxSourceBands = std::max(maxSourceBands, props->nBands);
812 152 : sourceProps[source_name] = std::move(props.value());
813 : }
814 : else
815 : {
816 4 : return nullptr;
817 : }
818 : }
819 :
820 113 : size_t iExpr = 0;
821 225 : for (const auto &origExpression : expressions)
822 : {
823 116 : GDALDataType bandType = options.dstType;
824 :
825 : // If output band type has not been specified, set it equal to the
826 : // input band type for certain pixel functions, if the inputs have
827 : // a consistent band type.
828 166 : if (bandType == GDT_Unknown && dialect == "builtin" &&
829 72 : (origExpression == "min" || origExpression == "max" ||
830 22 : origExpression == "mode"))
831 : {
832 12 : for (const auto &[_, props] : sourceProps)
833 : {
834 6 : if (bandType == GDT_Unknown)
835 : {
836 6 : bandType = props.eDT;
837 : }
838 0 : else if (props.eDT == GDT_Unknown || props.eDT != bandType)
839 : {
840 0 : bandType = GDT_Unknown;
841 0 : break;
842 : }
843 : }
844 : }
845 :
846 116 : if (!CreateDerivedBandXML(pszVRTFilename, root.get(), out.nX, out.nY,
847 : bandType, origExpression, dialect, flatten,
848 116 : noData, pixelFunctionArguments[iExpr],
849 : sources, sourceProps, fakeSourceFilename))
850 : {
851 4 : return nullptr;
852 : }
853 112 : ++iExpr;
854 : }
855 :
856 : // CPLDebug("VRT", "%s", CPLSerializeXMLTree(root.get()));
857 :
858 109 : auto ds = fakeSourceFilename.empty()
859 : ? std::make_unique<VRTDataset>(out.nX, out.nY)
860 218 : : std::make_unique<VRTDataset>(1, 1);
861 218 : if (ds->XMLInit(root.get(), pszVRTFilename[0]
862 126 : ? CPLGetPathSafe(pszVRTFilename).c_str()
863 218 : : "") != CE_None)
864 : {
865 0 : return nullptr;
866 : };
867 109 : if (out.hasGT)
868 : {
869 57 : ds->SetGeoTransform(out.gt);
870 : }
871 109 : if (out.srs)
872 : {
873 55 : ds->SetSpatialRef(out.srs.get());
874 : }
875 :
876 109 : return ds;
877 : }
878 :
879 : /************************************************************************/
880 : /* GDALRasterCalcAlgorithm::GDALRasterCalcAlgorithm() */
881 : /************************************************************************/
882 :
883 170 : GDALRasterCalcAlgorithm::GDALRasterCalcAlgorithm(bool standaloneStep) noexcept
884 : : GDALRasterPipelineStepAlgorithm(NAME, DESCRIPTION, HELP_URL,
885 510 : ConstructorOptions()
886 170 : .SetStandaloneStep(standaloneStep)
887 170 : .SetAddDefaultArguments(false)
888 170 : .SetAutoOpenInputDatasets(false)
889 340 : .SetInputDatasetMetaVar("INPUTS")
890 510 : .SetInputDatasetMaxCount(INT_MAX))
891 : {
892 170 : AddRasterInputArgs(false, false);
893 170 : if (standaloneStep)
894 : {
895 132 : AddProgressArg();
896 132 : AddRasterOutputArgs(false);
897 : }
898 :
899 170 : AddOutputDataTypeArg(&m_type);
900 :
901 : AddArg("no-check-crs", 0,
902 : _("Do not check consistency of input coordinate reference systems"),
903 340 : &m_noCheckCRS)
904 170 : .AddHiddenAlias("no-check-srs");
905 : AddArg("no-check-extent", 0, _("Do not check consistency of input extents"),
906 170 : &m_noCheckExtent);
907 :
908 : AddArg("propagate-nodata", 0,
909 : _("Whether to set pixels to the output NoData value if any of the "
910 : "input pixels is NoData"),
911 170 : &m_propagateNoData);
912 :
913 340 : AddArg("calc", 0, _("Expression(s) to evaluate"), &m_expr)
914 170 : .SetRequired()
915 170 : .SetPackedValuesAllowed(false)
916 170 : .SetMinCount(1)
917 : .SetAutoCompleteFunction(
918 4 : [this](const std::string ¤tValue)
919 : {
920 4 : std::vector<std::string> ret;
921 2 : if (m_dialect == "builtin")
922 : {
923 1 : if (currentValue.find('(') == std::string::npos)
924 1 : return VRTDerivedRasterBand::GetPixelFunctionNames();
925 : }
926 1 : return ret;
927 170 : });
928 :
929 340 : AddArg("dialect", 0, _("Expression dialect"), &m_dialect)
930 170 : .SetDefault(m_dialect)
931 170 : .SetChoices("muparser", "builtin");
932 :
933 : AddArg("flatten", 0,
934 : _("Generate a single band output raster per expression, even if "
935 : "input datasets are multiband"),
936 170 : &m_flatten);
937 :
938 170 : AddNodataArg(&m_nodata, true);
939 :
940 : // This is a hidden option only used by test_gdalalg_raster_calc_expression_rewriting()
941 : // for now
942 : AddArg("no-check-expression", 0,
943 : _("Whether to skip expression validity checks for virtual format "
944 : "output"),
945 340 : &m_noCheckExpression)
946 170 : .SetHidden();
947 :
948 170 : AddValidationAction(
949 178 : [this]()
950 : {
951 94 : GDALPipelineStepRunContext ctxt;
952 94 : return m_noCheckExpression || !IsGDALGOutput() || RunStep(ctxt);
953 : });
954 170 : }
955 :
956 : /************************************************************************/
957 : /* GDALRasterCalcAlgorithm::RunImpl() */
958 : /************************************************************************/
959 :
960 85 : bool GDALRasterCalcAlgorithm::RunImpl(GDALProgressFunc pfnProgress,
961 : void *pProgressData)
962 : {
963 85 : GDALPipelineStepRunContext stepCtxt;
964 85 : stepCtxt.m_pfnProgress = pfnProgress;
965 85 : stepCtxt.m_pProgressData = pProgressData;
966 85 : return RunPreStepPipelineValidations() && RunStep(stepCtxt);
967 : }
968 :
969 : /************************************************************************/
970 : /* GDALRasterCalcAlgorithm::RunStep() */
971 : /************************************************************************/
972 :
973 90 : bool GDALRasterCalcAlgorithm::RunStep(GDALPipelineStepRunContext &ctxt)
974 : {
975 90 : CPLAssert(!m_outputDataset.GetDatasetRef());
976 :
977 90 : GDALCalcOptions options;
978 90 : options.checkExtent = !m_noCheckExtent;
979 90 : options.checkCRS = !m_noCheckCRS;
980 90 : if (!m_type.empty())
981 : {
982 5 : options.dstType = GDALGetDataTypeByName(m_type.c_str());
983 : }
984 :
985 180 : std::vector<std::string> inputFilenames;
986 90 : if (!ReadFileLists(m_inputDataset, inputFilenames))
987 : {
988 0 : return false;
989 : }
990 :
991 180 : std::vector<std::vector<std::string>> pixelFunctionArgs;
992 90 : if (m_dialect == "builtin")
993 : {
994 27 : for (std::string &expr : m_expr)
995 : {
996 : const CPLStringList aosTokens(
997 : CSLTokenizeString2(expr.c_str(), "()",
998 14 : CSLT_STRIPLEADSPACES | CSLT_STRIPENDSPACES));
999 14 : const char *pszFunction = aosTokens[0];
1000 : const auto *pair =
1001 14 : VRTDerivedRasterBand::GetPixelFunction(pszFunction);
1002 14 : if (!pair)
1003 : {
1004 0 : ReportError(CE_Failure, CPLE_NotSupported,
1005 : "'%s' is a unknown builtin function", pszFunction);
1006 0 : return false;
1007 : }
1008 14 : if (aosTokens.size() == 2)
1009 : {
1010 2 : std::vector<std::string> validArguments;
1011 2 : AddOptionsSuggestions(pair->second.c_str(), 0, std::string(),
1012 : validArguments);
1013 6 : for (std::string &s : validArguments)
1014 : {
1015 4 : if (!s.empty() && s.back() == '=')
1016 4 : s.pop_back();
1017 : }
1018 :
1019 : const CPLStringList aosTokensArgs(CSLTokenizeString2(
1020 : aosTokens[1], ",",
1021 2 : CSLT_STRIPLEADSPACES | CSLT_STRIPENDSPACES));
1022 4 : for (const auto &[key, value] :
1023 6 : cpl::IterateNameValue(aosTokensArgs))
1024 : {
1025 2 : if (std::find(validArguments.begin(), validArguments.end(),
1026 2 : key) == validArguments.end())
1027 : {
1028 0 : if (validArguments.empty())
1029 : {
1030 0 : ReportError(
1031 : CE_Failure, CPLE_IllegalArg,
1032 : "'%s' is a unrecognized argument for builtin "
1033 : "function '%s'. It does not accept any "
1034 : "argument",
1035 : key, pszFunction);
1036 : }
1037 : else
1038 : {
1039 0 : std::string validArgumentsStr;
1040 0 : for (const std::string &s : validArguments)
1041 : {
1042 0 : if (!validArgumentsStr.empty())
1043 0 : validArgumentsStr += ", ";
1044 0 : validArgumentsStr += '\'';
1045 0 : validArgumentsStr += s;
1046 0 : validArgumentsStr += '\'';
1047 : }
1048 0 : ReportError(
1049 : CE_Failure, CPLE_IllegalArg,
1050 : "'%s' is a unrecognized argument for builtin "
1051 : "function '%s'. Only %s %s supported",
1052 : key, pszFunction,
1053 0 : validArguments.size() == 1 ? "is" : "are",
1054 : validArgumentsStr.c_str());
1055 : }
1056 0 : return false;
1057 : }
1058 2 : CPL_IGNORE_RET_VAL(value);
1059 : }
1060 2 : pixelFunctionArgs.emplace_back(aosTokensArgs);
1061 : }
1062 : else
1063 : {
1064 12 : pixelFunctionArgs.push_back(std::vector<std::string>());
1065 : }
1066 14 : expr = pszFunction;
1067 : }
1068 : }
1069 : else
1070 : {
1071 77 : pixelFunctionArgs.resize(m_expr.size());
1072 : }
1073 :
1074 90 : if (m_propagateNoData)
1075 : {
1076 2 : if (m_nodata == "none")
1077 : {
1078 0 : ReportError(CE_Failure, CPLE_AppDefined,
1079 : "Output NoData value must be specified to use "
1080 : "--propagate-nodata");
1081 0 : return false;
1082 : }
1083 4 : for (auto &args : pixelFunctionArgs)
1084 : {
1085 2 : args.push_back("propagateNoData=1");
1086 : }
1087 : }
1088 :
1089 90 : int maxSourceBands = 0;
1090 : const bool bIsVRT =
1091 230 : m_format == "VRT" ||
1092 89 : (m_format.empty() &&
1093 102 : EQUAL(CPLGetExtensionSafe(m_outputDataset.GetName().c_str()).c_str(),
1094 90 : "VRT"));
1095 :
1096 : auto vrt = GDALCalcCreateVRTDerived(
1097 19 : bIsVRT ? m_outputDataset.GetName().c_str() : "", inputFilenames, m_expr,
1098 90 : m_dialect, m_flatten, m_nodata, pixelFunctionArgs, options,
1099 199 : maxSourceBands);
1100 90 : if (vrt == nullptr)
1101 : {
1102 13 : return false;
1103 : }
1104 :
1105 77 : if (!m_noCheckExpression)
1106 : {
1107 : const bool bIsGDALG =
1108 157 : m_format == "GDALG" ||
1109 63 : (m_format.empty() &&
1110 30 : cpl::ends_with(m_outputDataset.GetName(), ".gdalg.json"));
1111 64 : if (!m_standaloneStep || m_format == "stream" || bIsVRT || bIsGDALG)
1112 : {
1113 : // Try reading a single pixel to check formulas are valid.
1114 32 : std::vector<GByte> dummyData(vrt->GetRasterCount());
1115 :
1116 32 : auto poGTIFFDrv = GetGDALDriverManager()->GetDriverByName("GTiff");
1117 32 : std::string osTmpFilename;
1118 32 : if (poGTIFFDrv)
1119 : {
1120 : std::string osFilename =
1121 64 : VSIMemGenerateHiddenFilename("tmp.tif");
1122 : auto poDS = std::unique_ptr<GDALDataset>(
1123 : poGTIFFDrv->Create(osFilename.c_str(), 1, 1, maxSourceBands,
1124 64 : GDT_UInt8, nullptr));
1125 32 : if (poDS)
1126 32 : osTmpFilename = std::move(osFilename);
1127 : }
1128 32 : if (!osTmpFilename.empty())
1129 : {
1130 : auto fakeVRT = GDALCalcCreateVRTDerived(
1131 32 : "", inputFilenames, m_expr, m_dialect, m_flatten, m_nodata,
1132 32 : pixelFunctionArgs, options, maxSourceBands, osTmpFilename);
1133 64 : if (fakeVRT &&
1134 32 : fakeVRT->RasterIO(GF_Read, 0, 0, 1, 1, dummyData.data(), 1,
1135 : 1, GDT_UInt8, vrt->GetRasterCount(),
1136 32 : nullptr, 0, 0, 0, nullptr) != CE_None)
1137 : {
1138 5 : return false;
1139 : }
1140 : }
1141 27 : if (bIsGDALG)
1142 : {
1143 1 : return true;
1144 : }
1145 : }
1146 : }
1147 :
1148 71 : if (m_format == "stream" || !m_standaloneStep)
1149 : {
1150 24 : m_outputDataset.Set(std::move(vrt));
1151 24 : return true;
1152 : }
1153 :
1154 94 : CPLStringList translateArgs;
1155 47 : if (!m_format.empty())
1156 : {
1157 9 : translateArgs.AddString("-of");
1158 9 : translateArgs.AddString(m_format.c_str());
1159 : }
1160 48 : for (const auto &co : m_creationOptions)
1161 : {
1162 1 : translateArgs.AddString("-co");
1163 1 : translateArgs.AddString(co.c_str());
1164 : }
1165 :
1166 : GDALTranslateOptions *translateOptions =
1167 47 : GDALTranslateOptionsNew(translateArgs.List(), nullptr);
1168 47 : GDALTranslateOptionsSetProgress(translateOptions, ctxt.m_pfnProgress,
1169 : ctxt.m_pProgressData);
1170 :
1171 : auto poOutDS =
1172 : std::unique_ptr<GDALDataset>(GDALDataset::FromHandle(GDALTranslate(
1173 47 : m_outputDataset.GetName().c_str(), GDALDataset::ToHandle(vrt.get()),
1174 94 : translateOptions, nullptr)));
1175 47 : GDALTranslateOptionsFree(translateOptions);
1176 :
1177 47 : const bool bOK = poOutDS != nullptr;
1178 47 : m_outputDataset.Set(std::move(poOutDS));
1179 :
1180 47 : return bOK;
1181 : }
1182 :
1183 : GDALRasterCalcAlgorithmStandalone::~GDALRasterCalcAlgorithmStandalone() =
1184 : default;
1185 :
1186 : //! @endcond
|