main.cpp 12.2 KB
Newer Older
DAUXAIS Yann's avatar
DAUXAIS Yann committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
#include <iostream>
#include <fstream>
#include <sstream>

#include <vector>
#include <list>
#include <map>

#include <signal.h>

#include <algorithm>
#include <boost/program_options.hpp>
#include <libltdl/lt_system.h>

#include "CDA.hh"
#include "Abstraction.hh"
#include "VerticalEventBase.hh"
#include "functions.hh"

CDA* cda = NULL;

void stopHandler(int){

          if (cda != NULL)
          	cda->stop = true;
}

using namespace boost;
namespace po = boost::program_options;

/**
 * 'Boilerplate' adapted from https://gist.github.com/ksimek/4a2814ba7d74f778bbee
 */
class Options
{
public:
	bool parse(int argc, char** argv)
	{
		std::vector<std::string> config_fnames;
		po::options_description general("General Options");
		general.add_options()
				("help", "Display this help message")
				("disc,d", po::value<std::string>(&gname),
				 "Extract discriminant chronicles using this file as negative dataset")
				("IBM,u", "Use IBM format for files instead of sequence per line")
				("mincs", po::value<unsigned> (&mincs), "Minimum size of extracted chronicles")
				("maxcs", po::value<unsigned> (&maxcs), "Maximum size of extracted chronicles")
48
				("tid", "Output the tid list in addition of extracted chronicles (first line is 0) /!\\ has to be proven to really correspond to the right line numbers")
DAUXAIS Yann's avatar
DAUXAIS Yann committed
49 50 51 52 53 54 55 56
				("close,c", "Extract frequent closed chronicles or discriminant chronicles from closed multisets if --disc is used")
				("json,j", "Output format is json instead of plain text")
				("verbose,v", "The program will speak")
				;

		po::options_description discriminant("Discriminant chronicles Options");
		discriminant.add_options()
				("gmin,g", po::value<float>(&gmin), "Minimal growth threshold\ndefault : 2")
57
				("episode,e", "Extract discriminant partially ordered patterns (episodes) instead of chronicles")
DAUXAIS Yann's avatar
DAUXAIS Yann committed
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
				;

		po::options_description frequent("Frequent chronicles Options");
		frequent.add_options()
				("all_different,a", "Extract chronicles with multisets containing at most one occurrence of an event")
				("cwm,w", po::value<unsigned>(&cwm),
				 "Define the maximal windows size for temporal constraints")
				("not_calc_freq,n", "If used, doesn't calculate exact frequency it's know bigger than fmin\n"
						"ignored if --close is used")
				;

		po::options_description desc;
		desc.add(general);
		desc.add(discriminant);
		desc.add(frequent);

		po::options_description hidden("Positional Options (required)");
		hidden.add_options()
				("input_file,i", po::value<std::string>(&fname)->required(),
				 "input file containing dataset to mine (string)\n"
						 "- positive dataset if --disc is used\n"
						 "positional : input_file")
				("fmin,f", po::value<float>(&fmin)->required(),
				 "minimal frequency threshold (number)\n"
						 "Number of sequences if >= 1 (support)\n"
						 "Percent of positive sequences number else\n"
						 "positional fmin")
				;

		po::positional_options_description p;
		p.add("input_file", 1);
		p.add("fmin", 1);

		po::variables_map vm;

		if (!notify(argc, argv, hidden, desc, p, vm)) return false;
		if(!parse_vm(vm)) return false;
		return parse_files(vm);
	}

private:
	bool notify(int argc, char** argv,
				const po::options_description& hidden,
				const po::options_description& desc,
				po::positional_options_description& p,
				po::variables_map& vm
	){
		po::options_description options;
		options.add(desc);
		options.add(hidden);
		bool need_help = false;

		try {
			po::store(po::command_line_parser(argc, (const char *const *) argv).
							  options(options).
							  positional(p).
							  run(),
					  vm);
		}
		catch(po::error &ex) {
			std::cout << ex.what() << std::endl << std::endl;
			need_help = true;
		}

		if (!need_help && !vm.count("help")) {
			try {
				po::notify(vm);
			}
			catch (po::error &ex) {
				std::cout << ex.what() << std::endl;
				need_help = true;
			}
		}
		else
			need_help = true;

		if(need_help)
		{
			std::cout << make_usage_string_(basename_(argv[0]), hidden, desc, p) << std::endl;
			return false;
		}
		return true;
	}

	bool parse_file(
			const std::string& filename,
			std::ifstream& fin,
			std::map<int, int>& sequences,
			std::vector<std::vector<Event>>& event_sequences,
			std::vector<std::vector<std::vector<int>>> &sequence_events

	) {
		std::string extension(filename);
		extension = extension.substr(extension.size() - 4, 4);

		try {
			if (!ibm)
				LineParser(fin, sequences, events, code_events, sequence_events);
			else if (extension.compare(".csv") == 0)
				CSVparser(fin, sequences, events, code_events, event_sequences, sequence_events);
			else
				TXTparser(fin, sequences, events, code_events, sequence_events);
			fin.close();
		}
		catch(...) {
			std::cerr << "Error during " << filename << " parsing." << std::endl;
			return false;
		}

		return true;
	}

