FileReaderVOTable.cc 16.2 KB
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 48 49 50 51 52 53 54 55 56 57 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 233 234 235 236 237 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 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
/*
 * FileReaderVOTable.cc
 *
 *  Created on: Nov 24, 2014
 *  Author: AKKA
 */

#include <boost/algorithm/string/trim_all.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>

#include <libxml/xmlreader.h>

#include "TimeUtil.hh"
#include "FileReaderVOTable.hh"

namespace AMDA {
namespace LocalFileInterface {

// 32 KB is the maximum supported line size
int FileReaderVOTable::MaxLineSize = 32 * 1024;

FileReaderVOTable::FileReaderVOTable() :
		_votFilePath(), _dataFloat(NULL), _dataDouble(NULL), _dataShort(NULL), _dataInt(NULL), _data(
				NULL) {
}

FileReaderVOTable::~FileReaderVOTable() {
}

/**
 * Parses XML file and looks for FIELD and PARAM element containing parameters informations
 */
void FileReaderVOTable::getVOTableInfo(void) {

	const xmlChar *name;
	const xmlChar *fieldId;
	const xmlChar *fieldName;
	const xmlChar *fieldXType;
	const xmlChar *fieldArraySize;
	const xmlChar *fieldDataType;
	const xmlChar *groupId;
	const xmlChar *paramName;
	const xmlChar *paramSize;
	const xmlChar *paramValue;

	bool parsingTable = false;
	bool parsingField = false;
	bool parsingGroup = false;
	bool parsingParam = false;

	std::string crtGroupId;

	// Clear current field informations
	_fieldsInfo.clear();

	//Clear current param informations
	_paramsInfo.clear();

	// created XML reader
	xmlTextReaderPtr reader = xmlReaderForFile(_votFilePath.c_str(), NULL, 0);

	// read xml file tag by tag
	while (xmlTextReaderRead(reader) == 1) {

		// -- read tag
		name = xmlTextReaderConstName(reader);
		if (name != NULL) {
			// get tag name to easily handle it
			std::string tagName = std::string((const char*) name);

			if (tagName == "TABLE") {
				parsingTable = !parsingTable;
			}

			if ((parsingTable == true) && (tagName == "GROUP")) {
				// parsing group is set when we are on the start element only,
				// this will prevent problems if GROUP tag ends width />
				parsingGroup = (xmlTextReaderNodeType(reader) == 1);

				if (parsingGroup == true) {
					groupId = xmlTextReaderGetAttribute(reader,
						(const xmlChar*) "ID");

					if (groupId != NULL)
					{
						crtGroupId = std::string((const char*) groupId);
						xmlFree((xmlChar *) groupId);
					}
					else
						crtGroupId = "";
				}
				else
					crtGroupId = "";
			}

			if ((parsingTable == true) && (tagName == "PARAM")) {
				// parsing param is set when we are on the start element only,
				// this will prevent problems if PARAM tag ends width />
				parsingParam = (xmlTextReaderNodeType(reader) == 1);

				if (parsingParam == true) {
					// Create e new param Info
					boost::shared_ptr<ParamInfo> paramInfo(new ParamInfo);

					paramName = xmlTextReaderGetAttribute(reader,
						(const xmlChar*) "name");
					paramSize = xmlTextReaderGetAttribute(reader,
						(const xmlChar*) "arraysize");
					paramValue = xmlTextReaderGetAttribute(reader,
						(const xmlChar*) "value");

					paramInfo->setGroupId(crtGroupId);

					if (paramName != NULL)
					{
						paramInfo->setName((const char *) paramName);
						xmlFree((xmlChar *) paramName);
					}

					if (paramSize != NULL)
					{
						paramInfo->setSize((const char *) paramSize);
						xmlFree((xmlChar *) paramSize);
					}

					if (paramValue != NULL)
					{
						paramInfo->setValue((const char *) paramValue);
						xmlFree((xmlChar *) paramValue);
					}

					LOG4CXX_INFO(gLogger, 	"PARAM :  " << tagName <<
										", GROUP ID = " << paramInfo->getGroupId() <<
										", name = " << paramInfo->getName() <<
										", arraysize = " << paramInfo->getSize() <<
										", value = " << paramInfo->getValue());
					_paramsInfo.push_back(paramInfo);
				}
			}

			if ((parsingTable == true) && (tagName == "FIELD")) {
				// parsing field is set when we are on the start element only,
				// this will prevent problems if FIELD tag ends width />
				parsingField = (xmlTextReaderNodeType(reader) == 1);

				if (parsingField == true) {
					// Create e new field Info
					boost::shared_ptr<FieldInfo> fieldInfo(new FieldInfo);

					fieldId = xmlTextReaderGetAttribute(reader,
							(const xmlChar*) "ID");
					fieldName = xmlTextReaderGetAttribute(reader,
							(const xmlChar*) "name");
					fieldXType = xmlTextReaderGetAttribute(reader,
							(const xmlChar*) "xtype");
					fieldArraySize = xmlTextReaderGetAttribute(reader,
							(const xmlChar*) "arraysize");
					fieldDataType = xmlTextReaderGetAttribute(reader,
							(const xmlChar*) "datatype");

					if (fieldId != NULL)
					{
						fieldInfo->setId((const char *) fieldId);
						xmlFree((xmlChar *) fieldId);
					}

					if (fieldName != NULL)
					{
						fieldInfo->setName((const char *) fieldName);
						xmlFree((xmlChar *) fieldName);
					}

					if (fieldXType != NULL)
					{
						fieldInfo->setXtype((const char *) fieldXType);
						xmlFree((xmlChar *)  fieldXType);
					}

					if (fieldArraySize != NULL)
					{
						fieldInfo->setSize((const char *) fieldArraySize);
						xmlFree((xmlChar *) fieldArraySize);
					}

					if (fieldDataType != NULL)
					{
						fieldInfo->setType((const char *) fieldDataType);
						xmlFree((xmlChar *) fieldDataType);
					}

					LOG4CXX_INFO(gLogger, 	"FIELD :  " << tagName <<
											", ID = " << fieldInfo->getId() <<
											", name = " << fieldInfo->getName() <<
											", xtype = " << fieldInfo->getXtype() <<
											", arraysize = " << fieldInfo->getSize() <<
											", datatype = " << fieldInfo->getType());
					_fieldsInfo.push_back(fieldInfo);
				}
			}

			// Stop reading fields informations when data starts
			if (tagName == "TABLEDATA")
				break;

		}
	}

	xmlFreeTextReader(reader);
}

/**
 * Retrieve TR line position in the VOTable file where time >= timeStart
 */
int FileReaderVOTable::getStartTimePos(int timeColumn, double timeStart) {

	const xmlChar *name;

	bool parsingTableData = false;
	bool parsingTR = false;
	bool parsingTD = false;

	int curTR = -1;
	int curTD = -1;

	// created XML reader
	xmlTextReaderPtr reader = xmlReaderForFile(_votFilePath.c_str(), NULL, 0);

	// read xml file tag by tag
	while (xmlTextReaderRead(reader) == 1) {

		// -- read tag
		name = xmlTextReaderConstName(reader);
		if (name != NULL) {
			// get tag name to easily handle it
			std::string tagName = std::string((const char*) name);

			if (tagName == "TABLEDATA") {
				parsingTableData = !parsingTableData;
			}

			// Detect start TR element
			if ((parsingTableData == true) && (tagName == "TR")) {
				parsingTR = !parsingTR;

				// Increment TR count
				// Reset TD count
				if (parsingTR == true) {
					curTR++;
					curTD = -1;
				}
			}

			// Detect start TD element
			if ((parsingTR == true) && (tagName == "TD")) {
				parsingTD = !parsingTD;

				// Increment TD count
				if (parsingTD == true)
					curTD++;
			}

			// Detect TD #text element
			if ((parsingTD == true) && (tagName == "#text")) {
				const xmlChar *text = xmlTextReaderConstValue(reader);

				// Current TD correspond with timeColumn ?
				if (curTD == timeColumn) {
					// Convert ISO time
					double lineTime = TimeUtil::readTimeInIso((char *) text);

					// Current line time is >= requested time start ?
					if (lineTime >= timeStart)
					{
						xmlFreeTextReader(reader);
						return (curTR);
					}
				}
			}
		}
	}

	xmlFreeTextReader(reader);

	LOG4CXX_ERROR(gLogger,
			"FileReaderVOTable::getFieldsStartTimePos - Cannot get record index");
	return (-1);
}

std::vector<std::string> &FileReaderVOTable::split(const std::string &s, char delim, std::vector<std::string> &elems) {
	std::stringstream ss(s);
	std::string item;
	while (std::getline(ss, item, delim)) {
		if (item.empty())
			continue;
		elems.push_back(item);
	}
	return elems;
}

FileReaderStatus FileReaderVOTable::getParamPacketData(int timeColumn, int paramColumn, int recordIndex, double stopTime,
		LocalParamDataPacket *packet) {
	const xmlChar *name;

	bool parsingTableData = false;
	bool parsingTR = false;
	bool parsingTD = false;

	int curTR = -1;
	int curTD = -1;

	double lineTime = 0;
	bool packetFull;

	std::string columnValues;

	// created XML reader
	xmlTextReaderPtr reader = xmlReaderForFile(_votFilePath.c_str(), NULL, 0);

	// read xml file tag by tag
	while (xmlTextReaderRead(reader) == 1) {

		// -- read tag
		name = xmlTextReaderConstName(reader);
		if (name != NULL) {
			// get tag name to easily handle it
			std::string tagName = std::string((const char*) name);

			if (tagName == "TABLEDATA") {
				parsingTableData = !parsingTableData;
			}

			// Detect start TR element
			if ((parsingTableData == true) && (tagName == "TR")) {
				parsingTR = !parsingTR;

				// Increment TR count
				// Reset TD count
				if (parsingTR == true) {
					curTR++;
					curTD = -1;
				}

				// Detect the end of a TR element ?
				// If so, and current time is not 0, write packet
				if ((parsingTR == false) && (lineTime != 0)) {

					std::vector<std::string> paramList;
					split (columnValues, ' ', paramList);

					if (((int) paramList.size()) == packet->getDimsSize()) {
						// Extract values on the line depending on their type
						for (int p=0;p<(int) paramList.size(); p++) {
							if (packet->getType() == TYPE_FLOAT)
								_dataFloat[p] = std::stof(paramList.at(p));
							else if (packet->getType() == TYPE_DOUBLE)
								_dataDouble[p] = std::stod(paramList.at(p));
							else if (packet->getType() == TYPE_SHORT)
								_dataShort[p] = (short) std::stof(paramList.at(p));
							else if (packet->getType() == TYPE_INT)
								_dataInt[p] = (int) std::stoi(paramList.at(p));
						}
					} else {
						LOG4CXX_ERROR(gLogger,
								"FileReaderASCII::getParamPacketData - Wrong dimension for parameter");
						xmlFreeTextReader(reader);
						return FRS_ERROR;
					}

					//add data record in the packet
					if (!packet->addData(lineTime, _data, packetFull)) {
						if (packetFull) {
							xmlFreeTextReader(reader);
							return FRS_MORE;
						}

						LOG4CXX_ERROR(gLogger,
								"FileReaderASCII::getParamPacketData - Error to add data in packet");
						xmlFreeTextReader(reader);
						return FRS_ERROR;
					}
				}
			}

			// Detect start TD element
			if ((parsingTR == true) && (tagName == "TD")) {
				parsingTD = !parsingTD;

				// Increment TD count
				if (parsingTD == true)
					curTD++;
			}

			// Wait for recordIndex TR to start extraction
			if (curTR < recordIndex)
				continue;

			// time for the current line is greater than stopTime
			// we have finished !
			if (lineTime > stopTime) {
				xmlFreeTextReader(reader);
				return FRS_FINISH;
			}

			// Detect TD #text element
			if ((parsingTD == true) && (tagName == "#text")) {
				const xmlChar *text = xmlTextReaderConstValue(reader);

				// Current TD correspond with timeColumn ?
				// Yes record current time
				if (curTD == timeColumn) {
					lineTime = TimeUtil::readTimeInIso((char *) text);
				}

				// Current TD correspond with parameter columns ?
				// Yes record them
				if (curTD == paramColumn) {
					columnValues = std::string((const char *) text);
				}
			}
		}
	}

	xmlFreeTextReader(reader);

	return FRS_EOF;
}

bool FileReaderVOTable::open(std::string filePath) {
	// Store votTable filePath
	_votFilePath = filePath;

	return (boost::filesystem::exists(filePath));
}

bool FileReaderVOTable::close(void) {
	return (true);
}

bool FileReaderVOTable::isOpened(void) {
	return (false);
}

std::string FileReaderVOTable::getTimeParamId(void) {
	LOG4CXX_DEBUG(gLogger, "FileReaderVOTable::getTimeParamId");

	// Read fields informations from the VOTable file
	getVOTableInfo();

	for (auto fieldInfo : _fieldsInfo) {
		if (fieldInfo->getXtype() == "dateTime") {
			if (fieldInfo->getId().empty() == false)
				return fieldInfo->getId();
			else
				return fieldInfo->getName();
		}
	}

	// Time parameter id is always at the first position in text files
	return std::string("");
}

bool FileReaderVOTable::getParamInfo(std::string& paramId,
		LocalParamType& paramType, int& dim1Size, int& dim2Size) {
	LOG4CXX_DEBUG(gLogger, "FileReaderVOTable::getParamInfo");

	// Read fields informations from the VOTable file
	getVOTableInfo();

	for (auto fieldInfo : _fieldsInfo) {
		// if Id is set check for corresponding paramId with Id, otherwise, use Name
		if ((fieldInfo->getId() == paramId)
				|| (fieldInfo->getName() == paramId)) {

			if (fieldInfo->getType() == "float")
				paramType = LocalParamType::TYPE_FLOAT;
			else if (fieldInfo->getType() == "double")
				paramType = LocalParamType::TYPE_DOUBLE;
			else if (fieldInfo->getType() == "short")
				paramType = LocalParamType::TYPE_SHORT;
			else if (fieldInfo->getType() == "int")
				paramType = LocalParamType::TYPE_INT;
			else
				// If field (data)type is not supported, suppose it's double
				paramType = LocalParamType::TYPE_DOUBLE;

			std::vector<std::string> dims;
			boost::split(dims, fieldInfo->getSize(), boost::is_any_of("*"));
			if (dims.empty())
			{
				dim1Size = 1;
				dim2Size = 1;
			}
			else if (dims.size() == 1)
			{
				dim1Size = std::stoi(dims[0]);
				dim2Size = 1;
			}
			else if (dims.size() == 2)
			{
				dim1Size = std::stoi(dims[0]);
				dim2Size = std::stoi(dims[1]);
			}
			else
			{
				LOG4CXX_ERROR(gLogger, "FileReaderVOTable::getParamInfo - Unknown dimensions");
				return false;
			}

			return true;
		}
	}

	// Parameter types and size can't be determined by the reader
	return false;
}

int FileReaderVOTable::getRecordIndex(std::string& timeId, double time) {
	LOG4CXX_DEBUG(gLogger, "FileReaderVOTable::getRecordIndex");

	// Read fields informations from the VOTable file
	getVOTableInfo();

	int timeColumn = -1;
	for (int f = 0; f < (int) _fieldsInfo.size(); f++) {
		if ((_fieldsInfo.at(f)->getId() == timeId)
				|| (_fieldsInfo.at(f)->getName() == timeId)) {
			timeColumn = f;
		}
	}

	if (timeColumn != -1)
		return getStartTimePos(timeColumn, time);
	else {
		LOG4CXX_ERROR(gLogger,
				"FileReaderVOTable::getRecordIndex - timeColumn was not found : " << timeId);
		return -1;
	}
}

FileReaderStatus FileReaderVOTable::getParamPacketData(std::string& timeId,
		std::string& paramId, int recordIndex, double stopTime,
		LocalParamDataPacket *packet) {
	LOG4CXX_DEBUG(gLogger, "FileReaderVOTable::getParamPacketData");

	// Read fields informations from the VOTable file
	getVOTableInfo();

	int timeColumn = -1;
	for (int f = 0; f < (int) _fieldsInfo.size(); f++) {
		if ((_fieldsInfo.at(f)->getId() == timeId)
				|| (_fieldsInfo.at(f)->getName() == timeId)) {
			timeColumn = f;
		}
	}

	if (timeColumn == -1) {
		LOG4CXX_ERROR(gLogger,
				"FileReaderVOTable::getParamPacketData - timeColumn was not found : " << timeId);
		return FRS_ERROR;
	}

	int paramColumn = -1;

	for (int f = 0; f < (int) _fieldsInfo.size(); f++) {
		if ((_fieldsInfo.at(f)->getId() == paramId)
				|| (_fieldsInfo.at(f)->getName() == paramId)) {
			paramColumn = f;
		}
	}

	// Prepare buffers used by packet->addData
	if ((packet->getType() != TYPE_FLOAT) &&
		(packet->getType() != TYPE_DOUBLE) &&
		(packet->getType() != TYPE_SHORT) &&
		(packet->getType() != TYPE_INT)) {
		LOG4CXX_ERROR(gLogger,
				"FileReaderVOTable::getParamPacketData - Not supported packet type");
		return FRS_ERROR;
	}

	_dataFloat  = NULL;
	_dataDouble = NULL;
	_dataShort  = NULL;
	_dataInt    = NULL;


	if (packet->getType() == TYPE_FLOAT) {
		_dataFloat = new float[packet->getDimsSize()];
		_data = _dataFloat;
	} else if (packet->getType() == TYPE_DOUBLE) {
		_dataDouble = new double[packet->getDimsSize()];
		_data = _dataDouble;
	} else if (packet->getType() == TYPE_SHORT) {
		_dataShort = new short[packet->getDimsSize()];
		_data = _dataShort;
	} else if (packet->getType() == TYPE_INT) {
		_dataInt = new int[packet->getDimsSize()];
		_data = _dataInt;
	}

	// Get values from VOTable file by parsint it
	FileReaderStatus ret = getParamPacketData(timeColumn, paramColumn,
			recordIndex, stopTime, packet);

	delete[] _dataFloat;
	delete[] _dataDouble;
	delete[] _dataShort;
	delete[] _dataInt;

	return ret;
}

/*
 * @brief Get an information
 */
bool FileReaderVOTable::getInfo(const char* pInfoName, std::vector<double>& res)
{
	res.clear();

	// Read fields and params  informations from the VOTable file
	getVOTableInfo();

	for (auto paramInfo : _paramsInfo) {
		if (strcmp(paramInfo->getName().c_str(), pInfoName) == 0)
		{
			std::vector<std::string> valueList;
			split (paramInfo->getValue(), ' ', valueList);

			for (auto val : valueList)
			{
				res.push_back(std::stof(val));
			}
			return true;
		}
	}

	return false;
}

} /* LocalFileInterface */
} /* AMDA */