Debian Codegraph @

src/imageclasses/jlannogr_lib.cc

raw symbols SCIP
1 /**********************************************************************
2 jlann_lib.cc: classify raster image using Artificial Neural Network
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 <stdlib.h>
22 #include <vector>
23 #include <map>
24 #include <algorithm>
25 #include "imageclasses/Jim.h"
26 #include "imageclasses/VectorOgr.h"
27 #include "base/Optionjl.h"
28 #include "base/PosValue.h"
29 #include "algorithms/ConfusionMatrix.h"
30 #include "floatfann.h"
31 #include "algorithms/myfann_cpp.h"
32
33 using namespace std;
34 using namespace app;
35
36 /**
37 * @param app application specific option arguments
38 * @return output Vector
39 **/
40 shared_ptr<VectorOgr> VectorOgr::classifyANN(app::AppFactory& app){
41 std::shared_ptr<VectorOgr> ogrWriter=VectorOgr::createVector();
42 classifyANN(*ogrWriter, app);
43 return(ogrWriter);
44 }
45
46 /**
47 * @param imgWriter output classified raster dataset
48 * @param app application specific option arguments
49 **/
50 void VectorOgr::classifyANN(VectorOgr& ogrWriter, app::AppFactory& app){
51 //--------------------------- command line options ------------------------------------
52 Optionjl<std::string> model_opt("model", "model", "Model filename for trained classifier.");
53 Optionjl<unsigned int> band_opt("b", "band", "band index (starting from 0, either use band option or use start to end)");
54 Optionjl<std::string> bandNames_opt("bn", "bandname", "Band name(s) to use. Leave empty to use all bands");
55 Optionjl<unsigned int> bstart_opt("sband", "startband", "Start band sequence number");
56 Optionjl<unsigned int> bend_opt("eband", "endband", "End band sequence number");
57 Optionjl<double> offset_opt("offset", "offset", "offset value for each spectral band input features: refl[band]=(DN[band]-offset[band])/scale[band]", 0.0);
58 Optionjl<double> scale_opt("scale", "scale", "scale value for each spectral band input features: refl=(DN[band]-offset[band])/scale[band] (use 0 if scale min and max in each band to -1.0 and 1.0)", 0.0);
59 Optionjl<double> priors_opt("prior", "prior", "prior probabilities for each class (e.g., -p 0.3 -p 0.3 -p 0.2 )");
60 Optionjl<string> output_opt("o", "output", "Filename of classified vector dataset");
61 Optionjl<string> ogrformat_opt("f", "oformat", "Output ogr format","SQLite");
62 Optionjl<std::string> option_opt("co", "co", "Creation option for output file. Multiple options can be specified.");
63 Optionjl<string> copyFields_opt("copy", "copy", "copy these fields from input to output vector dataset");
64 Optionjl<short> verbose_opt("v", "verbose", "set to: 0 (results only), 1 (confusion matrix), 2 (debug)",0,2);
65 // Optionjl<string> cmformat_opt("cmf","cmf","Format for confusion matrix (ascii or latex)","ascii");
66 // Optionjl<std::string> label_opt("label", "label", "Attribute name for reference class label used for validation.","label");
67 // Optionjl<string> classname_opt("c", "class", "list of class names.");
68 // Optionjl<short> classvalue_opt("r", "reclass", "list of class values (use same order as in class opt).");
69
70 band_opt.setHide(1);
71 bandNames_opt.setHide(1);
72 bstart_opt.setHide(1);
73 bend_opt.setHide(1);
74 option_opt.setHide(1);
75 verbose_opt.setHide(2);
76
77 bool doProcess;//stop process when program was invoked with help option (-h --help)
78 try{
79 doProcess=model_opt.retrieveOption(app);
80 copyFields_opt.retrieveOption(app);
81 ogrformat_opt.retrieveOption(app);
82 option_opt.retrieveOption(app);
83 priors_opt.retrieveOption(app);
84 // Advanced options
85 band_opt.retrieveOption(app);
86 bandNames_opt.retrieveOption(app);
87 bstart_opt.retrieveOption(app);
88 bend_opt.retrieveOption(app);
89 offset_opt.retrieveOption(app);
90 scale_opt.retrieveOption(app);
91 output_opt.retrieveOption(app);
92 verbose_opt.retrieveOption(app);
93 // cmformat_opt.retrieveOption(app);
94 // label_opt.retrieveOption(app);
95 // classname_opt.retrieveOption(app);
96 // classvalue_opt.retrieveOption(app);
97
98 if(!doProcess){
99 std::cout << std::endl;
100 std::ostringstream helpStream;
101 helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
102 throw(helpStream.str());//help was invoked, stop processing
103 }
104
105 if(model_opt.empty()){
106 std::ostringstream errorStream;
107 errorStream << "Error: model is not defined, please use option --model" << std::endl;
108 throw(errorStream.str());
109 }
110
111 if(verbose_opt[0]>=1)
112 std::cout << "model file: " << model_opt[0] << std::endl;
113
114 char **papszOptions=NULL;
115 for(std::vector<std::string>::const_iterator optionIt=option_opt.begin();optionIt!=option_opt.end();++optionIt)
116 papszOptions=CSLAddString(papszOptions,optionIt->c_str());
117
118 bool initWriter=true;
119 if(ogrWriter.open(output_opt[0],ogrformat_opt[0])!=OGRERR_NONE)
120 initWriter=false;
121
122 std::vector<double> offset;
123 std::vector<double> scale;
124 map<string,short> classValueMap;
125 vector<std::string> nameVector;
126 vector<std::string> bandNames;
127
128 FANN::neural_net net;//the neural network
129
130 if(!net.create_from_file(model_opt[0],offset,scale,classValueMap,nameVector,bandNames)){
131 std::ostringstream errorStream;
132 errorStream << "Error: could not create neural network from file " << model_opt[0];
133 throw(errorStream.str());
134 }
135
136 //todo: check if get_num_output() is really the number of classes
137 unsigned int nclass=net.get_num_output();
138 unsigned int nband=bandNames.size()?bandNames.size():offset.size();//todo: find a more elegant way to define number of bands (in model?)
139
140 if(verbose_opt[0]){
141 std::cout << "nclass: " << nclass << std::endl;
142 std::cout << "nband: " << nband << std::endl;
143 std::map<std::string,short>::const_iterator mapit=classValueMap.begin();
144 std::cout << "classValueMap:" << std::endl;
145 while(mapit!=classValueMap.end()){
146 std::cout << mapit->first << ": " << mapit->second << std::endl;
147 ++mapit;
148 }
149 std::cout << "nameVector:" << std::endl;
150 for(int index=0;index<nameVector.size();++index)
151 std::cout << nameVector[index] << std::endl;
152 std::cout << "bandNames:" << std::endl;
153 for(int index=0;index<bandNames.size();++index)
154 std::cout << bandNames[index] << std::endl;
155 }
156
157 //normalize priors from command line
158 vector<double> priors;
159 if(priors_opt.size()>1){//priors from argument list
160 priors.resize(priors_opt.size());
161 double normPrior=0;
162 for(unsigned int iclass=0;iclass<priors_opt.size();++iclass){
163 priors[iclass]=priors_opt[iclass];
164 normPrior+=priors[iclass];
165 }
166 //normalize
167 for(unsigned int iclass=0;iclass<priors_opt.size();++iclass)
168 priors[iclass]/=normPrior;
169 }
170
171 //convert start and end band options to vector of band indexes
172 if(bstart_opt.size()){
173 if(bend_opt.size()!=bstart_opt.size()){
174 string errorstring="Error: options for start and end band indexes must be provided as pairs, missing end band";
175 throw(errorstring);
176 }
177 band_opt.clear();
178 for(unsigned int ipair=0;ipair<bstart_opt.size();++ipair){
179 if(bend_opt[ipair]<=bstart_opt[ipair]){
180 string errorstring="Error: index for end band must be smaller then start band";
181 throw(errorstring);
182 }
183 for(unsigned int iband=bstart_opt[ipair];iband<=bend_opt[ipair];++iband)
184 band_opt.push_back(iband);
185 }
186 }
187
188 if(band_opt.size()){
189 //sort bands
190 // std::sort(band_opt.begin(),band_opt.end());
191 if(nband!=band_opt.size()){
192 string errorstring="Error: index for end band must be smaller then start band";
193 throw(errorstring);
194 }
195 }
196 else{
197 unsigned short iband=0;
198 while(band_opt.size()<nband)
199 band_opt.push_back(iband++);
200 }
201
202 // map<string,short> classValueMap;
203 // vector<std::string> nameVector;
204 // if(classname_opt.size()){
205 // assert(classname_opt.size()==classvalue_opt.size());
206 // for(unsigned int iclass=0;iclass<classname_opt.size();++iclass)
207 // classValueMap[classname_opt[iclass]]=classvalue_opt[iclass];
208 // }
209
210 const char* pszMessage;
211 void* pProgressArg=NULL;
212 GDALProgressFunc pfnProgress=GDALTermProgress;
213 float progress=0;
214 if(!verbose_opt[0])
215 pfnProgress(progress,pszMessage,pProgressArg);
216
217 // cm.clearResults();
218 //notice that fields have already been set by readDataImageOgr (taking into account appropriate bands)
219 int nvalidation=1;
220 for(int ivalidation=0;ivalidation<nvalidation;++ivalidation){
221 if(verbose_opt[0])
222 cout << "number of layers in input ogr file: " << getLayerCount() << std::endl;
223 for(unsigned int ilayer=0;ilayer<getLayerCount();++ilayer){
224 if(verbose_opt[0])
225 std::cout << "processing input layer " << ilayer << std::endl;
226 if(initWriter){
227 if(ogrWriter.pushLayer(getLayerName(ilayer),getProjection(ilayer),getGeometryType(),papszOptions)!=OGRERR_NONE){
228 ostringstream fs;
229 fs << "push layer to ogrWriter with polygons failed ";
230 fs << "layer name: "<< getLayerName(ilayer) << std::endl;
231 throw(fs.str());
232 }
233 // ogrWriter.pushLayer(getLayer()->GetName(),getProjection(),getGeometryType(),NULL);
234 if(copyFields_opt.size()){
235 if(verbose_opt[0])
236 std::cout << "copy fields" << std::endl;
237 ogrWriter.copyFields(*this,copyFields_opt,ilayer,ilayer);
238 }
239 if(verbose_opt[0])
240 std::cout << "creating field class" << std::endl;
241 if(classValueMap.size())
242 ogrWriter.createField("class",OFTInteger,ilayer);
243 else
244 ogrWriter.createField("class",OFTString,ilayer);
245 }
246
247 //make sure to use resize and setFeature instead of pushFeature when in processing in parallel!!!
248 ogrWriter.resize(getFeatureCount(ilayer),ilayer);
249
250 unsigned int nFeatures=getFeatureCount(ilayer);
251 progress=0;
252 pfnProgress(progress,pszMessage,pProgressArg);
253 #if JIPLIB_PROCESS_IN_PARALLEL == 1
254 #pragma omp parallel for
255 #else
256 #endif
257 for(unsigned int ifeature=0;ifeature<getFeatureCount(ilayer);++ifeature){
258 OGRFeature *poFeature=cloneFeature(ifeature,ilayer);
259 if(verbose_opt[0]>1)
260 std::cout << "feature " << ifeature << std::endl;
261 if( poFeature == NULL ){
262 cout << "Warning: could not read feature " << ifeature << " in layer " << getLayerName(ilayer) << endl;
263 continue;
264 }
265 OGRFeature *poDstFeature = NULL;
266 poDstFeature=ogrWriter.createFeature(ilayer);
267 if( poDstFeature->SetFrom( poFeature, TRUE ) != OGRERR_NONE ){
268 OGRFeature::DestroyFeature( poFeature );
269 OGRFeature::DestroyFeature( poDstFeature );
270 std::ostringstream errorStream;
271 errorStream << "Error: Unable to translate feature " << poFeature->GetFID() << "from layer " << ogrWriter.getLayerName(ilayer).c_str() << std::endl;
272 throw(errorStream.str());
273 }
274 // poDstFeature->SetGeometry(poFeature->GetGeometryRef());
275 std::vector<float> validationFeature;
276 std::vector<float> probOut(nclass);//posterior prob for each (internal) class
277 for(int iField=0;iField<m_features[ilayer][ifeature]->GetFieldCount();++iField){
278 std::string fieldname=m_features[ilayer][ifeature]->GetFieldDefnRef(iField)->GetNameRef();
279 if(bandNames.size()){
280 if(find(bandNames.begin(),bandNames.end(),fieldname)!=bandNames.end()){
281 double theValue=m_features[ilayer][ifeature]->GetFieldAsDouble(iField);
282 validationFeature.push_back((theValue-offset[iField])/scale[iField]);
283 }
284 }
285 else if(fieldname!="fid"){
286 double theValue=m_features[ilayer][ifeature]->GetFieldAsDouble(iField);
287 validationFeature.push_back((theValue-offset[iField])/scale[iField]);
288 }
289 }
290 vector<float> result(nclass);
291 result=net.run(validationFeature);
292
293 //calculate posterior prob and calculate max class prob
294 float max=0;//max probability
295 std::string classOut="Unclassified";
296 for(short iclass=0;iclass<nclass;++iclass){
297 result[iclass]=(result[iclass]+1.0)/2.0;//bring back to scale [0,1]
298 if(priors_opt.size())
299 probOut[iclass]=priors[iclass]*result[iclass];
300 else
301 probOut[iclass]=result[iclass];
302 if(verbose_opt[0]>1)
303 std::cout << "feature " << ifeature << " probOut " << iclass << ": " << probOut[iclass] << std::endl;
304 if(probOut[iclass]>max){
305 max=probOut[iclass];
306 if(classValueMap.size())
307 classOut=nameVector[iclass];//classOut=classValueMap[nameVector[iclass]];
308 else
309 classOut=type2string<short>(iclass);
310 }
311 }
312 if(verbose_opt[0]>1)
313 std::cout << "feature " << ifeature << " classOut " << classOut << std::endl;
314
315 if(classValueMap.size())
316 poDstFeature->SetField("class",classValueMap[classOut]);
317 else
318 poDstFeature->SetField("class",classOut.c_str());
319 //todo: might not be needed due to SetFrom
320 poDstFeature->SetFID( poFeature->GetFID() );
321
322 // int labelIndex=poFeature->GetFieldIndex(label_opt[0].c_str());
323 // if(labelIndex>=0){
324 // string classRef=poFeature->GetFieldAsString(labelIndex);
325 // if(classRef!="0"){
326 // if(classValueMap.size())
327 // cm.incrementResult(type2string<short>(classValueMap[classRef]),type2string<short>(classValueMap[classOut]),1);
328 // else
329 // cm.incrementResult(classRef,classOut,1);
330 // }
331 // }
332
333 //make sure to use setFeature instead of pushFeature when in processing in parallel!!!
334 ogrWriter.setFeature(ifeature,poDstFeature,ilayer);
335 if(!verbose_opt[0]){
336 progress=static_cast<float>(ifeature+1.0)/nFeatures;
337 pfnProgress(progress,pszMessage,pProgressArg);
338 }
339 }//get next feature
340 }//next layer
341 }
342 // if(cm.nReference()){
343 // std::cout << cm << std::endl;
344 // std::cout << "class #samples userAcc prodAcc" << std::endl;
345 // double se95_ua=0;
346 // double se95_pa=0;
347 // double se95_oa=0;
348 // double dua=0;
349 // double dpa=0;
350 // double doa=0;
351 // for(short iclass=0;iclass<cm.nClasses();++iclass){
352 // dua=cm.ua_pct(cm.getClass(iclass),&se95_ua);
353 // dpa=cm.pa_pct(cm.getClass(iclass),&se95_pa);
354 // cout << cm.getClass(iclass) << " " << cm.nReference(cm.getClass(iclass)) << " " << dua << " (" << se95_ua << ")" << " " << dpa << " (" << se95_pa << ")" << std::endl;
355 // }
356 // std::cout << "Kappa: " << cm.kappa() << std::endl;
357 // doa=cm.oa_pct(&se95_oa);
358 // std::cout << "Overall Accuracy: " << doa << " (" << se95_oa << ")" << std::endl;
359 // }
360 }
361 catch(BadConversion conversionString){
362 std::cerr << "Error: did you provide class pairs names (-c) and integer values (-r) for each class in training vector?" << std::endl;
363 throw;
364 }
365 catch(string predefinedString){
366 std::cout << predefinedString << std::endl;
367 throw;
368 }
369 }