	bool parse_files(po::variables_map& vm) {
		std::map<int, int> sequences;
		std::map<int, int> sequences2;

		std::vector<std::shared_ptr<TC>> base_pct;
		std::vector<std::shared_ptr<TC>> base_itv;

		std::vector<std::vector<Event>> event_sequences;
		std::vector<std::vector<std::vector<int>>> sequence_events;
		std::vector<std::vector<std::vector<int>>> sequence_events2;

		std::vector<std::vector<std::vector<Event>>> trace;
		std::vector<std::vector<std::vector<Event>>> trace2;

		if (verbose) std::cout << "Positive file parsing" << std::endl;
		if (!parse_file(fname, positives, sequences, event_sequences, sequence_events)) return false;

		if (disc) {
			if (verbose) std::cout << "Negative file parsing" << std::endl;
			if (!parse_file(gname, negatives, sequences2, event_sequences, sequence_events2)) return false;
		}

		for (unsigned int k = (unsigned) sequence_events.size(); k < code_events.size(); k++)
			sequence_events.push_back(std::vector<std::vector<int>>(sequences.size(), std::vector<int>()));

		abstractions = std::vector<int>(code_events.size(), -1);

		Abstraction::generatePathways<Event>((int) events.size(), trace, sequence_events);
		if (disc) {
			Abstraction::generatePathways<Event>((int) events.size(), trace2, sequence_events2);
			for (unsigned int k = (unsigned) trace.size(); k < trace2.size(); k++)
				trace.push_back(std::vector<std::vector<Event>>(trace[0].size(), std::vector<Event>()));
		}
		nb_se = (unsigned) abstractions.size();

		inv_events = std::vector<std::string>(events.size());
		for (auto e : events) inv_events[e.second] = e.first;

		setMinsup(trace[0].size());

		VerticalEventBase<Event>* base;
		base = new VerticalEventBase<Event>(trace,minsup);
		int tmp_cwm = -1;
		if (vm.count("cwm")) tmp_cwm = cwm;
		base->_cwm = tmp_cwm;
		b = base;
		b->classe = 0;

		if (disc) {
			base = new VerticalEventBase<Event>(trace2);
			base->_cwm = tmp_cwm;

			b2 = base;
			b2->classe = 1;
		}

		return true;
	}

	bool parse_vm(po::variables_map& vm) {
		if (vm.count("IBM")) ibm = true;
		if (vm.count("all_different")) dif = true;
		if (vm.count("close")) close = true;
233
		if (vm.count("episode")) episode = true;
DAUXAIS Yann's avatar
DAUXAIS Yann committed
234 235 236
		if (vm.count("not_calc_freq")) calc_freq = false;
		if (vm.count("json")) txt = false;
		if (vm.count("verbose")) verbose = true;
237
		if(vm.count("tid")) tid = true;
DAUXAIS Yann's avatar
DAUXAIS Yann committed
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366

		positives.open(fname);
		if (!positives) {
			std::cerr << "Unable to open " << fname << "." << std::endl;
			return false;
		}

		if (gname.compare("") != 0) {
			negatives.open(gname);
			if (!negatives) {
				std::cerr << "Unable to open " << gname << "." << std::endl;
				return false;
			}
			disc = true;
		}

		return true;
	}

	void setMinsup(unsigned long nb_seq) {
		if (fmin >= 1)
			minsup = (unsigned) ceil(fmin);
		else minsup = (unsigned) ceil(fmin * nb_seq);
	}

	std::string basename_(const std::string& p)
	{
#ifdef HAVE_BOOST_FILESYSTEM
		return boost::filesystem::path(p).stem().string();
#else
		size_t start = p.find_last_of("/");
		if(start == std::string::npos)
			start = 0;
		else
			++start;
		return p.substr(start);
#endif
	}

	std::vector<std::string> get_unlimited_positional_args_(const po::positional_options_description& p)
	{
		assert(p.max_total_count() == std::numeric_limits<unsigned>::max());
		std::vector<std::string> parts;
		const int MAX = 1000;
		std::string last = p.name_for_position(MAX);

		for(size_t i = 0; true; ++i)
		{
			std::string cur = p.name_for_position(i);
			if(cur == last)
			{
				parts.push_back(cur);
				parts.push_back('[' + cur + ']');
				parts.push_back("...");
				return parts;
			}
			parts.push_back(cur);
		}
		return parts;
	}

