/**
* @file VCFeaturePool.cpp
* @brief standard interface to feature pool classifiers
* @author Erik Rodner
* @date 07.09.2007

*/
#include <iostream>

#include "VCFeaturePool.h"
#include "vislearning/features/fpfeatures/VectorFeature.h"
#include "core/image/ImageT.h"
//#include "core/imagedisplay/ImageDisplay.h"

using namespace OBJREC;

using namespace std;

using namespace NICE;

VCFeaturePool::VCFeaturePool(const Config *_conf, FeaturePoolClassifier *_fpc)
	: VecClassifier(_conf),	fpc(_fpc)
{
	dimension = 0;
	this->conf = _conf;

	readFeaturePool = conf->gB("VCFeaturePool", "read_feature_pool", false);
	featurePoolCache = conf->gS("VCFeaturePool", "feature_pool_cache", "features.txt");
}

VCFeaturePool::~VCFeaturePool()
{
}

ClassificationResult VCFeaturePool::classify(const NICE::Vector & x) const
{
	NICE::Vector *v = new NICE::Vector(x);
	Example pe(v);
	ClassificationResult r = fpc->classify(pe);
	delete v;
	return r;
}

void VCFeaturePool::teach(const LabeledSetVector & teachSet)
{
	maxClassNo = teachSet.getMaxClassno();
	dimension = teachSet.dimension();
	LOOP_ALL(teachSet)
	{
		EACH(classno, x);
		NICE::Vector *v = new Vector(x);
		examples.push_back(	pair<int, Example> (classno, Example(v)));
	}
}

void VCFeaturePool::setMaxClassNo(int maxClassNo)
{
	VecClassifier::setMaxClassNo(maxClassNo);
	fpc->setMaxClassNo(maxClassNo);
}

void VCFeaturePool::clear()
{
	fpc->clear();
	examples.clear();
}

void VCFeaturePool::store(std::ostream & os, int format) const
{
	fpc->store(os, format);
}

void VCFeaturePool::restore(std::istream & is, int format)
{
	fpc->restore(is, format);
}

void VCFeaturePool::finishTeaching()
{
	FeaturePool fp(conf);

	if (readFeaturePool)
	{
		fprintf(stderr, "VCFeaturePool: reading features from %s\n", featurePoolCache.c_str());
		fp.read(featurePoolCache);
		fprintf(stderr, "VCFeaturePool: %d features read\n", (int)fp.size());
		fp.initRandomFeatureSelection();
	}
	else
	{
		Feature *f = new VectorFeature(dimension);
		f->explode(fp);
		delete f;
	}

	fpc->train(fp, examples);

	//FIXME: this will destroy all the copies of fp too
	//fp.destroy();
	examples.clean();
}
