MultiDataset.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. /**
  2. * @file MultiDataset.cpp
  3. * @brief multiple datasets
  4. * @author Erik Rodner
  5. * @date 02/08/2008
  6. */
  7. #include <iostream>
  8. #include <sys/stat.h>
  9. #include <sys/types.h>
  10. #ifdef WIN32
  11. #ifdef NICE_USELIB_BOOST
  12. #include "boost/filesystem.hpp"
  13. #endif
  14. #endif
  15. #include "vislearning/cbaselib/ClassNames.h"
  16. #include "core/basics/StringTools.h"
  17. #include "core/basics/FileMgt.h"
  18. #include "core/basics/FileName.h"
  19. #include "vislearning/cbaselib/MultiDataset.h"
  20. using namespace OBJREC;
  21. using namespace std;
  22. using namespace NICE;
  23. #undef DEBUG_MultiDataset
  24. void MultiDataset::selectExamples ( const std::string & examples_command,
  25. const LabeledSet & base,
  26. LabeledSet & positives,
  27. LabeledSet & negatives,
  28. const ClassNames & cn ) const
  29. {
  30. vector<string> examples;
  31. StringTools::split ( examples_command, ';', examples );
  32. set<int> processed_classes;
  33. for ( vector<string>::const_iterator i = examples.begin();
  34. i != examples.end();
  35. i++ )
  36. {
  37. const std::string & cmd = *i;
  38. vector<string> parts;
  39. StringTools::split ( cmd, ' ', parts );
  40. if ( (parts.size() != 3) && ((parts.size() != 2) || (parts[0].compare("all") != 0)) )
  41. {
  42. std::cerr << "parts.size(): "<<parts.size()<<std::endl;
  43. std::cerr << " parts[0]: " << parts[0] << std::endl;
  44. fthrow( Exception, "Syntax error " << examples_command );
  45. }
  46. const std::string & mode = parts[0];
  47. const std::string & csel = parts[1];
  48. double parameter = (parts.size() == 3 ) ? atof(parts[2].c_str()) : 0.0;
  49. map<int, int> fpe;
  50. set<int> selection;
  51. cn.getSelection ( csel, selection );
  52. for ( set<int>::const_iterator j = selection.begin();
  53. j != selection.end();
  54. j++ )
  55. {
  56. int classno = *j;
  57. if ( processed_classes.find(classno) == processed_classes.end() )
  58. {
  59. #ifdef DEBUG_MultiDataset
  60. fprintf (stderr, "class %s: %s %d\n", cn.text(classno).c_str(),
  61. mode.c_str(), (int)parameter );
  62. #endif
  63. fpe[*j] = (int)parameter;
  64. processed_classes.insert(classno);
  65. } else {
  66. if ( csel != "*" ) {
  67. fthrow ( Exception, "Example selection method for class %s has multiple specifications" << cn.text(classno) );
  68. }
  69. }
  70. }
  71. if ( mode == "seq" ) {
  72. LabeledSetSelection<LabeledSet>::selectSequential (
  73. fpe, base, positives, negatives );
  74. #ifdef DEBUG_MultiDataset
  75. fprintf (stderr, "MultiDataset: after special seq selection: %d\n", positives.count() );
  76. #endif
  77. } else if ( mode == "step" ) {
  78. LabeledSetSelection<LabeledSet>::selectSequentialStep (
  79. fpe, base, positives, negatives );
  80. #ifdef DEBUG_MultiDataset
  81. fprintf (stderr, "MultiDataset: after special step selection: %d\n", positives.count() );
  82. #endif
  83. } else if ( mode == "random" ) {
  84. LabeledSetSelection<LabeledSet>::selectRandom (
  85. fpe, base, positives, negatives );
  86. #ifdef DEBUG_MultiDataset
  87. fprintf (stderr, "MultiDataset: after special random selection: %d\n", positives.count() );
  88. #endif
  89. } else if ( mode == "all" ) {
  90. if ( (int)selection.size() == cn.numClasses() )
  91. {
  92. // preserve permutation
  93. LabeledSet::Permutation permutation;
  94. base.getPermutation ( permutation );
  95. for ( LabeledSet::Permutation::iterator i = permutation.begin(); i != permutation.end(); i++ )
  96. {
  97. int classno = i->first;
  98. ImageInfo *element = const_cast< ImageInfo * > ( i->second );
  99. positives.add_reference ( classno, element );
  100. }
  101. } else {
  102. LabeledSetSelection<LabeledSet>::selectClasses ( selection, base, positives, negatives );
  103. }
  104. #ifdef DEBUG_MultiDataset
  105. fprintf (stderr, "MultiDataset: after special class selection: %d\n", positives.count() );
  106. #endif
  107. } else {
  108. fthrow ( Exception, "Wrong value for parameter example\n");
  109. }
  110. }
  111. #ifdef DEBUG_MultiDataset
  112. fprintf (stderr, "MultiDataset: after special selection operations: %d\n", positives.count() );
  113. #endif
  114. set<int> allclasses;
  115. cn.getSelection ( "*", allclasses );
  116. set<int> allnegative_classes;
  117. // add all examples from allclasses \setminus processed_classes
  118. set_difference(allclasses.begin(), allclasses.end(), processed_classes.begin(), processed_classes.end(),
  119. inserter(allnegative_classes, allnegative_classes.end()));
  120. LabeledSet dummy;
  121. LabeledSetSelection<LabeledSet>::selectClasses ( allnegative_classes,
  122. base, negatives, dummy );
  123. }
  124. /** MultiDataset ------- constructor */
  125. MultiDataset::MultiDataset( const Config *conf , LabeledSetFactory *pSetFactory)
  126. {
  127. //read all blocks from our config file
  128. std::set<string> blocks;
  129. conf->getAllBlocks ( blocks );
  130. #ifdef DEBUG_MultiDataset
  131. std::cerr << "found the following config blocks: " << std::endl;
  132. for ( std::set<string>::const_iterator blockIt = blocks.begin(); blockIt != blocks.end(); blockIt++)
  133. {
  134. std::cerr << *blockIt << " ";
  135. }
  136. std::cerr << std::endl;
  137. #endif
  138. lfl.setFactory( pSetFactory );
  139. //for every dataset (e.g., train and test), we store a single confog file
  140. map<string, Config> dsconfs;
  141. //for every dataset (e.g., train and test), we store the position of the file directory
  142. map<string, string> dirs;
  143. //first of all, remove all blocks which do correspond to specified datasets, i.e., that do not contain a "dataset" entry
  144. for ( set<string>::iterator i = blocks.begin();
  145. i != blocks.end(); )
  146. {
  147. if ( conf->gB(*i, "disable", false) )
  148. {
  149. i++;
  150. continue;
  151. }
  152. std::string dataset = conf->gS( *i, "dataset", "unknown" );
  153. if ( dataset == "unknown" )
  154. blocks.erase(i++);
  155. else {
  156. #ifdef DEBUG_MultiDataset
  157. fprintf (stderr, "Reading dataset config for block [%s]\n", i->c_str() );
  158. #endif
  159. NICE::FileName t_ConfigFilename( conf->getFilename() );
  160. NICE::FileName t_DatasetFilename( dataset );
  161. // check for relative path correction:
  162. // if dataset is a relative path, then make it absolute using the
  163. // given config's directory
  164. if( t_DatasetFilename.isRelative() )
  165. {
  166. dataset = t_ConfigFilename.extractPath().str() + dataset;
  167. }
  168. std::string sDatasetConfFilename = dataset + "/dataset.conf";
  169. Config dsconf ( sDatasetConfFilename.c_str() );
  170. dirs[*i] = dataset;
  171. dsconfs[*i] = dsconf;
  172. i++;
  173. }
  174. }
  175. #ifdef DEBUG_MultiDataset
  176. std::cerr << "found the following datasets within all config blocks: " << std::endl;
  177. for ( std::set<string>::const_iterator blockIt = blocks.begin(); blockIt != blocks.end(); blockIt++)
  178. {
  179. std::cerr << *blockIt << " ";
  180. }
  181. std::cerr << std::endl;
  182. #endif
  183. //is there a dataset specified that contains images for both, training and testing?
  184. if ( blocks.find("traintest") != blocks.end() )
  185. {
  186. LabeledSet ls_base;
  187. LabeledSet ls_train (true);
  188. LabeledSet ls_nontrain (true);
  189. LabeledSet ls_test (true);
  190. LabeledSet dummy (true);
  191. LabeledSet temp (true);
  192. bool localizationInfoDisabled = conf->gB("traintest", "disable_localization_info", false );
  193. std::string classselection_train = conf->gS("traintest", "classselection_train", "*");
  194. std::string classselection_test = conf->gS("traintest", "classselection_test", "*");
  195. classnames["traintest"] = ClassNames();
  196. std::string classNamesTxt = dirs["traintest"] + "/classnames.txt";
  197. if ( FileMgt::fileExists ( classNamesTxt ) )
  198. {
  199. classnames["traintest"].read ( classNamesTxt );
  200. } else {
  201. classnames["traintest"].readFromConfig ( dsconfs["traintest"], classselection_train );
  202. }
  203. lfl.get ( dirs["traintest"], dsconfs["traintest"], classnames["traintest"], ls_base,
  204. localizationInfoDisabled, conf->gB("traintest", "debug_dataset", false ) );
  205. std::string examples_train = conf->gS("traintest", "examples_train" );
  206. selectExamples ( examples_train, ls_base, ls_train, ls_nontrain, classnames["traintest"] );
  207. set<int> selection_test;
  208. classnames["traintest"].getSelection ( classselection_test, selection_test );
  209. std::string examples_test = conf->gS("traintest", "examples_test" );
  210. if ( examples_test == "reclassification" )
  211. {
  212. LabeledSetSelection<LabeledSet>::selectClasses
  213. ( selection_test, ls_train, ls_test, dummy );
  214. } else {
  215. selectExamples ( examples_test, ls_nontrain, temp, dummy, classnames["traintest"] );
  216. LabeledSetSelection<LabeledSet>::selectClasses
  217. ( selection_test, temp, ls_test, dummy );
  218. }
  219. classnames["train"] = classnames["traintest"];
  220. classnames["test"] = ClassNames ( classnames["traintest"], classselection_test );
  221. datasets["test"] = ls_test;
  222. datasets["train"] = ls_train;
  223. }
  224. //now read files for every specified dataset (e.g., train and test)
  225. for ( set<string>::const_iterator i = blocks.begin();
  226. i != blocks.end();
  227. i++ )
  228. {
  229. std::string name = *i;
  230. std::cerr << "read: " << name << std::endl;
  231. if ( classnames.find(name) != classnames.end() )
  232. continue;
  233. if ( conf->gB(name, "disable", false) == true )
  234. continue;
  235. if ( dsconfs.find(name) == dsconfs.end() )
  236. continue;
  237. LabeledSet ls_base;
  238. LabeledSet ls (true);
  239. LabeledSet dummy (true);
  240. LabeledSet temp (true);
  241. bool localizationInfoDisabled = conf->gB(name, "disable_localization_info", false );
  242. std::string classselection = conf->gS(name, "classselection", "*");
  243. classnames[name] = ClassNames();
  244. std::string classNamesTxt = dirs[name] + "/classnames.txt";
  245. if ( FileMgt::fileExists ( classNamesTxt ) )
  246. {
  247. #ifdef DEBUG_MultiDataset
  248. fprintf (stderr, "MultiDataset: reading class names from %s\n", classNamesTxt.c_str() );
  249. #endif
  250. classnames[name].read ( classNamesTxt );
  251. } else {
  252. #ifdef DEBUG_MultiDataset
  253. fprintf (stderr, "MultiDataset: reading class names from dataset config file\n" );
  254. #endif
  255. classnames[name].readFromConfig ( dsconfs[name], classselection );
  256. }
  257. #ifdef DEBUG_MultiDataset
  258. std::cerr << "we set up everything to read this dataset - so now call lfl.get" << std::endl;
  259. #endif
  260. lfl.get ( dirs[name],
  261. dsconfs[name],
  262. classnames[name],
  263. ls_base,
  264. localizationInfoDisabled,
  265. conf->gB(name, "debug_dataset", false ) );
  266. #ifdef DEBUG_MultiDataset
  267. fprintf (stderr, "MultiDataset: class names -->\n" );
  268. classnames[name].store ( cerr );
  269. fprintf (stderr, "MultiDataset: all information about %s set obtained ! (size %d)\n", name.c_str(), ls_base.count() );
  270. #endif
  271. #ifdef DEBUG_MultiDataset
  272. std::cerr << "we now call selectExamples to pick only a subset if desired" << std::endl;
  273. #endif
  274. std::string examples = conf->gS(name, "examples", "all *" );
  275. selectExamples ( examples, ls_base, ls, dummy, classnames[name] );
  276. #ifdef DEBUG_MultiDataset
  277. fprintf (stderr, "MultiDataset: size after selection %d\n", ls.count() );
  278. #endif
  279. datasets[name] = ls;
  280. }
  281. bool dumpSelections = conf->gB("datasets", "dump_selection", false);
  282. if ( dumpSelections )
  283. {
  284. for ( map<string, LabeledSet>::const_iterator i = datasets.begin();
  285. i != datasets.end(); i++ )
  286. {
  287. const std::string & name = i->first;
  288. const LabeledSet & ls = i->second;
  289. const ClassNames & classNames = classnames[name];
  290. #ifdef WIN32
  291. #ifdef NICE_USELIB_BOOST
  292. boost::filesystem::path t_path(name.c_str());
  293. boost::filesystem::create_directory(t_path);
  294. #else
  295. fthrow(Exception,"mkdir function not defined on system. try using boost lib and rebuild library");
  296. #endif
  297. #else
  298. mkdir ( name.c_str(), 0755 );
  299. #endif
  300. std::string filelist = name + "/files.txt";
  301. ofstream olist ( filelist.c_str(), ios::out );
  302. if ( !olist.good() )
  303. fthrow (IOException, "Unable to dump selections to " << filelist );
  304. LOOP_ALL_S(ls)
  305. {
  306. EACH_S(classno, file);
  307. std::string classtext = classNames.code(classno);
  308. olist << classtext << " " << file << endl;
  309. }
  310. olist.close();
  311. std::string datasetconf = name + "/dataset.conf";
  312. ofstream oconf ( datasetconf.c_str(), ios::out );
  313. if ( !oconf.good() )
  314. fthrow (IOException, "Unable to dump selections to " << datasetconf );
  315. set<int> classnos;
  316. classNames.getSelection ( "*", classnos);
  317. oconf << "[main]" << endl;
  318. oconf << "filelist = \"files.txt\"" << endl << endl;
  319. oconf << "[classnames]" << endl;
  320. for ( set<int>::const_iterator i = classnos.begin();
  321. i != classnos.end(); i++ )
  322. {
  323. const std::string & code = classNames.code(*i);
  324. const std::string & text = classNames.text(*i);
  325. oconf << code << " = \"" << text << "\"" << endl;
  326. }
  327. oconf.close();
  328. classNames.save ( name + "/classnames.txt" );
  329. }
  330. }
  331. }
  332. MultiDataset::~MultiDataset()
  333. {
  334. }
  335. const ClassNames & MultiDataset::getClassNames ( const std::string & key ) const
  336. {
  337. map<string, ClassNames>::const_iterator i = classnames.find(key);
  338. if ( i == classnames.end() )
  339. {
  340. fprintf (stderr, "MultiDataSet::getClassNames() FATAL ERROR: dataset <%s> not found !\n", key.c_str() );
  341. exit(-1);
  342. }
  343. return (i->second);
  344. }
  345. ClassNames & MultiDataset::getClassNamesNonConst ( const std::string & key )
  346. {
  347. std::map<string, ClassNames>::iterator i = classnames.find(key);
  348. if ( i == classnames.end() )
  349. {
  350. fprintf (stderr, "MultiDataSet::getClassNamesNonConst() FATAL ERROR: dataset <%s> not found !\n", key.c_str() );
  351. exit(-1);
  352. }
  353. return (i->second);
  354. }
  355. const LabeledSet *MultiDataset::operator[] ( const std::string & key ) const
  356. {
  357. map<string, LabeledSet>::const_iterator i = datasets.find(key);
  358. if ( i == datasets.end() )
  359. {
  360. fprintf (stderr, "MultiDataSet: FATAL ERROR: dataset <%s> not found !\n", key.c_str() );
  361. exit(-1);
  362. }
  363. return &(i->second);
  364. }
  365. const LabeledSet *MultiDataset::at ( const std::string & key ) const
  366. {
  367. map<string, LabeledSet>::const_iterator i = datasets.find(key);
  368. if ( i == datasets.end() )
  369. return NULL;
  370. else
  371. return &(i->second);
  372. }