	std::string make_help_description(const std::string& program_name) {
		std::ostringstream oss;
		oss << "Description:" << std::endl;
		oss << program_name;
		oss << " implements the frequent chronicles extraction in timestamped sequences base." << std::endl;
		oss << "Using the --disc option, " << program_name << " is the implementation of DCM, ";
		oss << "an algorithm dedicated to extract discriminant frequent chronicles." << std::endl;

		return oss.str();
	}

	std::string make_usage_string_(
			const std::string& program_name,
			const po::options_description& hidden,
			const po::options_description& desc,
			po::positional_options_description& p)
	{
		std::vector<std::string> parts;
		parts.push_back("Usage: ");
		parts.push_back(program_name);
		size_t N = p.max_total_count();
		if(N == std::numeric_limits<unsigned>::max())
		{
			std::vector<std::string> args = get_unlimited_positional_args_(p);
			parts.insert(parts.end(), args.begin(), args.end());
		}
		else
		{
			for(size_t i = 0; i < N; ++i)
			{
				parts.push_back(p.name_for_position((int) i));
			}
		}
		if(desc.options().size() > 0)
		{
			parts.push_back("[options]");
		}
		std::ostringstream oss;
		oss << make_help_description(program_name) << std::endl;
		std::copy(
				parts.begin(),
				parts.end(),
				std::ostream_iterator<std::string>(oss, " "));
		oss << std::endl << hidden;
		oss << std::endl << desc;
		return oss.str();
	}

private:
	std::ifstream positives;
	std::ifstream negatives;
	std::string fname;
	std::string gname;
	bool ibm;
	float fmin;

public:

	unsigned cwm;
	unsigned minsup;
	unsigned nb_se;
	unsigned mincs;
	unsigned maxcs;

	float gmin;

	bool calc_freq;
	bool close;
367
	bool episode;
DAUXAIS Yann's avatar
DAUXAIS Yann committed
368 369 370 371
	bool disc;
	bool dif;
	bool txt;
	bool verbose;
372
	bool tid;
DAUXAIS Yann's avatar
DAUXAIS Yann committed
373 374 375 376 377 378 379 380 381

	std::map<std::string, int> events;
	std::vector<std::string> inv_events;
	std::vector<std::string> code_events;
	std::vector<int> abstractions;
	Base* b;
	Base* b2;

	Options() :	gname(""), ibm(false), cwm(0), mincs(0), maxcs(0), gmin(2),
382
				   calc_freq(true), close(false), episode(false), disc(false), dif(false), txt(true), verbose(false),
383
				   tid(false), b(NULL), b2(NULL) {}
DAUXAIS Yann's avatar
DAUXAIS Yann committed
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
};

int main(const int argc, char* argv[])
{
	Options options;
	if(!options.parse(argc, argv))
		return EXIT_FAILURE;

	std::vector<std::shared_ptr<TC>> base_pct;
	std::vector<std::shared_ptr<TC>> base_itv;

	CDA algo;

	if (!options.disc) {
		std::vector<bool> conclusion(options.code_events.size(),false);
		if (options.verbose) std::cout << "Constraints base generation" << std::endl;
		algo.CCDC(options.b, conclusion, (int) options.code_events.size(),
				  (int) options.abstractions.size(), options.minsup,
				  options.cwm, options.dif, false, base_pct, base_itv);
		if (options.verbose) std::cout << "Temporal constraints number: " << algo.nb_tc << std::endl;
		signal (SIGINT,stopHandler);
	}

	if (options.verbose) std::cout << "Chronicles mining" << std::endl;
408 409
	if (options.disc) 
		algo.inv_events = options.inv_events;
DAUXAIS Yann's avatar
DAUXAIS Yann committed
410
	algo.txt = options.txt;
411
	algo.extract_with_tid = options.tid;
DAUXAIS Yann's avatar
DAUXAIS Yann committed
412 413 414 415 416 417 418 419 420 421 422

	std::vector<Chronicle> res;
	bool disc_exec = true;

	if (!options.disc)
		res = algo.run(*options.b, base_pct, base_itv, NULL, options.minsup, (int) options.code_events.size(),
					   options.nb_se, options.verbose, options.cwm, options.mincs, options.maxcs,
					   options.close, options.dif, false, options.calc_freq);
	else
		disc_exec = algo.run (*options.b, *options.b2, options.minsup, options.gmin,
				  (int) options.code_events.size(), options.mincs,
423
				  options.maxcs, options.verbose, options.close, options.episode, false);
DAUXAIS Yann's avatar
DAUXAIS Yann committed
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440

	delete options.b;
	if (options.disc) delete options.b2;
	else {
		for (Chronicle c : res) {
			if (options.txt)
				std::cout << c.txt(options.inv_events, NULL) << std::endl;
			else
				std::cout << c.json(options.inv_events, NULL) << std::endl;
		}
	}

	if (options.verbose && disc_exec) std::cout << "-- End --" << std::endl;
	
	return EXIT_SUCCESS;
}