Debian Codegraph @

src/imageclasses/jlstatprofile_lib.cc

raw symbols SCIP
1 /**********************************************************************
2 jlstatprofile_lib.cc: program to calculate statistics in temporal or spectral profile
3 Author(s): [email protected]
4 Copyright (C) 2016-2020 European Union (Joint Research Centre)
5
6 This file is part of jiplib.
7
8 jiplib is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 jiplib is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with jiplib. If not, see <https://www.gnu.org/licenses/>.
20 ***********************************************************************/
21 #include <assert.h>
22 #include <iostream>
23 #include <string>
24 #include <fstream>
25 // #include <math.h>
26 #include <cmath>
27 #include <sys/types.h>
28 #include <stdio.h>
29 #include "base/Optionjl.h"
30 #include "base/Vector2d.h"
31 #include "algorithms/Filter2d.h"
32 #include "algorithms/Filter.h"
33 #include "imageclasses/Jim.h"
34 #include "imageclasses/JimList.h"
35 #include "algorithms/StatFactory.h"
36 #include "apps/AppFactory.h"
37 #include "config_jiplib.h"
38
39 using namespace std;
40 using namespace app;
41
42 /**
43 * @param function (type: std::string) Statistics function (mean, median, var, stdev, min, max, sum, mode (provide classes), minindex, maxindex, proportion (provide classes), percentile, nvalid
44 * @param perc (type: double) Percentile value(s) used for rule percentile
45 * @param otype (type: std::string) (default: GDT_Unknown) Data type for output image ({Byte/Int16/UInt16/UInt32/Int32/Float32/Float64/CInt16/CInt32/CFloat32/CFloat64}). Empty string: inherit type from input image
46 * @return shared pointer to image object
47 **/
48 shared_ptr<Jim> JimList::statProfile(app::AppFactory& app){
49 shared_ptr<Jim> imgWriter=Jim::createImg();
50 statProfile(*imgWriter, app);
51 return(imgWriter);
52 }
53
54 /**
55 * @param function (type: std::string) Statistics function (mean, median, var, stdev, min, max, sum, mode (provide classes), minindex, maxindex, proportion (provide classes), percentile, nvalid
56 * @param perc (type: double) Percentile value(s) used for rule percentile
57 * @param otype (type: std::string) (default: GDT_Unknown) Data type for output image ({Byte/Int16/UInt16/UInt32/Int32/Float32/Float64/CInt16/CInt32/CFloat32/CFloat64}). Empty string: inherit type from input image
58 * @param imgWriter output raster profile dataset
59 * @param app application specific option arguments
60 * @return CE_None if successful, CE_Failure if failed
61 **/
62 void JimList::statProfile(Jim& imgWriter, app::AppFactory& app){
63 Optionjl<std::string> function_opt("f", "function", "Statistics function (mean, median, var, stdev, min, max, sum, mode (provide classes), minindex, maxindex, proportion (provide classes), percentile, nvalid");
64 Optionjl<double> percentile_opt("perc","perc","Percentile value(s) used for rule percentile",90);
65 // Optionjl<short> class_opt("class", "class", "class value(s) to use for mode, proportion");
66 Optionjl<double> nodata_opt("nodata", "nodata", "nodata value");
67 Optionjl<std::string> otype_opt("ot", "otype", "Data type for output image ({Byte/Int16/UInt16/UInt32/Int32/Float32/Float64/CInt16/CInt32/CFloat32/CFloat64}). Empty string: inherit type from input image","GDT_Unknown");
68 // Optionjl<short> down_opt("d", "down", "down sampling factor. Use value 1 for no downsampling). Use value n>1 for downsampling (aggregation)", 1);
69 Optionjl<short> verbose_opt("v", "verbose", "verbose mode if > 0", 0,2);
70
71 // percentile_opt.setHide(1);
72 // class_opt.setHide(1);
73 otype_opt.setHide(1);
74
75 bool doProcess;//stop process when program was invoked with help option (-h --help)
76 try{
77 doProcess=function_opt.retrieveOption(app);
78 percentile_opt.retrieveOption(app);
79 nodata_opt.retrieveOption(app);
80 otype_opt.retrieveOption(app);
81 verbose_opt.retrieveOption(app);
82 if(!doProcess){
83 cout << endl;
84 std::ostringstream helpStream;
85 helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
86 throw(helpStream.str());//help was invoked, stop processing
87 }
88
89 std::vector<std::string> badKeys;
90 app.badKeys(badKeys);
91 if(badKeys.size()){
92 std::ostringstream errorStream;
93 if(badKeys.size()>1)
94 errorStream << "Error: unknown keys: ";
95 else
96 errorStream << "Error: unknown key: ";
97 for(int ikey=0;ikey<badKeys.size();++ikey){
98 errorStream << badKeys[ikey] << " ";
99 }
100 errorStream << std::endl;
101 throw(errorStream.str());
102 }
103
104 if(empty()){
105 std::string errorString="Input collection is empty";
106 throw(errorString);
107 }
108
109 if(function_opt.empty()){
110 std::ostringstream errorStream;
111 errorStream << "Error: no function selected, use option -f" << endl;
112 throw(errorStream.str());
113 }
114 std::vector<double> parallel_percentile;//used for parallel processing
115 if(function_opt.countSubstring("percentile")){
116 while(function_opt.countSubstring("percentile")<percentile_opt.size())
117 function_opt.push_back("percentile");
118 parallel_percentile.resize(function_opt.size());
119 std::vector<double>::const_iterator percit=percentile_opt.begin();
120 for(int ifunction=0;ifunction<function_opt.size();++ifunction){
121 if(function_opt[ifunction].compare("percentile"))
122 parallel_percentile[ifunction]=0;
123 else if(percit!=percentile_opt.end())
124 parallel_percentile[ifunction]=*(percit++);
125 else{
126 //we should never end up here...
127 std::ostringstream errorStream;
128 errorStream << "Error: percentiles inconsistent" << endl;
129 throw(errorStream.str());
130 }
131 }
132 }
133
134 GDALDataType theType=string2GDAL(otype_opt[0]);
135 if(theType==GDT_Unknown)
136 theType=this->front()->getGDALDataType();
137
138 if(verbose_opt[0]>1)
139 std::cout << std::endl << "Output pixel type: " << GDALGetDataTypeName(theType) << endl;
140
141 if(verbose_opt[0]>1)
142 cout << "Calculating statistic metrics: " << function_opt.size() << endl;
143 // imgWriter.open(output_opt[0],this->nrOfCol(),this->nrOfRow(),function_opt.size(),theType,imageType,memory_opt[0],option_opt);
144 //todo: expand for collections that have different image dimensions and geotransforms?
145 imgWriter.open(this->front()->nrOfCol(),this->front()->nrOfRow(),function_opt.size(),theType);
146 imgWriter.setProjection(this->front()->getProjection());
147 double gt[6];
148 this->front()->getGeoTransform(gt);
149 imgWriter.setGeoTransform(gt);
150
151 if(nodata_opt.size()){
152 for(int iband=0;iband<imgWriter.nrOfBand();++iband)
153 imgWriter.setNoData(nodata_opt);
154 }
155
156 //todo:replace assert with exception
157 assert(imgWriter.nrOfBand()==function_opt.size());
158 Vector2d<double> lineInput(this->size(),this->front()->nrOfCol());
159 assert(imgWriter.nrOfCol()==this->front()->nrOfCol());
160 Vector2d<double> lineOutput(function_opt.size(),imgWriter.nrOfCol());
161 statfactory::StatFactory stat;
162 stat.setNoDataValues(nodata_opt);
163 const char* pszMessage;
164 void* pProgressArg=NULL;
165 GDALProgressFunc pfnProgress=GDALTermProgress;
166 double progress=0;
167 if(verbose_opt[0])
168 MyProgressFunc(progress,pszMessage,pProgressArg);
169 Vector2d<double> lineInput_transposed(this->front()->nrOfCol(),size());//band interleaved by pixel
170 for(unsigned int y=0;y<this->front()->nrOfRow();++y){
171 std::list<std::shared_ptr<Jim> >::const_iterator imit=begin();
172 unsigned int ifile=0;
173 for(imit=begin();imit!=end();++imit){
174 (*imit)->readData(lineInput[ifile],y);
175 ++ifile;
176 }
177 for(int x=0;x<imgWriter.nrOfCol();++x){
178 lineInput_transposed[x]=lineInput.selectCol(x);
179 if(nodata_opt.size())
180 stat.eraseNoData(lineInput_transposed[x]);
181 }
182 //todo: check if multiple thresholds can be handled in parallel
183 // int ithreshold=0;//threshold to use for percentiles
184 #if JIPLIB_PROCESS_IN_PARALLEL == 1
185 #pragma omp parallel for
186 #else
187 #endif
188 for(int imethod=0;imethod<function_opt.size();++imethod){
189 int x=0;
190 vector<double> lineInput_tmp;
191 size_t stride=1;
192 switch(filter::Filter::getFilterType(function_opt[imethod])){
193 case(filter::first):
194 lineOutput[imethod]=lineInput.front();
195 break;
196 case(filter::last):
197 lineOutput[imethod]=lineInput.back();
198 break;
199 case(filter::nvalid):
200 for(x=0;x<imgWriter.nrOfCol();++x)
201 lineOutput[imethod][x]=stat.nvalid(lineInput_transposed[x]);
202 break;
203 case(filter::median):
204 for(x=0;x<imgWriter.nrOfCol();++x){
205 // lineInput_tmp.assign(lineInput_transposed[x].begin(),lineInput_transposed[x].end());
206 lineInput_tmp=lineInput_transposed[x];
207 gsl_sort(&(lineInput_tmp[0]),stride,lineInput_tmp.size());
208 lineOutput[imethod][x]=gsl_stats_median_from_sorted_data(&(lineInput_tmp[0]),stride,lineInput_tmp.size());
209 }
210 break;
211 case(filter::min):
212 for(x=0;x<imgWriter.nrOfCol();++x)
213 lineOutput[imethod][x]=gsl_stats_min(&(lineInput_transposed[x][0]),stride,lineInput_transposed[x].size());
214 break;
215 case(filter::minindex):
216 for(x=0;x<imgWriter.nrOfCol();++x)
217 lineOutput[imethod][x]=gsl_stats_min_index(&(lineInput_transposed[x][0]),stride,lineInput_transposed[x].size());
218 break;
219 case(filter::max):
220 for(x=0;x<imgWriter.nrOfCol();++x)
221 lineOutput[imethod][x]=gsl_stats_max(&(lineInput_transposed[x][0]),stride,lineInput_transposed[x].size());
222 break;
223 case(filter::maxindex):
224 for(x=0;x<imgWriter.nrOfCol();++x)
225 lineOutput[imethod][x]=gsl_stats_max_index(&(lineInput_transposed[x][0]),stride,lineInput_transposed[x].size());
226 break;
227 case(filter::sum):
228 for(x=0;x<imgWriter.nrOfCol();++x)
229 lineOutput[imethod][x]=size()*gsl_stats_mean(&(lineInput_transposed[x][0]),stride,lineInput_transposed[x].size());
230 break;
231 case(filter::var):
232 for(x=0;x<imgWriter.nrOfCol();++x)
233 lineOutput[imethod][x]=gsl_stats_variance(&(lineInput_transposed[x][0]),stride,lineInput_transposed[x].size());
234 break;
235 case(filter::stdev):
236 for(x=0;x<imgWriter.nrOfCol();++x)
237 lineOutput[imethod][x]=gsl_stats_sd(&(lineInput_transposed[x][0]),stride,lineInput_transposed[x].size());
238 break;
239 case(filter::mean):{
240 for(x=0;x<imgWriter.nrOfCol();++x)
241 lineOutput[imethod][x]=gsl_stats_mean(&(lineInput_transposed[x][0]),stride,lineInput_transposed[x].size());
242 break;
243 }
244 case(filter::percentile):{
245 // double threshold=(ithreshold<percentile_opt.size())? percentile_opt[ithreshold] : percentile_opt[0];
246 double threshold=parallel_percentile[imethod];
247 // double threshold=percentile_opt[0];
248 for(x=0;x<imgWriter.nrOfCol();++x){
249 lineInput_tmp=lineInput_transposed[x];
250 gsl_sort(&(lineInput_tmp[0]),stride,lineInput_tmp.size());
251 lineOutput[imethod][x]=gsl_stats_quantile_from_sorted_data(&(lineInput_tmp[0]),stride,lineInput_tmp.size(),threshold/100.0);
252 }
253 // ++ithreshold;
254 break;
255 }
256 default:
257 std::string errorString="method not supported";
258 throw(errorString);
259 break;
260 }
261 imgWriter.writeData(lineOutput[imethod],y,imethod);
262 }
263 progress=(1.0+y)/imgWriter.nrOfRow();
264 if(verbose_opt[0])
265 MyProgressFunc(progress,pszMessage,pProgressArg);
266 }
267 }
268 catch(string predefinedString){
269 std::cout << predefinedString << std::endl;
270 throw;
271 }
272 }
273
274 /**
275 * @param function (type: std::string) Statistics function (mean, median, var, stdev, min, max, sum, mode (provide classes), minindex, maxindex, proportion (provide classes), percentile, nvalid
276 * @param perc (type: double) Percentile value(s) used for rule percentile
277 * @param otype (type: std::string) (default: GDT_Unknown) Data type for output image ({Byte/Int16/UInt16/UInt32/Int32/Float32/Float64/CInt16/CInt32/CFloat32/CFloat64}). Empty string: inherit type from input image
278 * @return shared pointer to image object
279 **/
280 shared_ptr<Jim> Jim::statProfile(app::AppFactory& app){
281 try{
282 shared_ptr<Jim> imgWriter=Jim::createImg();
283 statProfile(*imgWriter, app);
284 return(imgWriter);
285 }
286 catch(string helpString){
287 cerr << helpString << endl;
288 throw;
289 }
290 }
291
292 /**
293 * @param function (type: std::string) Statistics function (mean, median, var, stdev, min, max, sum, mode (provide classes), minindex, maxindex, proportion (provide classes), percentile, nvalid
294 * @param perc (type: double) Percentile value(s) used for rule percentile
295 * @param otype (type: std::string) (default: GDT_Unknown) Data type for output image ({Byte/Int16/UInt16/UInt32/Int32/Float32/Float64/CInt16/CInt32/CFloat32/CFloat64}). Empty string: inherit type from input image
296 * @param imgWriter output raster profile dataset
297 * @param app application specific option arguments
298 * @return CE_None if successful, CE_Failure if failed
299 **/
300 void Jim::statProfile(Jim& imgWriter, app::AppFactory& app){
301 Optionjl<std::string> function_opt("f", "function", "Statistics function (mean, median, var, stdev, min, max, sum, mode, minindex, maxindex, proportion (provide classes), percentile, nvalid");
302 Optionjl<double> percentile_opt("perc","perc","Percentile value(s) used for rule percentile",90);
303 // Optionjl<short> class_opt("class", "class", "class value(s) to use for mode, proportion");
304 Optionjl<double> nodata_opt("nodata", "nodata", "nodata value)");
305 Optionjl<std::string> otype_opt("ot", "otype", "Data type for output image ({Byte/Int16/UInt16/UInt32/Int32/Float32/Float64/CInt16/CInt32/CFloat32/CFloat64}). Empty string: inherit type from input image","GDT_Unknown");
306 // Optionjl<short> down_opt("d", "down", "down sampling factor. Use value 1 for no downsampling). Use value n>1 for downsampling (aggregation)", 1);
307 Optionjl<short> verbose_opt("v", "verbose", "verbose mode if > 0", 0,2);
308
309 // percentile_opt.setHide(1);
310 // class_opt.setHide(1);
311 otype_opt.setHide(1);
312
313 bool doProcess;//stop process when program was invoked with help option (-h --help)
314 try{
315 doProcess=function_opt.retrieveOption(app);
316 percentile_opt.retrieveOption(app);
317 nodata_opt.retrieveOption(app);
318 otype_opt.retrieveOption(app);
319 verbose_opt.retrieveOption(app);
320 if(!doProcess){
321 cout << endl;
322 std::ostringstream helpStream;
323 helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
324 throw(helpStream.str());//help was invoked, stop processing
325 }
326
327 std::vector<std::string> badKeys;
328 app.badKeys(badKeys);
329 if(badKeys.size()){
330 std::ostringstream errorStream;
331 if(badKeys.size()>1)
332 errorStream << "Error: unknown keys: ";
333 else
334 errorStream << "Error: unknown key: ";
335 for(int ikey=0;ikey<badKeys.size();++ikey){
336 errorStream << badKeys[ikey] << " ";
337 }
338 errorStream << std::endl;
339 throw(errorStream.str());
340 }
341
342 if(function_opt.empty()){
343 std::ostringstream errorStream;
344 errorStream << "Error: no function selected, use option -f" << endl;
345 throw(errorStream.str());
346 }
347 std::vector<double> parallel_percentile;//used for parallel processing
348 if(function_opt.countSubstring("percentile")){
349 while(function_opt.countSubstring("percentile")<percentile_opt.size())
350 function_opt.push_back("percentile");
351 parallel_percentile.resize(function_opt.size());
352 std::vector<double>::const_iterator percit=percentile_opt.begin();
353 for(int ifunction=0;ifunction<function_opt.size();++ifunction){
354 if(function_opt[ifunction].compare("percentile"))
355 parallel_percentile[ifunction]=0;
356 else if(percit!=percentile_opt.end())
357 parallel_percentile[ifunction]=*(percit++);
358 else{
359 //we should never end up here...
360 std::ostringstream errorStream;
361 errorStream << "Error: percentiles inconsistent" << endl;
362 throw(errorStream.str());
363 }
364 }
365 }
366
367 GDALDataType theType=string2GDAL(otype_opt[0]);
368 if(theType==GDT_Unknown)
369 theType=this->getGDALDataType();
370
371 if(verbose_opt[0]>1)
372 std::cout << std::endl << "Output pixel type: " << GDALGetDataTypeName(theType) << endl;
373
374 if(verbose_opt[0]>1)
375 cout << "Calculating statistic metrics: " << function_opt.size() << endl;
376 // imgWriter.open(output_opt[0],this->nrOfCol(),this->nrOfRow(),function_opt.size(),theType,imageType,memory_opt[0],option_opt);
377 imgWriter.open(this->nrOfCol(),this->nrOfRow(),function_opt.size(),theType);
378 imgWriter.setProjection(this->getProjection());
379 double gt[6];
380 this->getGeoTransform(gt);
381 imgWriter.setGeoTransform(gt);
382
383 if(nodata_opt.size()){
384 for(int iband=0;iband<imgWriter.nrOfBand();++iband)
385 imgWriter.GDALSetNoDataValue(nodata_opt[0],iband);
386 }
387
388 //todo:replace assert with exception
389 assert(imgWriter.nrOfBand()==function_opt.size());
390 Vector2d<double> lineInput(this->nrOfBand(),this->nrOfCol());
391 assert(imgWriter.nrOfCol()==this->nrOfCol());
392 Vector2d<double> lineOutput(function_opt.size(),imgWriter.nrOfCol());
393 statfactory::StatFactory stat;
394 stat.setNoDataValues(nodata_opt);
395 const char* pszMessage;
396 void* pProgressArg=NULL;
397 GDALProgressFunc pfnProgress=GDALTermProgress;
398 double progress=0;
399 if(verbose_opt[0])
400 MyProgressFunc(progress,pszMessage,pProgressArg);
401 Vector2d<double> lineInput_transposed(nrOfCol(),nrOfBand());//band interleaved by pixel
402 for(unsigned int y=0;y<this->nrOfRow();++y){
403 for(unsigned int iband=0;iband<this->nrOfBand();++iband)
404 this->readData(lineInput[iband],y,iband);
405 for(int x=0;x<nrOfCol();++x){
406 lineInput_transposed[x]=lineInput.selectCol(x);
407 if(nodata_opt.size())
408 stat.eraseNoData(lineInput_transposed[x]);
409 }
410 //todo: check if multiple thresholds can be handled in parallel
411 // int ithreshold=0;//threshold to use for percentiles
412 #if JIPLIB_PROCESS_IN_PARALLEL == 1
413 #pragma omp parallel for
414 #else
415 #endif
416 for(int imethod=0;imethod<function_opt.size();++imethod){
417 int x=0;
418 vector<double> lineInput_tmp;
419 size_t stride=1;
420 switch(filter::Filter::getFilterType(function_opt[imethod])){
421 case(filter::first):
422 lineOutput[imethod]=lineInput.front();
423 break;
424 case(filter::last):
425 lineOutput[imethod]=lineInput.back();
426 break;
427 case(filter::median):
428 for(x=0;x<imgWriter.nrOfCol();++x){
429 lineInput_tmp=lineInput_transposed[x];
430 gsl_sort(&(lineInput_tmp[0]),stride,lineInput_tmp.size());
431 lineOutput[imethod][x]=gsl_stats_median_from_sorted_data(&(lineInput_tmp[0]),stride,lineInput_tmp.size());
432 }
433 break;
434 case(filter::min):
435 for(x=0;x<nrOfCol();++x)
436 lineOutput[imethod][x]=gsl_stats_min(&(lineInput_transposed[x][0]),stride,lineInput_transposed[x].size());
437 break;
438 case(filter::minindex):
439 for(x=0;x<imgWriter.nrOfCol();++x)
440 lineOutput[imethod][x]=gsl_stats_min_index(&(lineInput_transposed[x][0]),stride,lineInput_transposed[x].size());
441 break;
442 case(filter::max):
443 for(x=0;x<nrOfCol();++x)
444 lineOutput[imethod][x]=gsl_stats_max(&(lineInput_transposed[x][0]),stride,lineInput_transposed[x].size());
445 break;
446 case(filter::maxindex):
447 for(x=0;x<imgWriter.nrOfCol();++x)
448 lineOutput[imethod][x]=gsl_stats_max_index(&(lineInput_transposed[x][0]),stride,lineInput_transposed[x].size());
449 break;
450 case(filter::sum):
451 for(x=0;x<nrOfCol();++x)
452 lineOutput[imethod][x]=nrOfBand()*gsl_stats_mean(&(lineInput_transposed[x][0]),stride,lineInput_transposed[x].size());
453 break;
454 case(filter::var):
455 for(x=0;x<nrOfCol();++x)
456 lineOutput[imethod][x]=gsl_stats_variance(&(lineInput_transposed[x][0]),stride,lineInput_transposed[x].size());
457 break;
458 case(filter::stdev):
459 for(x=0;x<nrOfCol();++x)
460 lineOutput[imethod][x]=gsl_stats_sd(&(lineInput_transposed[x][0]),stride,lineInput_transposed[x].size());
461 break;
462 case(filter::mean):{
463 for(x=0;x<nrOfCol();++x)
464 lineOutput[imethod][x]=gsl_stats_mean(&(lineInput_transposed[x][0]),stride,lineInput_transposed[x].size());
465 break;
466 }
467 case(filter::percentile):{
468 // double threshold=(ithreshold<percentile_opt.size())? percentile_opt[ithreshold] : percentile_opt[0];
469 double threshold=parallel_percentile[imethod];
470 for(x=0;x<nrOfCol();++x){
471 lineInput_tmp=lineInput_transposed[x];
472 gsl_sort(&(lineInput_tmp[0]),stride,lineInput_tmp.size());
473 lineOutput[imethod][x]=gsl_stats_quantile_from_sorted_data(&(lineInput_tmp[0]),stride,lineInput_tmp.size(),threshold/100.0);
474 }
475 // ++ithreshold;
476 break;
477 }
478 default:
479 std::string errorString="method not supported";
480 throw(errorString);
481 break;
482 }
483 imgWriter.writeData(lineOutput[imethod],y,imethod);
484 }
485 progress=(1.0+y)/imgWriter.nrOfRow();
486 if(verbose_opt[0])
487 MyProgressFunc(progress,pszMessage,pProgressArg);
488 }
489 }
490 catch(string predefinedString){
491 std::cout << predefinedString << std::endl;
492 throw;
493 }
494 }