Line data Source code
1 : /******************************************************************************
2 : *
3 : * Project: GDAL Utilities
4 : * Purpose: Command line application to convert a multidimensional raster
5 : * Author: Even Rouault,<even.rouault at spatialys.com>
6 : *
7 : * ****************************************************************************
8 : * Copyright (c) 2019, Even Rouault <even.rouault at spatialys.com>
9 : *
10 : * SPDX-License-Identifier: MIT
11 : ****************************************************************************/
12 :
13 : #include "cpl_port.h"
14 : #include "commonutils.h"
15 : #include "gdal_priv.h"
16 : #include "gdal_utils.h"
17 : #include "gdal_utils_priv.h"
18 : #include "gdalargumentparser.h"
19 : #include "vrtdataset.h"
20 : #include <algorithm>
21 : #include <map>
22 : #include <set>
23 :
24 : /************************************************************************/
25 : /* GDALMultiDimTranslateOptions */
26 : /************************************************************************/
27 :
28 : struct GDALMultiDimTranslateOptions
29 : {
30 : std::string osFormat{};
31 : CPLStringList aosCreateOptions{};
32 : std::vector<std::string> aosArraySpec{};
33 : CPLStringList aosArrayOptions{};
34 : std::vector<std::string> aosSubset{};
35 : std::vector<std::string> aosScaleFactor{};
36 : std::vector<std::string> aosGroup{};
37 : GDALProgressFunc pfnProgress = GDALDummyProgress;
38 : bool bStrict = false;
39 : void *pProgressData = nullptr;
40 : bool bUpdate = false;
41 : bool bOverwrite = false;
42 : bool bNoOverwrite = false;
43 : };
44 :
45 : /*************************************************************************/
46 : /* GDALMultiDimTranslateAppOptionsGetParser() */
47 : /************************************************************************/
48 :
49 : static std::unique_ptr<GDALArgumentParser>
50 123 : GDALMultiDimTranslateAppOptionsGetParser(
51 : GDALMultiDimTranslateOptions *psOptions,
52 : GDALMultiDimTranslateOptionsForBinary *psOptionsForBinary)
53 : {
54 : auto argParser = std::make_unique<GDALArgumentParser>(
55 123 : "gdalmdimtranslate", /* bForBinary=*/psOptionsForBinary != nullptr);
56 :
57 123 : argParser->add_description(
58 : _("Converts multidimensional data between different formats, and "
59 123 : "performs subsetting."));
60 :
61 123 : argParser->add_epilog(
62 : _("For more details, consult "
63 123 : "https://gdal.org/programs/gdalmdimtranslate.html"));
64 :
65 123 : if (psOptionsForBinary)
66 : {
67 : argParser->add_input_format_argument(
68 3 : &psOptionsForBinary->aosAllowInputDrivers);
69 : }
70 :
71 123 : argParser->add_output_format_argument(psOptions->osFormat);
72 :
73 123 : argParser->add_creation_options_argument(psOptions->aosCreateOptions);
74 :
75 123 : auto &group = argParser->add_mutually_exclusive_group();
76 123 : group.add_argument("-array")
77 246 : .metavar("<array_spec>")
78 123 : .append()
79 123 : .store_into(psOptions->aosArraySpec)
80 : .help(_(
81 123 : "Select a single array instead of converting the whole dataset."));
82 :
83 123 : argParser->add_argument("-arrayoption")
84 246 : .metavar("<NAME>=<VALUE>")
85 123 : .append()
86 1 : .action([psOptions](const std::string &s)
87 124 : { psOptions->aosArrayOptions.AddString(s.c_str()); })
88 : .help(_("Option passed to GDALGroup::GetMDArrayNames() to filter "
89 123 : "arrays."));
90 :
91 123 : group.add_argument("-group")
92 246 : .metavar("<group_spec>")
93 123 : .append()
94 123 : .store_into(psOptions->aosGroup)
95 : .help(_(
96 123 : "Select a single group instead of converting the whole dataset."));
97 :
98 : // Note: this is mutually exclusive with "view" option in -array
99 123 : argParser->add_argument("-subset")
100 246 : .metavar("<subset_spec>")
101 123 : .append()
102 123 : .store_into(psOptions->aosSubset)
103 123 : .help(_("Select a subset of the data."));
104 :
105 : // Note: this is mutually exclusive with "view" option in -array
106 123 : argParser->add_argument("-scaleaxes")
107 246 : .metavar("<scaleaxes_spec>")
108 : .action(
109 4 : [psOptions](const std::string &s)
110 : {
111 : CPLStringList aosScaleFactors(
112 4 : CSLTokenizeString2(s.c_str(), ",", 0));
113 4 : for (int j = 0; j < aosScaleFactors.size(); j++)
114 : {
115 2 : psOptions->aosScaleFactor.push_back(aosScaleFactors[j]);
116 : }
117 125 : })
118 : .help(
119 123 : _("Applies a integral scale factor to one or several dimensions."));
120 :
121 123 : argParser->add_argument("-strict")
122 123 : .flag()
123 123 : .store_into(psOptions->bStrict)
124 123 : .help(_("Turn warnings into failures."));
125 :
126 : // Undocumented option used by gdal mdim convert
127 123 : argParser->add_argument("--overwrite")
128 123 : .store_into(psOptions->bOverwrite)
129 123 : .hidden();
130 :
131 : // Undocumented option used by gdal mdim convert
132 123 : argParser->add_argument("--no-overwrite")
133 123 : .store_into(psOptions->bNoOverwrite)
134 123 : .hidden();
135 :
136 123 : if (psOptionsForBinary)
137 : {
138 : argParser->add_open_options_argument(
139 3 : psOptionsForBinary->aosOpenOptions);
140 :
141 3 : argParser->add_argument("src_dataset")
142 6 : .metavar("<src_dataset>")
143 3 : .store_into(psOptionsForBinary->osSource)
144 3 : .help(_("The source dataset name."));
145 :
146 3 : argParser->add_argument("dst_dataset")
147 6 : .metavar("<dst_dataset>")
148 3 : .store_into(psOptionsForBinary->osDest)
149 3 : .help(_("The destination file name."));
150 :
151 3 : argParser->add_quiet_argument(&psOptionsForBinary->bQuiet);
152 : }
153 :
154 123 : return argParser;
155 : }
156 :
157 : /************************************************************************/
158 : /* GDALMultiDimTranslateAppGetParserUsage() */
159 : /************************************************************************/
160 :
161 0 : std::string GDALMultiDimTranslateAppGetParserUsage()
162 : {
163 : try
164 : {
165 0 : GDALMultiDimTranslateOptions sOptions;
166 0 : GDALMultiDimTranslateOptionsForBinary sOptionsForBinary;
167 : auto argParser = GDALMultiDimTranslateAppOptionsGetParser(
168 0 : &sOptions, &sOptionsForBinary);
169 0 : return argParser->usage();
170 : }
171 0 : catch (const std::exception &err)
172 : {
173 0 : CPLError(CE_Failure, CPLE_AppDefined, "Unexpected exception: %s",
174 0 : err.what());
175 0 : return std::string();
176 : }
177 : }
178 :
179 : /************************************************************************/
180 : /* FindMinMaxIdxNumeric() */
181 : /************************************************************************/
182 :
183 40 : static void FindMinMaxIdxNumeric(const GDALMDArray *var, double *pdfTmp,
184 : const size_t nCount, const GUInt64 nStartIdx,
185 : const double dfMin, const double dfMax,
186 : const bool bSlice, bool &bFoundMinIdx,
187 : GUInt64 &nMinIdx, bool &bFoundMaxIdx,
188 : GUInt64 &nMaxIdx, bool &bLastWasReversed,
189 : bool &bEmpty, const double EPS)
190 : {
191 40 : if (nCount >= 2)
192 : {
193 40 : bool bReversed = false;
194 40 : if (pdfTmp[0] > pdfTmp[nCount - 1])
195 : {
196 19 : bReversed = true;
197 19 : std::reverse(pdfTmp, pdfTmp + nCount);
198 : }
199 40 : if (nStartIdx > 0 && bLastWasReversed != bReversed)
200 : {
201 0 : CPLError(CE_Failure, CPLE_AppDefined,
202 0 : "Variable %s is non monotonic", var->GetName().c_str());
203 0 : bEmpty = true;
204 0 : return;
205 : }
206 40 : bLastWasReversed = bReversed;
207 :
208 40 : if (!bFoundMinIdx)
209 : {
210 40 : if (bReversed && nStartIdx == 0 && dfMin > pdfTmp[nCount - 1])
211 : {
212 2 : bEmpty = true;
213 2 : return;
214 : }
215 38 : else if (!bReversed && dfMin < pdfTmp[0] - EPS)
216 : {
217 6 : if (bSlice)
218 : {
219 1 : bEmpty = true;
220 1 : return;
221 : }
222 5 : bFoundMinIdx = true;
223 5 : nMinIdx = nStartIdx;
224 : }
225 32 : else if (dfMin >= pdfTmp[0] - EPS &&
226 28 : dfMin <= pdfTmp[nCount - 1] + EPS)
227 : {
228 130 : for (size_t i = 0; i < nCount; i++)
229 : {
230 130 : if (dfMin <= pdfTmp[i] + EPS)
231 : {
232 26 : bFoundMinIdx = true;
233 26 : nMinIdx = nStartIdx + (bReversed ? nCount - 1 - i : i);
234 26 : break;
235 : }
236 : }
237 26 : CPLAssert(bFoundMinIdx);
238 : }
239 : }
240 37 : if (!bFoundMaxIdx)
241 : {
242 37 : if (bReversed && nStartIdx == 0 && dfMax > pdfTmp[nCount - 1])
243 : {
244 2 : if (bSlice)
245 : {
246 0 : bEmpty = true;
247 0 : return;
248 : }
249 2 : bFoundMaxIdx = true;
250 2 : nMaxIdx = 0;
251 : }
252 35 : else if (!bReversed && dfMax < pdfTmp[0] - EPS)
253 : {
254 1 : if (nStartIdx == 0)
255 : {
256 1 : bEmpty = true;
257 1 : return;
258 : }
259 0 : bFoundMaxIdx = true;
260 0 : nMaxIdx = nStartIdx - 1;
261 : }
262 34 : else if (dfMax > pdfTmp[0] - EPS &&
263 32 : dfMax <= pdfTmp[nCount - 1] + EPS)
264 : {
265 156 : for (size_t i = 1; i < nCount; i++)
266 : {
267 148 : if (dfMax <= pdfTmp[i] - EPS)
268 : {
269 18 : bFoundMaxIdx = true;
270 18 : nMaxIdx = nStartIdx +
271 18 : (bReversed ? nCount - 1 - (i - 1) : i - 1);
272 18 : break;
273 : }
274 : }
275 26 : if (!bFoundMaxIdx)
276 : {
277 8 : bFoundMaxIdx = true;
278 8 : nMaxIdx = nStartIdx + (bReversed ? 0 : nCount - 1);
279 : }
280 : }
281 : }
282 : }
283 : else
284 : {
285 0 : if (!bFoundMinIdx)
286 : {
287 0 : if (dfMin <= pdfTmp[0] + EPS)
288 : {
289 0 : bFoundMinIdx = true;
290 0 : nMinIdx = nStartIdx;
291 : }
292 0 : else if (bLastWasReversed && nStartIdx > 0)
293 : {
294 0 : bFoundMinIdx = true;
295 0 : nMinIdx = nStartIdx - 1;
296 : }
297 : }
298 0 : if (!bFoundMaxIdx)
299 : {
300 0 : if (dfMax >= pdfTmp[0] - EPS)
301 : {
302 0 : bFoundMaxIdx = true;
303 0 : nMaxIdx = nStartIdx;
304 : }
305 0 : else if (!bLastWasReversed && nStartIdx > 0)
306 : {
307 0 : bFoundMaxIdx = true;
308 0 : nMaxIdx = nStartIdx - 1;
309 : }
310 : }
311 : }
312 : }
313 :
314 : /************************************************************************/
315 : /* FindMinMaxIdxString() */
316 : /************************************************************************/
317 :
318 40 : static void FindMinMaxIdxString(const GDALMDArray *var, const char **ppszTmp,
319 : const size_t nCount, const GUInt64 nStartIdx,
320 : const std::string &osMin,
321 : const std::string &osMax, const bool bSlice,
322 : bool &bFoundMinIdx, GUInt64 &nMinIdx,
323 : bool &bFoundMaxIdx, GUInt64 &nMaxIdx,
324 : bool &bLastWasReversed, bool &bEmpty)
325 : {
326 40 : bool bFoundNull = false;
327 200 : for (size_t i = 0; i < nCount; i++)
328 : {
329 160 : if (ppszTmp[i] == nullptr)
330 : {
331 0 : bFoundNull = true;
332 0 : break;
333 : }
334 : }
335 40 : if (bFoundNull)
336 : {
337 0 : CPLError(CE_Failure, CPLE_AppDefined,
338 0 : "Variable %s contains null strings", var->GetName().c_str());
339 0 : bEmpty = true;
340 0 : return;
341 : }
342 40 : if (nCount >= 2)
343 : {
344 40 : bool bReversed = false;
345 40 : if (std::string(ppszTmp[0]) > std::string(ppszTmp[nCount - 1]))
346 : {
347 19 : bReversed = true;
348 19 : std::reverse(ppszTmp, ppszTmp + nCount);
349 : }
350 40 : if (nStartIdx > 0 && bLastWasReversed != bReversed)
351 : {
352 0 : CPLError(CE_Failure, CPLE_AppDefined,
353 0 : "Variable %s is non monotonic", var->GetName().c_str());
354 0 : bEmpty = true;
355 0 : return;
356 : }
357 40 : bLastWasReversed = bReversed;
358 :
359 40 : if (!bFoundMinIdx)
360 : {
361 59 : if (bReversed && nStartIdx == 0 &&
362 59 : osMin > std::string(ppszTmp[nCount - 1]))
363 : {
364 2 : bEmpty = true;
365 2 : return;
366 : }
367 38 : else if (!bReversed && osMin < std::string(ppszTmp[0]))
368 : {
369 5 : if (bSlice)
370 : {
371 1 : bEmpty = true;
372 1 : return;
373 : }
374 4 : bFoundMinIdx = true;
375 4 : nMinIdx = nStartIdx;
376 : }
377 94 : else if (osMin >= std::string(ppszTmp[0]) &&
378 61 : osMin <= std::string(ppszTmp[nCount - 1]))
379 : {
380 68 : for (size_t i = 0; i < nCount; i++)
381 : {
382 68 : if (osMin <= std::string(ppszTmp[i]))
383 : {
384 26 : bFoundMinIdx = true;
385 26 : nMinIdx = nStartIdx + (bReversed ? nCount - 1 - i : i);
386 26 : break;
387 : }
388 : }
389 26 : CPLAssert(bFoundMinIdx);
390 : }
391 : }
392 37 : if (!bFoundMaxIdx)
393 : {
394 54 : if (bReversed && nStartIdx == 0 &&
395 54 : osMax > std::string(ppszTmp[nCount - 1]))
396 : {
397 3 : if (bSlice)
398 : {
399 0 : bEmpty = true;
400 0 : return;
401 : }
402 3 : bFoundMaxIdx = true;
403 3 : nMaxIdx = 0;
404 : }
405 34 : else if (!bReversed && osMax < std::string(ppszTmp[0]))
406 : {
407 1 : if (nStartIdx == 0)
408 : {
409 1 : bEmpty = true;
410 1 : return;
411 : }
412 0 : bFoundMaxIdx = true;
413 0 : nMaxIdx = nStartIdx - 1;
414 : }
415 33 : else if (osMax == std::string(ppszTmp[0]))
416 : {
417 6 : bFoundMaxIdx = true;
418 6 : nMaxIdx = nStartIdx + (bReversed ? nCount - 1 : 0);
419 : }
420 79 : else if (osMax > std::string(ppszTmp[0]) &&
421 52 : osMax <= std::string(ppszTmp[nCount - 1]))
422 : {
423 42 : for (size_t i = 1; i < nCount; i++)
424 : {
425 42 : if (osMax <= std::string(ppszTmp[i]))
426 : {
427 20 : bFoundMaxIdx = true;
428 20 : if (osMax == std::string(ppszTmp[i]))
429 16 : nMaxIdx =
430 16 : nStartIdx + (bReversed ? nCount - 1 - i : i);
431 : else
432 4 : nMaxIdx =
433 4 : nStartIdx +
434 4 : (bReversed ? nCount - 1 - (i - 1) : i - 1);
435 20 : break;
436 : }
437 : }
438 20 : CPLAssert(bFoundMaxIdx);
439 : }
440 : }
441 : }
442 : else
443 : {
444 0 : if (!bFoundMinIdx)
445 : {
446 0 : if (osMin <= std::string(ppszTmp[0]))
447 : {
448 0 : bFoundMinIdx = true;
449 0 : nMinIdx = nStartIdx;
450 : }
451 0 : else if (bLastWasReversed && nStartIdx > 0)
452 : {
453 0 : bFoundMinIdx = true;
454 0 : nMinIdx = nStartIdx - 1;
455 : }
456 : }
457 0 : if (!bFoundMaxIdx)
458 : {
459 0 : if (osMax >= std::string(ppszTmp[0]))
460 : {
461 0 : bFoundMaxIdx = true;
462 0 : nMaxIdx = nStartIdx;
463 : }
464 0 : else if (!bLastWasReversed && nStartIdx > 0)
465 : {
466 0 : bFoundMaxIdx = true;
467 0 : nMaxIdx = nStartIdx - 1;
468 : }
469 : }
470 : }
471 : }
472 :
473 : /************************************************************************/
474 : /* GetDimensionDesc() */
475 : /************************************************************************/
476 :
477 : struct DimensionDesc
478 : {
479 : GUInt64 nStartIdx = 0;
480 : GUInt64 nStep = 1;
481 : GUInt64 nSize = 0;
482 : GUInt64 nOriSize = 0;
483 : bool bSlice = false;
484 : };
485 :
486 : struct DimensionRemapper
487 : {
488 : std::map<std::string, DimensionDesc> oMap{};
489 : };
490 :
491 : static const DimensionDesc *
492 207 : GetDimensionDesc(DimensionRemapper &oDimRemapper,
493 : const GDALMultiDimTranslateOptions *psOptions,
494 : const std::shared_ptr<GDALDimension> &poDim)
495 : {
496 414 : std::string osKey(poDim->GetFullName());
497 : osKey +=
498 207 : CPLSPrintf("_" CPL_FRMT_GUIB, static_cast<GUIntBig>(poDim->GetSize()));
499 207 : auto oIter = oDimRemapper.oMap.find(osKey);
500 317 : if (oIter != oDimRemapper.oMap.end() &&
501 110 : oIter->second.nOriSize == poDim->GetSize())
502 : {
503 110 : return &(oIter->second);
504 : }
505 97 : DimensionDesc desc;
506 97 : desc.nSize = poDim->GetSize();
507 97 : desc.nOriSize = desc.nSize;
508 :
509 194 : CPLString osRadix(poDim->GetName());
510 97 : osRadix += '(';
511 107 : for (const auto &subset : psOptions->aosSubset)
512 : {
513 93 : if (STARTS_WITH(subset.c_str(), osRadix.c_str()))
514 : {
515 83 : auto var = poDim->GetIndexingVariable();
516 166 : if (!var || var->GetDimensionCount() != 1 ||
517 83 : var->GetDimensions()[0]->GetSize() != poDim->GetSize())
518 : {
519 0 : CPLError(CE_Failure, CPLE_AppDefined,
520 : "Dimension %s has a subset specification, but lacks "
521 : "a single dimension indexing variable",
522 0 : poDim->GetName().c_str());
523 0 : return nullptr;
524 : }
525 83 : if (subset.back() != ')')
526 : {
527 2 : CPLError(CE_Failure, CPLE_AppDefined,
528 : "Missing ')' in subset specification.");
529 2 : return nullptr;
530 : }
531 : CPLStringList aosTokens(CSLTokenizeString2(
532 : subset
533 81 : .substr(osRadix.size(), subset.size() - 1 - osRadix.size())
534 : .c_str(),
535 81 : ",", CSLT_HONOURSTRINGS));
536 81 : if (aosTokens.size() == 1)
537 : {
538 26 : desc.bSlice = true;
539 : }
540 81 : if (aosTokens.size() != 1 && aosTokens.size() != 2)
541 : {
542 1 : CPLError(CE_Failure, CPLE_AppDefined,
543 : "Invalid number of values in subset specification.");
544 1 : return nullptr;
545 : }
546 :
547 : const bool bIsNumeric =
548 80 : var->GetDataType().GetClass() == GEDTC_NUMERIC;
549 : const GDALExtendedDataType dt(
550 : bIsNumeric ? GDALExtendedDataType::Create(GDT_Float64)
551 80 : : GDALExtendedDataType::CreateString());
552 :
553 80 : double dfMin = 0;
554 80 : double dfMax = 0;
555 80 : std::string osMin;
556 80 : std::string osMax;
557 80 : if (bIsNumeric)
558 : {
559 80 : if (CPLGetValueType(aosTokens[0]) == CPL_VALUE_STRING ||
560 40 : (aosTokens.size() == 2 &&
561 28 : CPLGetValueType(aosTokens[1]) == CPL_VALUE_STRING))
562 : {
563 0 : CPLError(CE_Failure, CPLE_AppDefined,
564 : "Non numeric bound in subset specification.");
565 0 : return nullptr;
566 : }
567 40 : dfMin = CPLAtof(aosTokens[0]);
568 40 : dfMax = dfMin;
569 40 : if (aosTokens.size() == 2)
570 28 : dfMax = CPLAtof(aosTokens[1]);
571 40 : if (dfMin > dfMax)
572 0 : std::swap(dfMin, dfMax);
573 : }
574 : else
575 : {
576 40 : osMin = aosTokens[0];
577 40 : osMax = osMin;
578 40 : if (aosTokens.size() == 2)
579 26 : osMax = aosTokens[1];
580 40 : if (osMin > osMax)
581 0 : std::swap(osMin, osMax);
582 : }
583 :
584 80 : const size_t nDTSize(dt.GetSize());
585 : const size_t nMaxChunkSize = static_cast<size_t>(std::min(
586 80 : static_cast<GUInt64>(10 * 1000 * 1000), poDim->GetSize()));
587 80 : std::vector<GByte> abyTmp(nDTSize * nMaxChunkSize);
588 80 : double *pdfTmp = reinterpret_cast<double *>(&abyTmp[0]);
589 80 : const char **ppszTmp = reinterpret_cast<const char **>(&abyTmp[0]);
590 80 : GUInt64 nStartIdx = 0;
591 160 : const double EPS = std::max(std::max(1e-10, fabs(dfMin) / 1e10),
592 80 : fabs(dfMax) / 1e10);
593 80 : bool bFoundMinIdx = false;
594 80 : bool bFoundMaxIdx = false;
595 80 : GUInt64 nMinIdx = 0;
596 80 : GUInt64 nMaxIdx = 0;
597 80 : bool bLastWasReversed = false;
598 80 : bool bEmpty = false;
599 : while (true)
600 : {
601 : const size_t nCount = static_cast<size_t>(
602 200 : std::min(static_cast<GUInt64>(nMaxChunkSize),
603 100 : poDim->GetSize() - nStartIdx));
604 100 : if (nCount == 0)
605 20 : break;
606 80 : const GUInt64 anStartId[] = {nStartIdx};
607 80 : const size_t anCount[] = {nCount};
608 160 : if (!var->Read(anStartId, anCount, nullptr, nullptr, dt,
609 80 : &abyTmp[0], nullptr, 0))
610 : {
611 0 : return nullptr;
612 : }
613 80 : if (bIsNumeric)
614 : {
615 40 : FindMinMaxIdxNumeric(
616 40 : var.get(), pdfTmp, nCount, nStartIdx, dfMin, dfMax,
617 40 : desc.bSlice, bFoundMinIdx, nMinIdx, bFoundMaxIdx,
618 : nMaxIdx, bLastWasReversed, bEmpty, EPS);
619 : }
620 : else
621 : {
622 40 : FindMinMaxIdxString(var.get(), ppszTmp, nCount, nStartIdx,
623 40 : osMin, osMax, desc.bSlice, bFoundMinIdx,
624 : nMinIdx, bFoundMaxIdx, nMaxIdx,
625 : bLastWasReversed, bEmpty);
626 : }
627 80 : if (dt.NeedsFreeDynamicMemory())
628 : {
629 200 : for (size_t i = 0; i < nCount; i++)
630 : {
631 160 : dt.FreeDynamicMemory(&abyTmp[i * nDTSize]);
632 : }
633 : }
634 80 : if (bEmpty || (bFoundMinIdx && bFoundMaxIdx) ||
635 : nCount < nMaxChunkSize)
636 : {
637 : break;
638 : }
639 20 : nStartIdx += nMaxChunkSize;
640 20 : }
641 :
642 : // cppcheck-suppress knownConditionTrueFalse
643 80 : if (!bLastWasReversed)
644 : {
645 42 : if (!bFoundMinIdx)
646 6 : bEmpty = true;
647 36 : else if (!bFoundMaxIdx)
648 9 : nMaxIdx = poDim->GetSize() - 1;
649 : else
650 27 : bEmpty = nMaxIdx < nMinIdx;
651 : }
652 : else
653 : {
654 38 : if (!bFoundMaxIdx)
655 8 : bEmpty = true;
656 30 : else if (!bFoundMinIdx)
657 5 : nMinIdx = poDim->GetSize() - 1;
658 : else
659 25 : bEmpty = nMinIdx < nMaxIdx;
660 : }
661 80 : if (bEmpty)
662 : {
663 16 : CPLError(CE_Failure, CPLE_AppDefined,
664 : "Subset specification results in an empty set");
665 16 : return nullptr;
666 : }
667 :
668 : // cppcheck-suppress knownConditionTrueFalse
669 64 : if (!bLastWasReversed)
670 : {
671 34 : CPLAssert(nMaxIdx >= nMinIdx);
672 34 : desc.nStartIdx = nMinIdx;
673 34 : desc.nSize = nMaxIdx - nMinIdx + 1;
674 : }
675 : else
676 : {
677 30 : CPLAssert(nMaxIdx <= nMinIdx);
678 30 : desc.nStartIdx = nMaxIdx;
679 30 : desc.nSize = nMinIdx - nMaxIdx + 1;
680 : }
681 :
682 64 : break;
683 : }
684 : }
685 :
686 82 : for (const auto &scaleFactor : psOptions->aosScaleFactor)
687 : {
688 6 : if (STARTS_WITH(scaleFactor.c_str(), osRadix.c_str()))
689 : {
690 2 : if (scaleFactor.back() != ')')
691 : {
692 0 : CPLError(CE_Failure, CPLE_AppDefined,
693 : "Missing ')' in scalefactor specification.");
694 0 : return nullptr;
695 : }
696 : std::string osScaleFactor(scaleFactor.substr(
697 2 : osRadix.size(), scaleFactor.size() - 1 - osRadix.size()));
698 2 : int nScaleFactor = atoi(osScaleFactor.c_str());
699 2 : if (CPLGetValueType(osScaleFactor.c_str()) != CPL_VALUE_INTEGER ||
700 : nScaleFactor <= 0)
701 : {
702 0 : CPLError(CE_Failure, CPLE_NotSupported,
703 : "Only positive integer scale factor is supported");
704 0 : return nullptr;
705 : }
706 2 : desc.nSize /= nScaleFactor;
707 2 : if (desc.nSize == 0)
708 0 : desc.nSize = 1;
709 2 : desc.nStep *= nScaleFactor;
710 2 : break;
711 : }
712 : }
713 :
714 78 : oDimRemapper.oMap[osKey] = desc;
715 78 : return &oDimRemapper.oMap[osKey];
716 : }
717 :
718 : /************************************************************************/
719 : /* ParseArraySpec() */
720 : /************************************************************************/
721 :
722 : // foo
723 : // name=foo,transpose=[1,0],view=[0],dstname=bar,ot=Float32
724 151 : static bool ParseArraySpec(const std::string &arraySpec, std::string &srcName,
725 : std::string &dstName, int &band,
726 : std::vector<int> &anTransposedAxis,
727 : std::string &viewExpr,
728 : GDALExtendedDataType &outputType, bool &bResampled)
729 : {
730 287 : if (!STARTS_WITH(arraySpec.c_str(), "name=") &&
731 136 : !STARTS_WITH(arraySpec.c_str(), "band="))
732 : {
733 135 : srcName = arraySpec;
734 135 : dstName = arraySpec;
735 135 : auto pos = dstName.rfind('/');
736 135 : if (pos != std::string::npos)
737 22 : dstName = dstName.substr(pos + 1);
738 135 : return true;
739 : }
740 :
741 32 : std::vector<std::string> tokens;
742 32 : std::string curToken;
743 16 : bool bInArray = false;
744 644 : for (size_t i = 0; i < arraySpec.size(); ++i)
745 : {
746 628 : if (!bInArray && arraySpec[i] == ',')
747 : {
748 20 : tokens.emplace_back(std::move(curToken));
749 20 : curToken = std::string();
750 : }
751 : else
752 : {
753 608 : if (arraySpec[i] == '[')
754 : {
755 8 : bInArray = true;
756 : }
757 600 : else if (arraySpec[i] == ']')
758 : {
759 8 : bInArray = false;
760 : }
761 608 : curToken += arraySpec[i];
762 : }
763 : }
764 16 : if (!curToken.empty())
765 : {
766 16 : tokens.emplace_back(std::move(curToken));
767 : }
768 50 : for (const auto &token : tokens)
769 : {
770 36 : if (STARTS_WITH(token.c_str(), "name="))
771 : {
772 15 : srcName = token.substr(strlen("name="));
773 15 : if (dstName.empty())
774 15 : dstName = srcName;
775 : }
776 21 : else if (STARTS_WITH(token.c_str(), "band="))
777 : {
778 1 : band = atoi(token.substr(strlen("band=")).c_str());
779 1 : if (dstName.empty())
780 1 : dstName = CPLSPrintf("Band%d", band);
781 : }
782 20 : else if (STARTS_WITH(token.c_str(), "dstname="))
783 : {
784 10 : dstName = token.substr(strlen("dstname="));
785 : }
786 10 : else if (STARTS_WITH(token.c_str(), "transpose="))
787 : {
788 2 : auto transposeExpr = token.substr(strlen("transpose="));
789 4 : if (transposeExpr.size() < 3 || transposeExpr[0] != '[' ||
790 2 : transposeExpr.back() != ']')
791 : {
792 0 : CPLError(CE_Failure, CPLE_AppDefined,
793 : "Invalid value for transpose");
794 0 : return false;
795 : }
796 2 : transposeExpr = transposeExpr.substr(1, transposeExpr.size() - 2);
797 : CPLStringList aosAxis(
798 2 : CSLTokenizeString2(transposeExpr.c_str(), ",", 0));
799 5 : for (int i = 0; i < aosAxis.size(); ++i)
800 : {
801 4 : int iAxis = atoi(aosAxis[i]);
802 : // check for non-integer characters
803 4 : if (iAxis == 0)
804 : {
805 2 : if (!EQUAL(aosAxis[i], "0"))
806 : {
807 1 : CPLError(CE_Failure, CPLE_AppDefined,
808 : "Invalid value for axis in transpose: %s",
809 : aosAxis[i]);
810 1 : return false;
811 : }
812 : }
813 :
814 3 : anTransposedAxis.push_back(iAxis);
815 : }
816 : }
817 8 : else if (STARTS_WITH(token.c_str(), "view="))
818 : {
819 6 : viewExpr = token.substr(strlen("view="));
820 : }
821 2 : else if (STARTS_WITH(token.c_str(), "ot="))
822 : {
823 0 : auto outputTypeStr = token.substr(strlen("ot="));
824 0 : if (outputTypeStr == "String")
825 0 : outputType = GDALExtendedDataType::CreateString();
826 : else
827 : {
828 0 : auto eDT = GDALGetDataTypeByName(outputTypeStr.c_str());
829 0 : if (eDT == GDT_Unknown)
830 0 : return false;
831 0 : outputType = GDALExtendedDataType::Create(eDT);
832 : }
833 : }
834 2 : else if (STARTS_WITH(token.c_str(), "resample="))
835 : {
836 1 : bResampled = CPLTestBool(token.c_str() + strlen("resample="));
837 : }
838 : else
839 : {
840 1 : CPLError(CE_Failure, CPLE_AppDefined,
841 : "Unexpected array specification part: %s", token.c_str());
842 1 : return false;
843 : }
844 : }
845 14 : return true;
846 : }
847 :
848 : /************************************************************************/
849 : /* TranslateArray() */
850 : /************************************************************************/
851 :
852 148 : static bool TranslateArray(
853 : DimensionRemapper &oDimRemapper,
854 : const std::shared_ptr<GDALMDArray> &poSrcArrayIn,
855 : const std::string &arraySpec,
856 : const std::shared_ptr<GDALGroup> &poSrcRootGroup,
857 : const std::shared_ptr<GDALGroup> &poSrcGroup,
858 : const std::shared_ptr<VRTGroup> &poDstRootGroup,
859 : std::shared_ptr<VRTGroup> &poDstGroup, GDALDataset *poSrcDS,
860 : std::map<std::string, std::shared_ptr<GDALDimension>> &mapSrcToDstDims,
861 : std::map<std::string, std::shared_ptr<GDALDimension>> &mapDstDimFullNames,
862 : const GDALMultiDimTranslateOptions *psOptions)
863 : {
864 296 : std::string srcArrayName;
865 296 : std::string dstArrayName;
866 148 : int band = -1;
867 296 : std::vector<int> anTransposedAxis;
868 296 : std::string viewExpr;
869 148 : bool bResampled = false;
870 296 : GDALExtendedDataType outputType(GDALExtendedDataType::Create(GDT_Unknown));
871 148 : if (!ParseArraySpec(arraySpec, srcArrayName, dstArrayName, band,
872 : anTransposedAxis, viewExpr, outputType, bResampled))
873 : {
874 2 : return false;
875 : }
876 :
877 146 : std::shared_ptr<GDALMDArray> srcArray;
878 146 : bool bSrcArrayAccessibleThroughSrcGroup = true;
879 146 : if (poSrcRootGroup && poSrcGroup)
880 : {
881 142 : if (!srcArrayName.empty() && srcArrayName[0] == '/')
882 28 : srcArray = poSrcRootGroup->OpenMDArrayFromFullname(srcArrayName);
883 : else
884 114 : srcArray = poSrcGroup->OpenMDArray(srcArrayName);
885 142 : if (!srcArray)
886 : {
887 3 : if (poSrcArrayIn && poSrcArrayIn->GetFullName() == arraySpec)
888 : {
889 2 : bSrcArrayAccessibleThroughSrcGroup = false;
890 2 : srcArray = poSrcArrayIn;
891 : }
892 : else
893 : {
894 1 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find array %s",
895 : srcArrayName.c_str());
896 1 : return false;
897 : }
898 : }
899 : }
900 4 : else if (band < 0)
901 : {
902 3 : srcArray = poSrcDS->AsMDArray();
903 : }
904 : else
905 : {
906 1 : auto poBand = poSrcDS->GetRasterBand(band);
907 1 : if (!poBand)
908 0 : return false;
909 1 : srcArray = poBand->AsMDArray();
910 : }
911 :
912 290 : auto tmpArray = srcArray;
913 :
914 145 : if (bResampled)
915 : {
916 : auto newTmpArray =
917 3 : tmpArray->GetResampled(std::vector<std::shared_ptr<GDALDimension>>(
918 1 : tmpArray->GetDimensionCount()),
919 2 : GRIORA_NearestNeighbour, nullptr, nullptr);
920 1 : if (!newTmpArray)
921 0 : return false;
922 1 : tmpArray = std::move(newTmpArray);
923 : }
924 :
925 145 : if (!anTransposedAxis.empty())
926 : {
927 1 : auto newTmpArray = tmpArray->Transpose(anTransposedAxis);
928 1 : if (!newTmpArray)
929 0 : return false;
930 1 : tmpArray = std::move(newTmpArray);
931 : }
932 145 : const auto &srcArrayDims(tmpArray->GetDimensions());
933 : std::map<std::shared_ptr<GDALDimension>, std::shared_ptr<GDALDimension>>
934 290 : oMapSubsetDimToSrcDim;
935 :
936 290 : std::vector<GDALMDArray::ViewSpec> viewSpecs;
937 145 : if (!viewExpr.empty())
938 : {
939 6 : if (!psOptions->aosSubset.empty() || !psOptions->aosScaleFactor.empty())
940 : {
941 0 : CPLError(CE_Failure, CPLE_NotSupported,
942 : "View specification not supported when used together "
943 : "with subset and/or scalefactor options");
944 0 : return false;
945 : }
946 6 : auto newTmpArray = tmpArray->GetView(viewExpr, true, viewSpecs);
947 6 : if (!newTmpArray)
948 0 : return false;
949 6 : tmpArray = std::move(newTmpArray);
950 : }
951 188 : else if (!psOptions->aosSubset.empty() ||
952 49 : !psOptions->aosScaleFactor.empty())
953 : {
954 98 : bool bHasModifiedDim = false;
955 98 : viewExpr = '[';
956 194 : for (size_t i = 0; i < srcArrayDims.size(); ++i)
957 : {
958 112 : const auto &srcDim(srcArrayDims[i]);
959 : const auto poDimDesc =
960 112 : GetDimensionDesc(oDimRemapper, psOptions, srcDim);
961 112 : if (poDimDesc == nullptr)
962 16 : return false;
963 96 : if (i > 0)
964 14 : viewExpr += ',';
965 76 : if (!poDimDesc->bSlice && poDimDesc->nStartIdx == 0 &&
966 172 : poDimDesc->nStep == 1 && poDimDesc->nSize == srcDim->GetSize())
967 : {
968 28 : viewExpr += ":";
969 : }
970 : else
971 : {
972 68 : bHasModifiedDim = true;
973 : viewExpr += CPLSPrintf(
974 68 : CPL_FRMT_GUIB, static_cast<GUInt64>(poDimDesc->nStartIdx));
975 68 : if (!poDimDesc->bSlice)
976 : {
977 48 : viewExpr += ':';
978 : viewExpr +=
979 : CPLSPrintf(CPL_FRMT_GUIB,
980 48 : static_cast<GUInt64>(poDimDesc->nStartIdx +
981 48 : poDimDesc->nSize *
982 48 : poDimDesc->nStep));
983 48 : viewExpr += ':';
984 : viewExpr += CPLSPrintf(
985 48 : CPL_FRMT_GUIB, static_cast<GUInt64>(poDimDesc->nStep));
986 : }
987 : }
988 : }
989 82 : viewExpr += ']';
990 82 : if (bHasModifiedDim)
991 : {
992 66 : auto tmpArrayNew = tmpArray->GetView(viewExpr, false, viewSpecs);
993 66 : if (!tmpArrayNew)
994 0 : return false;
995 66 : tmpArray = std::move(tmpArrayNew);
996 66 : size_t j = 0;
997 66 : const auto &tmpArrayDims(tmpArray->GetDimensions());
998 146 : for (size_t i = 0; i < srcArrayDims.size(); ++i)
999 : {
1000 80 : const auto &srcDim(srcArrayDims[i]);
1001 : const auto poDimDesc =
1002 80 : GetDimensionDesc(oDimRemapper, psOptions, srcDim);
1003 80 : if (poDimDesc == nullptr)
1004 0 : return false;
1005 80 : if (poDimDesc->bSlice)
1006 20 : continue;
1007 60 : CPLAssert(j < tmpArrayDims.size());
1008 60 : oMapSubsetDimToSrcDim[tmpArrayDims[j]] = srcDim;
1009 60 : j++;
1010 : }
1011 : }
1012 : else
1013 : {
1014 16 : viewExpr.clear();
1015 : }
1016 : }
1017 :
1018 129 : int idxSliceSpec = -1;
1019 201 : for (size_t i = 0; i < viewSpecs.size(); ++i)
1020 : {
1021 72 : if (viewSpecs[i].m_osFieldName.empty())
1022 : {
1023 72 : if (idxSliceSpec >= 0)
1024 : {
1025 0 : idxSliceSpec = -1;
1026 0 : break;
1027 : }
1028 : else
1029 : {
1030 72 : idxSliceSpec = static_cast<int>(i);
1031 : }
1032 : }
1033 : }
1034 :
1035 : // Map source dimensions to target dimensions
1036 258 : std::vector<std::shared_ptr<GDALDimension>> dstArrayDims;
1037 129 : const auto &tmpArrayDims(tmpArray->GetDimensions());
1038 278 : for (size_t i = 0; i < tmpArrayDims.size(); ++i)
1039 : {
1040 149 : const auto &srcDim(tmpArrayDims[i]);
1041 149 : std::string srcDimFullName(srcDim->GetFullName());
1042 :
1043 0 : std::shared_ptr<GDALDimension> dstDim;
1044 : {
1045 298 : CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
1046 149 : if (!srcDimFullName.empty() && srcDimFullName[0] == '/')
1047 : {
1048 : dstDim =
1049 88 : poDstRootGroup->OpenDimensionFromFullname(srcDimFullName);
1050 : }
1051 : }
1052 149 : if (dstDim)
1053 : {
1054 45 : dstArrayDims.emplace_back(dstDim);
1055 45 : continue;
1056 : }
1057 :
1058 104 : auto oIter = mapSrcToDstDims.find(srcDimFullName);
1059 104 : if (oIter != mapSrcToDstDims.end())
1060 : {
1061 2 : dstArrayDims.emplace_back(oIter->second);
1062 2 : continue;
1063 : }
1064 102 : auto oIterRealSrcDim = oMapSubsetDimToSrcDim.find(srcDim);
1065 102 : if (oIterRealSrcDim != oMapSubsetDimToSrcDim.end())
1066 : {
1067 52 : srcDimFullName = oIterRealSrcDim->second->GetFullName();
1068 52 : oIter = mapSrcToDstDims.find(srcDimFullName);
1069 52 : if (oIter != mapSrcToDstDims.end())
1070 : {
1071 10 : dstArrayDims.emplace_back(oIter->second);
1072 10 : continue;
1073 : }
1074 : }
1075 :
1076 92 : const auto nDimSize = srcDim->GetSize();
1077 92 : std::string newDimNameFullName(srcDimFullName);
1078 92 : std::string newDimName(srcDim->GetName());
1079 92 : int nIncr = 2;
1080 92 : std::string osDstGroupFullName(poDstGroup->GetFullName());
1081 92 : if (osDstGroupFullName == "/")
1082 90 : osDstGroupFullName.clear();
1083 184 : auto oIter2 = mapDstDimFullNames.find(osDstGroupFullName + '/' +
1084 184 : srcDim->GetName());
1085 97 : while (oIter2 != mapDstDimFullNames.end() &&
1086 4 : oIter2->second->GetSize() != nDimSize)
1087 : {
1088 1 : newDimName = srcDim->GetName() + CPLSPrintf("_%d", nIncr);
1089 2 : newDimNameFullName = osDstGroupFullName + '/' + srcDim->GetName() +
1090 1 : CPLSPrintf("_%d", nIncr);
1091 1 : nIncr++;
1092 1 : oIter2 = mapDstDimFullNames.find(newDimNameFullName);
1093 : }
1094 95 : if (oIter2 != mapDstDimFullNames.end() &&
1095 3 : oIter2->second->GetSize() == nDimSize)
1096 : {
1097 3 : dstArrayDims.emplace_back(oIter2->second);
1098 3 : continue;
1099 : }
1100 :
1101 178 : dstDim = poDstGroup->CreateDimension(newDimName, srcDim->GetType(),
1102 89 : srcDim->GetDirection(), nDimSize);
1103 89 : if (!dstDim)
1104 0 : return false;
1105 89 : if (!srcDimFullName.empty() && srcDimFullName[0] == '/')
1106 : {
1107 79 : mapSrcToDstDims[srcDimFullName] = dstDim;
1108 : }
1109 89 : mapDstDimFullNames[dstDim->GetFullName()] = dstDim;
1110 89 : dstArrayDims.emplace_back(dstDim);
1111 :
1112 0 : std::shared_ptr<GDALMDArray> srcIndexVar;
1113 89 : GDALMDArray::Range range;
1114 89 : range.m_nStartIdx = 0;
1115 89 : range.m_nIncr = 1;
1116 89 : std::string indexingVarSpec;
1117 89 : if (idxSliceSpec >= 0)
1118 : {
1119 54 : const auto &viewSpec(viewSpecs[idxSliceSpec]);
1120 54 : auto iParentDim = viewSpec.m_mapDimIdxToParentDimIdx[i];
1121 53 : if (iParentDim != static_cast<size_t>(-1) &&
1122 : (srcIndexVar =
1123 107 : srcArrayDims[iParentDim]->GetIndexingVariable()) !=
1124 51 : nullptr &&
1125 158 : srcIndexVar->GetDimensionCount() == 1 &&
1126 51 : srcIndexVar->GetFullName() != srcArray->GetFullName())
1127 : {
1128 15 : CPLAssert(iParentDim < viewSpec.m_parentRanges.size());
1129 15 : range = viewSpec.m_parentRanges[iParentDim];
1130 15 : indexingVarSpec = "name=" + srcIndexVar->GetFullName();
1131 15 : indexingVarSpec += ",dstname=" + newDimName;
1132 30 : if (psOptions->aosSubset.empty() &&
1133 15 : psOptions->aosScaleFactor.empty())
1134 : {
1135 15 : if (range.m_nStartIdx != 0 || range.m_nIncr != 1 ||
1136 6 : srcArrayDims[iParentDim]->GetSize() !=
1137 6 : srcDim->GetSize())
1138 : {
1139 3 : indexingVarSpec += ",view=[";
1140 4 : if (range.m_nIncr > 0 ||
1141 1 : range.m_nStartIdx != srcDim->GetSize() - 1)
1142 : {
1143 : indexingVarSpec +=
1144 2 : CPLSPrintf(CPL_FRMT_GUIB, range.m_nStartIdx);
1145 : }
1146 3 : indexingVarSpec += ':';
1147 3 : if (range.m_nIncr > 0)
1148 : {
1149 : const auto nEndIdx =
1150 2 : range.m_nStartIdx +
1151 2 : range.m_nIncr * srcDim->GetSize();
1152 : indexingVarSpec +=
1153 2 : CPLSPrintf(CPL_FRMT_GUIB, nEndIdx);
1154 : }
1155 2 : else if (range.m_nStartIdx >
1156 1 : -range.m_nIncr * srcDim->GetSize())
1157 : {
1158 : const auto nEndIdx =
1159 0 : range.m_nStartIdx +
1160 0 : range.m_nIncr * srcDim->GetSize();
1161 : indexingVarSpec +=
1162 0 : CPLSPrintf(CPL_FRMT_GUIB, nEndIdx - 1);
1163 : }
1164 3 : indexingVarSpec += ':';
1165 : indexingVarSpec +=
1166 3 : CPLSPrintf(CPL_FRMT_GIB, range.m_nIncr);
1167 3 : indexingVarSpec += ']';
1168 : }
1169 : }
1170 : }
1171 : }
1172 : else
1173 : {
1174 35 : srcIndexVar = srcDim->GetIndexingVariable();
1175 35 : if (srcIndexVar)
1176 : {
1177 33 : indexingVarSpec = srcIndexVar->GetFullName();
1178 : }
1179 : }
1180 137 : if (srcIndexVar && !indexingVarSpec.empty() &&
1181 48 : srcIndexVar->GetFullName() != srcArray->GetFullName())
1182 : {
1183 38 : if (poSrcRootGroup)
1184 : {
1185 28 : if (!TranslateArray(oDimRemapper, srcIndexVar, indexingVarSpec,
1186 : poSrcRootGroup, poSrcGroup, poDstRootGroup,
1187 : poDstGroup, poSrcDS, mapSrcToDstDims,
1188 : mapDstDimFullNames, psOptions))
1189 : {
1190 0 : return false;
1191 : }
1192 : }
1193 : else
1194 : {
1195 10 : bool bIndexingVarCreated = false;
1196 19 : if (srcIndexVar->GetName() == "X" ||
1197 9 : srcIndexVar->GetName() == "Y")
1198 : {
1199 5 : GDALGeoTransform gt;
1200 5 : if (poSrcDS->GetGeoTransform(gt) == CE_None &&
1201 5 : gt[2] == 0.0 && gt[4] == 0.0)
1202 : {
1203 : auto var = poDstGroup->CreateVRTMDArray(
1204 : newDimName, {dstDim},
1205 25 : GDALExtendedDataType::Create(GDT_Float64));
1206 5 : if (var)
1207 : {
1208 : const double dfStart =
1209 5 : srcIndexVar->GetName() == "X"
1210 5 : ? gt[0] + (range.m_nStartIdx + 0.5) * gt[1]
1211 4 : : gt[3] + (range.m_nStartIdx + 0.5) * gt[5];
1212 : const double dfIncr =
1213 9 : (srcIndexVar->GetName() == "X" ? gt[1]
1214 4 : : gt[5]) *
1215 5 : range.m_nIncr;
1216 : auto poSource = std::make_unique<
1217 : VRTMDArraySourceRegularlySpaced>(dfStart,
1218 5 : dfIncr);
1219 5 : var->AddSource(std::move(poSource));
1220 5 : bIndexingVarCreated = true;
1221 : }
1222 : // else: error emitted by CreateVRTMDArray()
1223 : }
1224 : }
1225 :
1226 : // Arbitrary: to avoid blowing up RAM
1227 10 : constexpr size_t MAX_SIZE_FOR_INDEXING_VAR = 1000 * 1000;
1228 25 : if (!bIndexingVarCreated &&
1229 10 : srcIndexVar->GetDimensionCount() == 1 &&
1230 20 : srcIndexVar->GetDataType().GetClass() != GEDTC_COMPOUND &&
1231 5 : srcIndexVar->GetDimensions()[0]->GetSize() <
1232 : MAX_SIZE_FOR_INDEXING_VAR)
1233 : {
1234 : auto var = poDstGroup->CreateVRTMDArray(
1235 20 : newDimName, {dstDim}, srcIndexVar->GetDataType());
1236 5 : if (var)
1237 : {
1238 10 : std::vector<GUInt64> anOffset = {0};
1239 : const size_t nCount = static_cast<size_t>(
1240 5 : srcIndexVar->GetDimensions()[0]->GetSize());
1241 10 : std::vector<size_t> anCount = {nCount};
1242 10 : std::vector<GByte> abyValues;
1243 5 : abyValues.resize(srcIndexVar->GetDataType().GetSize() *
1244 : nCount);
1245 5 : const GInt64 arrayStep[] = {1};
1246 5 : const GPtrDiff_t anBufferStride[] = {1};
1247 10 : srcIndexVar->Read(anOffset.data(), anCount.data(),
1248 : arrayStep, anBufferStride,
1249 5 : srcIndexVar->GetDataType(),
1250 5 : abyValues.data());
1251 : auto poSource =
1252 : std::make_unique<VRTMDArraySourceInlinedValues>(
1253 0 : var.get(),
1254 5 : /* bIsConstantValue = */ false,
1255 5 : std::move(anOffset), std::move(anCount),
1256 10 : std::move(abyValues));
1257 5 : var->AddSource(std::move(poSource));
1258 : }
1259 : // else: error emitted by CreateVRTMDArray()
1260 : }
1261 5 : else if (!bIndexingVarCreated)
1262 : {
1263 0 : CPLDebug("GDAL", "Cannot create indexing variable for %s",
1264 0 : srcIndexVar->GetName().c_str());
1265 : }
1266 : }
1267 :
1268 76 : CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
1269 76 : auto poDstIndexingVar(poDstGroup->OpenMDArray(newDimName));
1270 38 : if (poDstIndexingVar)
1271 37 : dstDim->SetIndexingVariable(std::move(poDstIndexingVar));
1272 : }
1273 : }
1274 258 : if (outputType.GetClass() == GEDTC_NUMERIC &&
1275 129 : outputType.GetNumericDataType() == GDT_Unknown)
1276 : {
1277 129 : outputType = GDALExtendedDataType(tmpArray->GetDataType());
1278 : }
1279 :
1280 258 : CPLStringList aosArrayCO;
1281 184 : if (!bResampled && anTransposedAxis.empty() && viewExpr.empty() &&
1282 353 : psOptions->aosSubset.empty() && psOptions->aosScaleFactor.empty() &&
1283 40 : srcArray->GetDimensionCount() == dstArrayDims.size())
1284 : {
1285 80 : const auto anBlockSize = srcArray->GetBlockSize();
1286 80 : std::string osBlockSize;
1287 97 : for (auto v : anBlockSize)
1288 : {
1289 57 : if (!osBlockSize.empty())
1290 17 : osBlockSize += ',';
1291 57 : osBlockSize += std::to_string(v);
1292 : }
1293 40 : if (!osBlockSize.empty())
1294 40 : aosArrayCO.SetNameValue("BLOCKSIZE", osBlockSize.c_str());
1295 : }
1296 :
1297 : auto dstArray = poDstGroup->CreateVRTMDArray(dstArrayName, dstArrayDims,
1298 258 : outputType, aosArrayCO.List());
1299 129 : if (!dstArray)
1300 0 : return false;
1301 :
1302 129 : GUInt64 nCurCost = 0;
1303 129 : dstArray->CopyFromAllExceptValues(srcArray.get(), false, nCurCost, 0,
1304 : nullptr, nullptr);
1305 129 : if (bResampled)
1306 1 : dstArray->SetSpatialRef(tmpArray->GetSpatialRef().get());
1307 :
1308 129 : if (idxSliceSpec >= 0)
1309 : {
1310 144 : std::set<size_t> oSetParentDimIdxNotInArray;
1311 166 : for (size_t i = 0; i < srcArrayDims.size(); ++i)
1312 : {
1313 94 : oSetParentDimIdxNotInArray.insert(i);
1314 : }
1315 72 : const auto &viewSpec(viewSpecs[idxSliceSpec]);
1316 145 : for (size_t i = 0; i < tmpArrayDims.size(); ++i)
1317 : {
1318 73 : auto iParentDim = viewSpec.m_mapDimIdxToParentDimIdx[i];
1319 73 : if (iParentDim != static_cast<size_t>(-1))
1320 : {
1321 72 : oSetParentDimIdxNotInArray.erase(iParentDim);
1322 : }
1323 : }
1324 94 : for (const auto parentDimIdx : oSetParentDimIdxNotInArray)
1325 : {
1326 22 : const auto &srcDim(srcArrayDims[parentDimIdx]);
1327 : const auto nStartIdx =
1328 22 : viewSpec.m_parentRanges[parentDimIdx].m_nStartIdx;
1329 22 : if (nStartIdx < static_cast<GUInt64>(INT_MAX))
1330 : {
1331 : auto dstAttr = dstArray->CreateAttribute(
1332 44 : "DIM_" + srcDim->GetName() + "_INDEX", {},
1333 88 : GDALExtendedDataType::Create(GDT_Int32));
1334 22 : dstAttr->Write(static_cast<int>(nStartIdx));
1335 : }
1336 : else
1337 : {
1338 : auto dstAttr = dstArray->CreateAttribute(
1339 0 : "DIM_" + srcDim->GetName() + "_INDEX", {},
1340 0 : GDALExtendedDataType::CreateString());
1341 0 : dstAttr->Write(CPLSPrintf(CPL_FRMT_GUIB,
1342 : static_cast<GUIntBig>(nStartIdx)));
1343 : }
1344 :
1345 44 : auto srcIndexVar(srcDim->GetIndexingVariable());
1346 22 : if (srcIndexVar && srcIndexVar->GetDimensionCount() == 1)
1347 : {
1348 22 : const auto &dt(srcIndexVar->GetDataType());
1349 44 : std::vector<GByte> abyTmp(dt.GetSize());
1350 22 : const size_t nCount = 1;
1351 44 : if (srcIndexVar->Read(&nStartIdx, &nCount, nullptr, nullptr, dt,
1352 22 : &abyTmp[0], nullptr, 0))
1353 : {
1354 : {
1355 : auto dstAttr = dstArray->CreateAttribute(
1356 66 : "DIM_" + srcDim->GetName() + "_VALUE", {}, dt);
1357 22 : dstAttr->Write(abyTmp.data(), abyTmp.size());
1358 22 : dt.FreeDynamicMemory(&abyTmp[0]);
1359 : }
1360 :
1361 22 : const auto &unit(srcIndexVar->GetUnit());
1362 22 : if (!unit.empty())
1363 : {
1364 : auto dstAttr = dstArray->CreateAttribute(
1365 0 : "DIM_" + srcDim->GetName() + "_UNIT", {},
1366 0 : GDALExtendedDataType::CreateString());
1367 0 : dstAttr->Write(unit.c_str());
1368 : }
1369 : }
1370 : }
1371 : }
1372 : }
1373 :
1374 129 : double dfStart = 0.0;
1375 129 : double dfIncrement = 0.0;
1376 131 : if (!bSrcArrayAccessibleThroughSrcGroup &&
1377 2 : tmpArray->IsRegularlySpaced(dfStart, dfIncrement))
1378 : {
1379 : auto poSource = std::make_unique<VRTMDArraySourceRegularlySpaced>(
1380 2 : dfStart, dfIncrement);
1381 2 : dstArray->AddSource(std::move(poSource));
1382 : }
1383 : else
1384 : {
1385 127 : const auto dimCount(tmpArray->GetDimensionCount());
1386 254 : std::vector<GUInt64> anSrcOffset(dimCount);
1387 254 : std::vector<GUInt64> anCount(dimCount);
1388 274 : for (size_t i = 0; i < dimCount; ++i)
1389 : {
1390 147 : anCount[i] = tmpArrayDims[i]->GetSize();
1391 : }
1392 254 : std::vector<GUInt64> anStep(dimCount, 1);
1393 254 : std::vector<GUInt64> anDstOffset(dimCount);
1394 : auto poSource = std::make_unique<VRTMDArraySourceFromArray>(
1395 254 : dstArray.get(), false, false, poSrcDS->GetDescription(),
1396 254 : band < 0 ? srcArray->GetFullName() : std::string(),
1397 255 : band >= 1 ? CPLSPrintf("%d", band) : std::string(),
1398 127 : std::move(anTransposedAxis),
1399 253 : bResampled ? (viewExpr.empty()
1400 : ? std::string("resample=true")
1401 127 : : std::string("resample=true,").append(viewExpr))
1402 126 : : std::move(viewExpr),
1403 127 : std::move(anSrcOffset), std::move(anCount), std::move(anStep),
1404 254 : std::move(anDstOffset));
1405 127 : dstArray->AddSource(std::move(poSource));
1406 : }
1407 :
1408 129 : return true;
1409 : }
1410 :
1411 : /************************************************************************/
1412 : /* GetGroup() */
1413 : /************************************************************************/
1414 :
1415 : static std::shared_ptr<GDALGroup>
1416 6 : GetGroup(const std::shared_ptr<GDALGroup> &poRootGroup,
1417 : const std::string &fullName)
1418 : {
1419 12 : auto poCurGroup = poRootGroup;
1420 12 : CPLStringList aosTokens(CSLTokenizeString2(fullName.c_str(), "/", 0));
1421 10 : for (int i = 0; i < aosTokens.size(); i++)
1422 : {
1423 10 : auto poCurGroupNew = poCurGroup->OpenGroup(aosTokens[i], nullptr);
1424 5 : if (!poCurGroupNew)
1425 : {
1426 1 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find group %s",
1427 : aosTokens[i]);
1428 1 : return nullptr;
1429 : }
1430 4 : poCurGroup = std::move(poCurGroupNew);
1431 : }
1432 5 : return poCurGroup;
1433 : }
1434 :
1435 : /************************************************************************/
1436 : /* CopyGroup() */
1437 : /************************************************************************/
1438 :
1439 17 : static bool CopyGroup(
1440 : DimensionRemapper &oDimRemapper,
1441 : const std::shared_ptr<VRTGroup> &poDstRootGroup,
1442 : std::shared_ptr<VRTGroup> &poDstGroup,
1443 : const std::shared_ptr<GDALGroup> &poSrcRootGroup,
1444 : const std::shared_ptr<GDALGroup> &poSrcGroup, GDALDataset *poSrcDS,
1445 : std::map<std::string, std::shared_ptr<GDALDimension>> &mapSrcToDstDims,
1446 : std::map<std::string, std::shared_ptr<GDALDimension>> &mapDstDimFullNames,
1447 : const GDALMultiDimTranslateOptions *psOptions, bool bRecursive)
1448 : {
1449 34 : const auto srcDims = poSrcGroup->GetDimensions();
1450 34 : std::map<std::string, std::string> mapSrcVariableNameToIndexedDimName;
1451 29 : for (const auto &dim : srcDims)
1452 : {
1453 15 : const auto poDimDesc = GetDimensionDesc(oDimRemapper, psOptions, dim);
1454 15 : if (poDimDesc == nullptr)
1455 3 : return false;
1456 12 : if (poDimDesc->bSlice)
1457 2 : continue;
1458 : auto dstDim =
1459 : poDstGroup->CreateDimension(dim->GetName(), dim->GetType(),
1460 10 : dim->GetDirection(), poDimDesc->nSize);
1461 10 : if (!dstDim)
1462 0 : return false;
1463 10 : mapSrcToDstDims[dim->GetFullName()] = dstDim;
1464 10 : mapDstDimFullNames[dstDim->GetFullName()] = dstDim;
1465 20 : auto poIndexingVarSrc(dim->GetIndexingVariable());
1466 10 : if (poIndexingVarSrc)
1467 : {
1468 10 : mapSrcVariableNameToIndexedDimName[poIndexingVarSrc->GetName()] =
1469 20 : dim->GetFullName();
1470 : }
1471 : }
1472 :
1473 14 : if (!(poSrcGroup == poSrcRootGroup && psOptions->aosGroup.empty()))
1474 : {
1475 11 : auto attrs = poSrcGroup->GetAttributes();
1476 15 : for (const auto &attr : attrs)
1477 : {
1478 : auto dstAttr = poDstGroup->CreateAttribute(
1479 4 : attr->GetName(), attr->GetDimensionsSize(),
1480 8 : attr->GetDataType());
1481 4 : if (!dstAttr)
1482 : {
1483 0 : if (!psOptions->bStrict)
1484 0 : continue;
1485 0 : return false;
1486 : }
1487 4 : auto raw(attr->ReadAsRaw());
1488 4 : if (!dstAttr->Write(raw.data(), raw.size()) && !psOptions->bStrict)
1489 0 : return false;
1490 : }
1491 : }
1492 :
1493 : auto arrayNames =
1494 28 : poSrcGroup->GetMDArrayNames(psOptions->aosArrayOptions.List());
1495 40 : for (const auto &name : arrayNames)
1496 : {
1497 26 : if (!TranslateArray(oDimRemapper, nullptr, name, poSrcRootGroup,
1498 : poSrcGroup, poDstRootGroup, poDstGroup, poSrcDS,
1499 : mapSrcToDstDims, mapDstDimFullNames, psOptions))
1500 : {
1501 0 : return false;
1502 : }
1503 :
1504 : // If this array is the indexing variable of a dimension, link them
1505 : // together.
1506 52 : auto srcArray = poSrcGroup->OpenMDArray(name);
1507 26 : CPLAssert(srcArray);
1508 52 : auto dstArray = poDstGroup->OpenMDArray(name);
1509 26 : CPLAssert(dstArray);
1510 : auto oIterDimName =
1511 26 : mapSrcVariableNameToIndexedDimName.find(srcArray->GetName());
1512 26 : if (oIterDimName != mapSrcVariableNameToIndexedDimName.end())
1513 : {
1514 : auto oCorrespondingDimIter =
1515 10 : mapSrcToDstDims.find(oIterDimName->second);
1516 10 : if (oCorrespondingDimIter != mapSrcToDstDims.end())
1517 : {
1518 10 : CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
1519 20 : oCorrespondingDimIter->second->SetIndexingVariable(
1520 10 : std::move(dstArray));
1521 : }
1522 : }
1523 : }
1524 :
1525 14 : if (bRecursive)
1526 : {
1527 14 : auto groupNames = poSrcGroup->GetGroupNames();
1528 20 : for (const auto &name : groupNames)
1529 : {
1530 6 : auto srcSubGroup = poSrcGroup->OpenGroup(name);
1531 6 : if (!srcSubGroup)
1532 : {
1533 0 : return false;
1534 : }
1535 6 : auto dstSubGroup = poDstGroup->CreateVRTGroup(name);
1536 6 : if (!dstSubGroup)
1537 : {
1538 0 : return false;
1539 : }
1540 6 : if (!CopyGroup(oDimRemapper, poDstRootGroup, dstSubGroup,
1541 : poSrcRootGroup, srcSubGroup, poSrcDS,
1542 : mapSrcToDstDims, mapDstDimFullNames, psOptions,
1543 : true))
1544 : {
1545 0 : return false;
1546 : }
1547 : }
1548 : }
1549 14 : return true;
1550 : }
1551 :
1552 : /************************************************************************/
1553 : /* ParseGroupSpec() */
1554 : /************************************************************************/
1555 :
1556 : // foo
1557 : // name=foo,dstname=bar,recursive=no
1558 7 : static bool ParseGroupSpec(const std::string &groupSpec, std::string &srcName,
1559 : std::string &dstName, bool &bRecursive)
1560 : {
1561 7 : bRecursive = true;
1562 7 : if (!STARTS_WITH(groupSpec.c_str(), "name="))
1563 : {
1564 5 : srcName = groupSpec;
1565 5 : return true;
1566 : }
1567 :
1568 4 : CPLStringList aosTokens(CSLTokenizeString2(groupSpec.c_str(), ",", 0));
1569 5 : for (int i = 0; i < aosTokens.size(); i++)
1570 : {
1571 4 : const std::string token(aosTokens[i]);
1572 4 : if (STARTS_WITH(token.c_str(), "name="))
1573 : {
1574 2 : srcName = token.substr(strlen("name="));
1575 : }
1576 2 : else if (STARTS_WITH(token.c_str(), "dstname="))
1577 : {
1578 1 : dstName = token.substr(strlen("dstname="));
1579 : }
1580 1 : else if (token == "recursive=no")
1581 : {
1582 0 : bRecursive = false;
1583 : }
1584 : else
1585 : {
1586 1 : CPLError(CE_Failure, CPLE_AppDefined,
1587 : "Unexpected group specification part: %s", token.c_str());
1588 1 : return false;
1589 : }
1590 : }
1591 1 : return true;
1592 : }
1593 :
1594 : /************************************************************************/
1595 : /* TranslateInternal() */
1596 : /************************************************************************/
1597 :
1598 106 : static bool TranslateInternal(std::shared_ptr<VRTGroup> &poDstRootGroup,
1599 : GDALDataset *poSrcDS,
1600 : const GDALMultiDimTranslateOptions *psOptions)
1601 : {
1602 :
1603 212 : auto poSrcRootGroup = poSrcDS->GetRootGroup();
1604 106 : if (poSrcRootGroup)
1605 : {
1606 102 : if (psOptions->aosGroup.empty())
1607 : {
1608 192 : auto attrs = poSrcRootGroup->GetAttributes();
1609 104 : for (const auto &attr : attrs)
1610 : {
1611 8 : if (attr->GetName() == "Conventions")
1612 2 : continue;
1613 : auto dstAttr = poDstRootGroup->CreateAttribute(
1614 6 : attr->GetName(), attr->GetDimensionsSize(),
1615 18 : attr->GetDataType());
1616 6 : if (dstAttr)
1617 : {
1618 12 : auto raw(attr->ReadAsRaw());
1619 6 : dstAttr->Write(raw.data(), raw.size());
1620 : }
1621 : }
1622 : }
1623 : }
1624 :
1625 212 : DimensionRemapper oDimRemapper;
1626 212 : std::map<std::string, std::shared_ptr<GDALDimension>> mapSrcToDstDims;
1627 212 : std::map<std::string, std::shared_ptr<GDALDimension>> mapDstDimFullNames;
1628 106 : if (!psOptions->aosGroup.empty())
1629 : {
1630 6 : if (poSrcRootGroup == nullptr)
1631 : {
1632 0 : CPLError(
1633 : CE_Failure, CPLE_AppDefined,
1634 : "No multidimensional source dataset: -group cannot be used");
1635 0 : return false;
1636 : }
1637 6 : if (psOptions->aosGroup.size() == 1)
1638 : {
1639 10 : std::string srcName;
1640 10 : std::string dstName;
1641 : bool bRecursive;
1642 5 : if (!ParseGroupSpec(psOptions->aosGroup[0], srcName, dstName,
1643 : bRecursive))
1644 1 : return false;
1645 8 : auto poSrcGroup = GetGroup(poSrcRootGroup, srcName);
1646 4 : if (!poSrcGroup)
1647 1 : return false;
1648 3 : return CopyGroup(oDimRemapper, poDstRootGroup, poDstRootGroup,
1649 : poSrcRootGroup, poSrcGroup, poSrcDS,
1650 : mapSrcToDstDims, mapDstDimFullNames, psOptions,
1651 3 : bRecursive);
1652 : }
1653 : else
1654 : {
1655 3 : for (const auto &osGroupSpec : psOptions->aosGroup)
1656 : {
1657 2 : std::string srcName;
1658 2 : std::string dstName;
1659 : bool bRecursive;
1660 2 : if (!ParseGroupSpec(osGroupSpec, srcName, dstName, bRecursive))
1661 0 : return false;
1662 2 : auto poSrcGroup = GetGroup(poSrcRootGroup, srcName);
1663 2 : if (!poSrcGroup)
1664 0 : return false;
1665 2 : if (dstName.empty())
1666 1 : dstName = poSrcGroup->GetName();
1667 2 : auto dstSubGroup = poDstRootGroup->CreateVRTGroup(dstName);
1668 4 : if (!dstSubGroup ||
1669 2 : !CopyGroup(oDimRemapper, poDstRootGroup, dstSubGroup,
1670 : poSrcRootGroup, poSrcGroup, poSrcDS,
1671 : mapSrcToDstDims, mapDstDimFullNames, psOptions,
1672 : bRecursive))
1673 : {
1674 0 : return false;
1675 : }
1676 : }
1677 : }
1678 : }
1679 100 : else if (!psOptions->aosArraySpec.empty())
1680 : {
1681 169 : for (const auto &arraySpec : psOptions->aosArraySpec)
1682 : {
1683 94 : if (!TranslateArray(oDimRemapper, nullptr, arraySpec,
1684 : poSrcRootGroup, poSrcRootGroup, poDstRootGroup,
1685 : poDstRootGroup, poSrcDS, mapSrcToDstDims,
1686 : mapDstDimFullNames, psOptions))
1687 : {
1688 19 : return false;
1689 : }
1690 : }
1691 : }
1692 : else
1693 : {
1694 6 : if (poSrcRootGroup == nullptr)
1695 : {
1696 0 : CPLError(CE_Failure, CPLE_AppDefined,
1697 : "No multidimensional source dataset");
1698 0 : return false;
1699 : }
1700 6 : return CopyGroup(oDimRemapper, poDstRootGroup, poDstRootGroup,
1701 : poSrcRootGroup, poSrcRootGroup, poSrcDS,
1702 6 : mapSrcToDstDims, mapDstDimFullNames, psOptions, true);
1703 : }
1704 :
1705 76 : return true;
1706 : }
1707 :
1708 : /************************************************************************/
1709 : /* CopyToNonMultiDimensionalDriver() */
1710 : /************************************************************************/
1711 :
1712 : static GDALDatasetH
1713 4 : CopyToNonMultiDimensionalDriver(GDALDriver *poDriver, const char *pszDest,
1714 : const std::shared_ptr<GDALGroup> &poRG,
1715 : const GDALMultiDimTranslateOptions *psOptions)
1716 : {
1717 4 : std::shared_ptr<GDALMDArray> srcArray;
1718 4 : if (psOptions && !psOptions->aosArraySpec.empty())
1719 : {
1720 3 : if (psOptions->aosArraySpec.size() != 1)
1721 : {
1722 0 : CPLError(CE_Failure, CPLE_NotSupported,
1723 : "For output to a non-multidimensional driver, only "
1724 : "one array should be specified");
1725 0 : return nullptr;
1726 : }
1727 6 : std::string srcArrayName;
1728 6 : std::string dstArrayName;
1729 3 : int band = -1;
1730 6 : std::vector<int> anTransposedAxis;
1731 6 : std::string viewExpr;
1732 : GDALExtendedDataType outputType(
1733 3 : GDALExtendedDataType::Create(GDT_Unknown));
1734 3 : bool bResampled = false;
1735 3 : ParseArraySpec(psOptions->aosArraySpec[0], srcArrayName, dstArrayName,
1736 : band, anTransposedAxis, viewExpr, outputType,
1737 : bResampled);
1738 3 : srcArray = poRG->OpenMDArray(dstArrayName);
1739 : }
1740 : else
1741 : {
1742 1 : auto srcArrayNames = poRG->GetMDArrayNames(
1743 1 : psOptions ? psOptions->aosArrayOptions.List() : nullptr);
1744 5 : for (const auto &srcArrayName : srcArrayNames)
1745 : {
1746 5 : auto tmpArray = poRG->OpenMDArray(srcArrayName);
1747 5 : if (tmpArray)
1748 : {
1749 5 : const auto &dims(tmpArray->GetDimensions());
1750 13 : if (!(dims.size() == 1 && dims[0]->GetIndexingVariable() &&
1751 8 : dims[0]->GetIndexingVariable()->GetName() ==
1752 : srcArrayName))
1753 : {
1754 2 : if (srcArray)
1755 : {
1756 1 : CPLError(CE_Failure, CPLE_AppDefined,
1757 : "Several arrays exist. Select one for "
1758 : "output to non-multidimensional driver");
1759 1 : return nullptr;
1760 : }
1761 1 : srcArray = std::move(tmpArray);
1762 : }
1763 : }
1764 : }
1765 : }
1766 3 : if (!srcArray)
1767 : {
1768 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find source array");
1769 0 : return nullptr;
1770 : }
1771 3 : size_t iXDim = static_cast<size_t>(-1);
1772 3 : size_t iYDim = static_cast<size_t>(-1);
1773 3 : const auto &dims(srcArray->GetDimensions());
1774 8 : for (size_t i = 0; i < dims.size(); ++i)
1775 : {
1776 5 : if (dims[i]->GetType() == GDAL_DIM_TYPE_HORIZONTAL_X)
1777 : {
1778 2 : iXDim = i;
1779 : }
1780 3 : else if (dims[i]->GetType() == GDAL_DIM_TYPE_HORIZONTAL_Y)
1781 : {
1782 3 : iYDim = i;
1783 : }
1784 : }
1785 3 : if (dims.size() == 1)
1786 : {
1787 1 : iXDim = 0;
1788 : }
1789 2 : else if (dims.size() >= 2 && (iXDim == static_cast<size_t>(-1) ||
1790 : iYDim == static_cast<size_t>(-1)))
1791 : {
1792 0 : iXDim = dims.size() - 1;
1793 0 : iYDim = dims.size() - 2;
1794 : }
1795 : std::unique_ptr<GDALDataset> poTmpSrcDS(
1796 6 : srcArray->AsClassicDataset(iXDim, iYDim));
1797 3 : if (!poTmpSrcDS)
1798 0 : return nullptr;
1799 6 : return GDALDataset::ToHandle(poDriver->CreateCopy(
1800 : pszDest, poTmpSrcDS.get(), false,
1801 3 : psOptions ? const_cast<char **>(psOptions->aosCreateOptions.List())
1802 : : nullptr,
1803 : psOptions ? psOptions->pfnProgress : nullptr,
1804 3 : psOptions ? psOptions->pProgressData : nullptr));
1805 : }
1806 :
1807 : /************************************************************************/
1808 : /* GDALMultiDimTranslate() */
1809 : /************************************************************************/
1810 :
1811 : /* clang-format off */
1812 : /**
1813 : * Converts raster data between different formats.
1814 : *
1815 : * This is the equivalent of the
1816 : * <a href="/programs/gdalmdimtranslate.html">gdalmdimtranslate</a> utility.
1817 : *
1818 : * GDALMultiDimTranslateOptions* must be allocated and freed with
1819 : * GDALMultiDimTranslateOptionsNew() and GDALMultiDimTranslateOptionsFree()
1820 : * respectively. pszDest and hDstDS cannot be used at the same time.
1821 : *
1822 : * @param pszDest the destination dataset path or NULL.
1823 : * @param hDstDS the destination dataset or NULL.
1824 : * @param nSrcCount the number of input datasets.
1825 : * @param pahSrcDS the list of input datasets.
1826 : * @param psOptions the options struct returned by
1827 : * GDALMultiDimTranslateOptionsNew() or NULL.
1828 : * @param pbUsageError pointer to a integer output variable to store if any
1829 : * usage error has occurred or NULL.
1830 : * @return the output dataset (new dataset that must be closed using
1831 : * GDALClose(), or hDstDS is not NULL) or NULL in case of error.
1832 : *
1833 : * @since GDAL 3.1
1834 : */
1835 : /* clang-format on */
1836 :
1837 : GDALDatasetH
1838 122 : GDALMultiDimTranslate(const char *pszDest, GDALDatasetH hDstDS, int nSrcCount,
1839 : GDALDatasetH *pahSrcDS,
1840 : const GDALMultiDimTranslateOptions *psOptions,
1841 : int *pbUsageError)
1842 : {
1843 122 : if (pbUsageError)
1844 111 : *pbUsageError = false;
1845 122 : if (nSrcCount != 1 || pahSrcDS[0] == nullptr)
1846 : {
1847 0 : CPLError(CE_Failure, CPLE_NotSupported,
1848 : "Only one source dataset is supported");
1849 0 : if (pbUsageError)
1850 0 : *pbUsageError = true;
1851 0 : return nullptr;
1852 : }
1853 :
1854 122 : if (hDstDS)
1855 : {
1856 0 : CPLError(CE_Failure, CPLE_NotSupported,
1857 : "Update of existing file not supported yet");
1858 0 : GDALClose(hDstDS);
1859 0 : return nullptr;
1860 : }
1861 :
1862 366 : CPLString osFormat(psOptions ? psOptions->osFormat : "");
1863 122 : if (pszDest == nullptr /* && hDstDS == nullptr */)
1864 : {
1865 0 : CPLError(CE_Failure, CPLE_NotSupported,
1866 : "Both pszDest and hDstDS are NULL.");
1867 0 : if (pbUsageError)
1868 0 : *pbUsageError = true;
1869 0 : return nullptr;
1870 : }
1871 :
1872 122 : GDALDriver *poDriver = nullptr;
1873 :
1874 : #ifdef this_is_dead_code_for_now
1875 : const bool bCloseOutDSOnError = hDstDS == nullptr;
1876 : if (pszDest == nullptr)
1877 : pszDest = GDALGetDescription(hDstDS);
1878 : #endif
1879 :
1880 122 : if (psOptions && psOptions->bOverwrite && !EQUAL(pszDest, ""))
1881 : {
1882 1 : VSIRmdirRecursive(pszDest);
1883 : }
1884 121 : else if (psOptions && psOptions->bNoOverwrite && !EQUAL(pszDest, ""))
1885 : {
1886 : VSIStatBufL sStat;
1887 9 : if (VSIStatL(pszDest, &sStat) == 0)
1888 : {
1889 0 : CPLError(CE_Failure, CPLE_AppDefined,
1890 : "File '%s' already exists. Specify the --overwrite "
1891 : "option to overwrite it.",
1892 : pszDest);
1893 0 : return nullptr;
1894 : }
1895 9 : else if (std::unique_ptr<GDALDataset>(GDALDataset::Open(pszDest)))
1896 : {
1897 0 : CPLError(CE_Failure, CPLE_AppDefined,
1898 : "Dataset '%s' already exists. Specify the --overwrite "
1899 : "option to overwrite it.",
1900 : pszDest);
1901 0 : return nullptr;
1902 : }
1903 : }
1904 :
1905 : #ifdef this_is_dead_code_for_now
1906 : if (hDstDS == nullptr)
1907 : #endif
1908 : {
1909 122 : if (osFormat.empty())
1910 : {
1911 109 : if (EQUAL(CPLGetExtensionSafe(pszDest).c_str(), "nc"))
1912 4 : osFormat = "netCDF";
1913 : else
1914 105 : osFormat = GetOutputDriverForRaster(pszDest);
1915 109 : if (osFormat.empty())
1916 : {
1917 1 : CPLError(CE_Failure, CPLE_AppDefined,
1918 : "Cannot determine output driver for dataset name '%s'",
1919 : pszDest);
1920 1 : return nullptr;
1921 : }
1922 : }
1923 121 : poDriver = GDALDriver::FromHandle(GDALGetDriverByName(osFormat));
1924 121 : char **papszDriverMD = poDriver ? poDriver->GetMetadata() : nullptr;
1925 242 : if (poDriver == nullptr ||
1926 121 : (!CPLTestBool(CSLFetchNameValueDef(papszDriverMD, GDAL_DCAP_RASTER,
1927 0 : "FALSE")) &&
1928 0 : !CPLTestBool(CSLFetchNameValueDef(
1929 242 : papszDriverMD, GDAL_DCAP_MULTIDIM_RASTER, "FALSE"))) ||
1930 121 : (!CPLTestBool(CSLFetchNameValueDef(papszDriverMD, GDAL_DCAP_CREATE,
1931 0 : "FALSE")) &&
1932 0 : !CPLTestBool(CSLFetchNameValueDef(
1933 0 : papszDriverMD, GDAL_DCAP_CREATECOPY, "FALSE")) &&
1934 0 : !CPLTestBool(CSLFetchNameValueDef(
1935 0 : papszDriverMD, GDAL_DCAP_CREATE_MULTIDIMENSIONAL, "FALSE")) &&
1936 0 : !CPLTestBool(CSLFetchNameValueDef(
1937 : papszDriverMD, GDAL_DCAP_CREATECOPY_MULTIDIMENSIONAL,
1938 : "FALSE"))))
1939 : {
1940 0 : CPLError(CE_Failure, CPLE_NotSupported,
1941 : "Output driver `%s' not recognised or does not support "
1942 : "output file creation.",
1943 : osFormat.c_str());
1944 0 : return nullptr;
1945 : }
1946 : }
1947 :
1948 121 : GDALDataset *poSrcDS = GDALDataset::FromHandle(pahSrcDS[0]);
1949 :
1950 121 : std::unique_ptr<GDALDataset> poTmpDS;
1951 121 : GDALDataset *poTmpSrcDS = poSrcDS;
1952 242 : if (psOptions &&
1953 121 : (!psOptions->aosArraySpec.empty() || !psOptions->aosGroup.empty() ||
1954 21 : !psOptions->aosSubset.empty() || !psOptions->aosScaleFactor.empty() ||
1955 16 : !psOptions->aosArrayOptions.empty()))
1956 : {
1957 : auto poVRTDS =
1958 106 : VRTDataset::CreateVRTMultiDimensional("", nullptr, nullptr);
1959 106 : CPLAssert(poVRTDS);
1960 :
1961 106 : auto poDstRootGroup = poVRTDS->GetRootVRTGroup();
1962 106 : CPLAssert(poDstRootGroup);
1963 :
1964 106 : if (!TranslateInternal(poDstRootGroup, poSrcDS, psOptions))
1965 : {
1966 : #ifdef this_is_dead_code_for_now
1967 : if (bCloseOutDSOnError)
1968 : #endif
1969 : {
1970 24 : GDALClose(hDstDS);
1971 24 : hDstDS = nullptr;
1972 : }
1973 24 : return nullptr;
1974 : }
1975 :
1976 82 : poTmpDS = std::move(poVRTDS);
1977 82 : poTmpSrcDS = poTmpDS.get();
1978 : }
1979 :
1980 97 : auto poRG(poTmpSrcDS->GetRootGroup());
1981 191 : if (poRG &&
1982 94 : poDriver->GetMetadataItem(GDAL_DCAP_CREATE_MULTIDIMENSIONAL) ==
1983 191 : nullptr &&
1984 4 : poDriver->GetMetadataItem(GDAL_DCAP_CREATECOPY_MULTIDIMENSIONAL) ==
1985 : nullptr)
1986 : {
1987 : #ifdef this_is_dead_code_for_now
1988 : if (hDstDS)
1989 : {
1990 : CPLError(CE_Failure, CPLE_NotSupported,
1991 : "Appending to non-multidimensional driver not supported.");
1992 : GDALClose(hDstDS);
1993 : hDstDS = nullptr;
1994 : return nullptr;
1995 : }
1996 : #endif
1997 : hDstDS =
1998 4 : CopyToNonMultiDimensionalDriver(poDriver, pszDest, poRG, psOptions);
1999 : }
2000 : else
2001 : {
2002 186 : hDstDS = GDALDataset::ToHandle(poDriver->CreateCopy(
2003 : pszDest, poTmpSrcDS, false,
2004 93 : psOptions ? const_cast<char **>(psOptions->aosCreateOptions.List())
2005 : : nullptr,
2006 : psOptions ? psOptions->pfnProgress : nullptr,
2007 : psOptions ? psOptions->pProgressData : nullptr));
2008 : }
2009 :
2010 97 : return hDstDS;
2011 : }
2012 :
2013 : /************************************************************************/
2014 : /* GDALMultiDimTranslateOptionsNew() */
2015 : /************************************************************************/
2016 :
2017 : /**
2018 : * Allocates a GDALMultiDimTranslateOptions struct.
2019 : *
2020 : * @param papszArgv NULL terminated list of options (potentially including
2021 : * filename and open options too), or NULL. The accepted options are the ones of
2022 : * the <a href="/programs/gdalmdimtranslate.html">gdalmdimtranslate</a> utility.
2023 : * @param psOptionsForBinary should be nullptr, unless called from
2024 : * gdalmdimtranslate_bin.cpp
2025 : * @return pointer to the allocated GDALMultiDimTranslateOptions struct. Must be
2026 : * freed with GDALMultiDimTranslateOptionsFree().
2027 : *
2028 : * @since GDAL 3.1
2029 : */
2030 :
2031 123 : GDALMultiDimTranslateOptions *GDALMultiDimTranslateOptionsNew(
2032 : char **papszArgv, GDALMultiDimTranslateOptionsForBinary *psOptionsForBinary)
2033 : {
2034 :
2035 246 : auto psOptions = std::make_unique<GDALMultiDimTranslateOptions>();
2036 :
2037 : /* -------------------------------------------------------------------- */
2038 : /* Parse arguments. */
2039 : /* -------------------------------------------------------------------- */
2040 : try
2041 : {
2042 : auto argParser = GDALMultiDimTranslateAppOptionsGetParser(
2043 123 : psOptions.get(), psOptionsForBinary);
2044 :
2045 123 : argParser->parse_args_without_binary_name(papszArgv);
2046 :
2047 : // Check for invalid options:
2048 : // -scaleaxes is not compatible with -array = "view"
2049 : // -subset is not compatible with -array = "view"
2050 123 : if (std::find(psOptions->aosArraySpec.cbegin(),
2051 123 : psOptions->aosArraySpec.cend(),
2052 369 : "view") != psOptions->aosArraySpec.cend())
2053 : {
2054 0 : if (!psOptions->aosScaleFactor.empty())
2055 : {
2056 0 : CPLError(CE_Failure, CPLE_NotSupported,
2057 : "The -scaleaxes option is not compatible with the "
2058 : "-array \"view\" option.");
2059 0 : return nullptr;
2060 : }
2061 :
2062 0 : if (!psOptions->aosSubset.empty())
2063 : {
2064 0 : CPLError(CE_Failure, CPLE_NotSupported,
2065 : "The -subset option is not compatible with the -array "
2066 : "\"view\" option.");
2067 0 : return nullptr;
2068 : }
2069 : }
2070 : }
2071 0 : catch (const std::exception &error)
2072 : {
2073 0 : CPLError(CE_Failure, CPLE_AppDefined, "%s", error.what());
2074 0 : return nullptr;
2075 : }
2076 :
2077 123 : if (psOptionsForBinary)
2078 : {
2079 : // Note: bUpdate is apparently never changed by the command line options
2080 3 : psOptionsForBinary->bUpdate = psOptions->bUpdate;
2081 3 : if (!psOptions->osFormat.empty())
2082 0 : psOptionsForBinary->osFormat = psOptions->osFormat;
2083 : }
2084 :
2085 123 : return psOptions.release();
2086 : }
2087 :
2088 : /************************************************************************/
2089 : /* GDALMultiDimTranslateOptionsFree() */
2090 : /************************************************************************/
2091 :
2092 : /**
2093 : * Frees the GDALMultiDimTranslateOptions struct.
2094 : *
2095 : * @param psOptions the options struct for GDALMultiDimTranslate().
2096 : *
2097 : * @since GDAL 3.1
2098 : */
2099 :
2100 122 : void GDALMultiDimTranslateOptionsFree(GDALMultiDimTranslateOptions *psOptions)
2101 : {
2102 122 : delete psOptions;
2103 122 : }
2104 :
2105 : /************************************************************************/
2106 : /* GDALMultiDimTranslateOptionsSetProgress() */
2107 : /************************************************************************/
2108 :
2109 : /**
2110 : * Set a progress function.
2111 : *
2112 : * @param psOptions the options struct for GDALMultiDimTranslate().
2113 : * @param pfnProgress the progress callback.
2114 : * @param pProgressData the user data for the progress callback.
2115 : *
2116 : * @since GDAL 3.1
2117 : */
2118 :
2119 14 : void GDALMultiDimTranslateOptionsSetProgress(
2120 : GDALMultiDimTranslateOptions *psOptions, GDALProgressFunc pfnProgress,
2121 : void *pProgressData)
2122 : {
2123 14 : psOptions->pfnProgress = pfnProgress;
2124 14 : psOptions->pProgressData = pProgressData;
2125 14 : }
|