ITANUPCFilterSegmentation.cpp 15.7 KB
Newer Older
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
#include "ITANUPCFilterSegmentation.h"

#include <algorithm>
#include <iostream>
#include <string>
#include <sstream>

#include <ITAException.h>
#include <ITAStringUtils.h>

#ifdef ITA_CONVOLUTION_NUPCONV_WITH_XML_READER

#include <QSX.h>
using namespace QSX;
// XML Schema used for validation of the single filtersegmentation file format
#define FSEG_XML_SCHEMA "\
<?xml version=\"1.0\"?>\n\
\n\
<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n\
	<xs:complexType name=\"filtersegmentType\">\n\
		<xs:simpleContent>\n\
			<xs:extension base=\"xs:positiveInteger\">\n\
				<xs:attribute name=\"multiplicity\" type=\"xs:positiveInteger\"/>\n\
			</xs:extension>\n\
		</xs:simpleContent>\n\
	</xs:complexType>\n\
	\n\
	<xs:simpleType name=\"decimalGreaterZero\">\n\
		<xs:restriction base=\"xs:decimal\">\n\
			<xs:minExclusive value=\"0\"/>\n\
		</xs:restriction>\n\
	</xs:simpleType>\n\
	\n\
	<xs:element name=\"filtersegmentation\">\n\
		<xs:complexType>\n\
			<xs:sequence>\n\
				<xs:element name=\"filtersegment\" type=\"filtersegmentType\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n\
			</xs:sequence>\n\
			\n\
			<xs:attribute name=\"samplerate\" type=\"decimalGreaterZero\" use=\"required\"/>\n\
			<xs:attribute name=\"length\" type=\"xs:nonNegativeInteger\"/>\n\
			<xs:attribute name=\"parts\" type=\"xs:nonNegativeInteger\"/>\n\
		</xs:complexType>\n\
	</xs:element>\n\
</xs:schema>"

#endif

FILTERSEGMENT fseg_make( int iPartlength, int iMultiplicity ) {
	FILTERSEGMENT fs;
	fs.iPartlength = iPartlength, fs.iMultiplicity = iMultiplicity;
	return fs;
};

FILTERSEGMENTATION fseg_vector( const FILTERSEGMENT* pfsFSegs, int iNumFSegs ) {
	FILTERSEGMENTATION result;
	for( int i = 0; i < iNumFSegs; i++ ) result.push_back( pfsFSegs[ i ] );
	return result;
}

FILTERSEGMENTATION fseg_tidy( const FILTERSEGMENTATION& vFSegs ) {
	FILTERSEGMENTATION result;

	// Ensure that no part is negative and the series is nondecreasing
	// Remove parts whose multiplicity is 0
	int l = 1;
	int s = 0;
	for( FILTERSEGMENTATION::const_iterator cit = vFSegs.begin(); cit != vFSegs.end(); ++cit ) {
		if( ( ( *cit ).iPartlength < 0 ) || ( ( *cit ).iPartlength < l ) || ( ( *cit ).iMultiplicity < 0 ) )
			ITA_EXCEPT1( INVALID_PARAMETER, "Not a causal binary partition" );

		if( ( *cit ).iMultiplicity > 0 ) {
			// Causality check
			if( ( cit != vFSegs.begin() ) && ( s < ( *cit ).iPartlength ) )
				ITA_EXCEPT1( INVALID_PARAMETER, "Not a causal binary partition" );

			result.push_back( *cit );

			s += ( *cit ).iPartlength * ( *cit ).iMultiplicity;
		}

		l = ( *cit ).iPartlength;
	}

	// Stuff same parts following each other together
	int i = 0;
	while( i < ( int ) result.size() ) {
		while( ( ( i + 1 ) < ( int ) result.size() ) && ( result[ i + 1 ].iPartlength == result[ i ].iPartlength ) ) {
			result[ i ].iMultiplicity += result[ i + 1 ].iMultiplicity;
			result.erase( result.begin() + i + 1 );
		}
		i++;
	}

	return result;
}

FILTERSEGMENTATION fseg_load( const std::string& sFilename, double* pdSamplerate, int* piLength, int* piNumParts )
{
	FILTERSEGMENTATION segs_checked;

#ifdef ITA_CONVOLUTION_NUPCONV_WITH_XML_READER
	XMLNode* root = 0;

	try {
		/* Read the filtersegmentation from the given XML file and
		   validate it against the filtersegmentation XML schema */
		root = XMLNode::loadXMLDocument(sFilename,
			XMLNode::XML_SCHEMA_VALIDATION | XMLNode::READ_FROM_STRING,
			FSEG_XML_SCHEMA);

		double samplerate = 0;
		int length = -1;
		int numparts = -1;

		// The "samplerate" attribute is mandatory
		samplerate = root->getAttributeAsDouble("samplerate");

		if (root->hasAttribute("length"))
			length = root->getAttributeAsInt("length");

		if (root->hasAttribute("parts"))
			numparts = root->getAttributeAsInt("parts");

		/* We known that all nodes directly below the root node are "filtersegment" nodes */
		std::list<XMLNode*> children = root->getChildren();
		FILTERSEGMENTATION segs;
		for (std::list<XMLNode*>::const_iterator cit=children.begin(); cit!=children.end(); ++cit) {
			XMLNode* child = *cit;
			FILTERSEGMENT seg;
			seg.iPartlength = child->getContentAsInt();

			if (child->hasAttribute("multiplicity"))
				seg.iMultiplicity = child->getAttributeAsInt("multiplicity");
			else
				seg.iMultiplicity = 1;

			segs.push_back(seg);
		}

		// Free the XML document
		delete root;

		// More semantical checks that cannot be done via XML Schemata
		int l=0;
		int p=0;
		for (FILTERSEGMENTATION::const_iterator cit=segs.begin(); cit!=segs.end(); ++cit) {
			l += (*cit).iPartlength * (*cit).iMultiplicity;
			p += (*cit).iMultiplicity;
		}

		if ((length != -1) && (length != l))
			std::cout << "Warning: The filtersegmentation file \"" << sFilename << 
			"\" contains a wrong \"length\" attribute (Should be " << l << ")" << std::endl;

		if ((numparts != -1) && (numparts != p))
			std::cout << "Warning: The filtersegmentation file \"" << sFilename << 
			"\" contains a wrong \"parts\" attribute (Should be " << p << ")" << std::endl;

		// Check and correct the segmentation
		segs_checked = fseg_tidy(segs);

		if (segs.size() != segs_checked.size())
			std::cout << "Note: The filtersegmentation file \"" << sFilename << "\" is untidy" << std::endl;

		if (pdSamplerate) *pdSamplerate = samplerate;
		if (piLength) *piLength = l;
		if (piNumParts) *piNumParts = p;

	} 
	catch (XMLException& e)
	{
		delete root;
		std::cerr << "XML-Exception: " << e.toString() << std::endl;
		ITA_EXCEPT1(UNKNOWN, std::string("XML-Exception: ") + e.toString());
}

	return segs_checked;

#else // ITA_CONVOLUTION_NUPCONV_WITH_XML_READER
	ITA_EXCEPT1( NOT_IMPLEMENTED, "Read/write of filter segmentation with XML file format not supported" );
#endif
}

void fseg_store( const std::string& sFilename, const FILTERSEGMENTATION& vFSegs, double dSamplerate, std::string sComment )
{

	/* Add the attributes for the length and number of parts */
	FILTERSEGMENTATION segs = fseg_tidy( vFSegs );
	int iLength = 0;
	int iParts = 0;
	for( FILTERSEGMENTATION::const_iterator cit = segs.begin(); cit != segs.end(); ++cit )
	{
		iLength += ( ( *cit ).iPartlength * ( *cit ).iMultiplicity );
		iParts += (*cit).iMultiplicity;
	}

#ifdef ITA_CONVOLUTION_NUPCONV_WITH_XML_READER
	XMLNode* root = 0;

	// Initialize the XML parser library
	try {
		root = XMLNode::createEmptyXMLDocument("filtersegmentation");
		root->setAttribute("samplerate", dSamplerate);
		root->setAttribute("length", iLength);
		root->setAttribute("parts", iParts);

		/* Write a child node for each filter segment */
		for (FILTERSEGMENTATION::const_iterator cit=segs.begin(); cit != segs.end(); ++cit) {
			XMLNode* child = root->addChild("filtersegment", (*cit).iPartlength);
			if ((*cit).iMultiplicity > 0)
				child->setAttribute("multiplicity", (*cit).iMultiplicity);
		}

		// Write the XML document into the file. Afterwards free it...
		XMLNode::storeXMLDocument(root, sFilename);

	} catch (XMLException& e) {
		delete root;
		ITA_EXCEPT1( IO_ERROR, e.toString() );
	}
#else // ITA_CONVOLUTION_NUPCONV_WITH_XML_READER
	ITA_EXCEPT1( NOT_IMPLEMENTED, "Read/write of filter segmentation with XML file format not supported" );
#endif
}

int fseg_len( const FILTERSEGMENTATION& vFSegs )
{
	int s = 0;
	for( FILTERSEGMENTATION::const_iterator cit = vFSegs.begin(); cit != vFSegs.end(); ++cit )
		s += ( cit->iPartlength * cit->iMultiplicity );
	return s;
}

std::string fseg_str( const FILTERSEGMENTATION& vFSegs )
{
	std::stringstream ss;
	//for (FILTERSEGMENTATION::const_iterator cit=vFSegs.begin(); cit!=vFSegs.end(); ++cit)
	//	ss << (*cit).iPartlength << "^" << (*cit).iMultiplicity << " ";
	for( int i = 0; i < ( int ) vFSegs.size(); i++ )
		if( vFSegs[ i ].iMultiplicity > 0 )
			ss << vFSegs[ i ].iPartlength << "^" << vFSegs[ i ].iMultiplicity << " ";
	return ss.str();
}

#ifdef ITA_CONVOLUTION_NUPCONV_WITH_PERFORMANCE_LOGGER
ITASerializationBuffer& operator>>( ITASerializationBuffer& buffer, FILTERSEGMENT& seg )
{
	return buffer >> seg.iPartlength >> seg.iMultiplicity;
}

ITASerializationBuffer& operator<<( ITASerializationBuffer& buffer, const FILTERSEGMENT& seg )
{
	return buffer << seg.iPartlength << seg.iMultiplicity;
}
#endif


// XML Schema used for validation of the signel filtersegmentation file format
#define FSEGCOLL_XML_SCHEMA "\
<?xml version=\"1.0\"?>\n\
\n\
<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n\
	<xs:complexType name=\"filtersegmentType\">\n\
		<xs:simpleContent>\n\
			<xs:extension base=\"xs:positiveInteger\">\n\
				<xs:attribute name=\"multiplicity\" type=\"xs:positiveInteger\"/>\n\
			</xs:extension>\n\
		</xs:simpleContent>\n\
	</xs:complexType>\n\
	\n\
	<xs:simpleType name=\"decimalGreaterZero\">\n\
		<xs:restriction base=\"xs:decimal\">\n\
			<xs:minExclusive value=\"0\"/>\n\
		</xs:restriction>\n\
	</xs:simpleType>\n\
	\n\
	<xs:complexType name=\"filtersegmentationType\">\n\
		<xs:sequence>\n\
			<xs:element name=\"filtersegment\" type=\"filtersegmentType\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n\
		</xs:sequence>\n\
		\n\
		<xs:attribute name=\"samplerate\" type=\"decimalGreaterZero\" use=\"required\"/>\n\
		<xs:attribute name=\"length\" type=\"xs:nonNegativeInteger\"/>\n\
		<xs:attribute name=\"parts\" type=\"xs:nonNegativeInteger\"/>\n\
	</xs:complexType>\n\
	\n\
	<xs:element name=\"filtersegmentation_collection\">\n\
		<xs:complexType>\n\
			<xs:sequence>\n\
				<xs:element name=\"filtersegmentation\" type=\"filtersegmentationType\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n\
			</xs:sequence>\n\
		</xs:complexType>\n\
	</xs:element>\n\
</xs:schema>"


FSegCollection::FSegCollection() {}

FSegCollection::FSegCollection( const std::string& sFilename )
{
#ifdef ITA_CONVOLUTION_NUPCONV_WITH_XML_READER

	XMLNode* root = 0;
	FILTERSEGMENTATION segs_checked;

	try {
		/* Read the filtersegmentation from the given XML file and
		   validate it against the filtersegmentation XML schema */
		root = XMLNode::loadXMLDocument(sFilename,
			XMLNode::XML_SCHEMA_VALIDATION | XMLNode::READ_FROM_STRING,
			FSEGCOLL_XML_SCHEMA);

		std::list<XMLNode*> fseg_nodes = root->getChildren();

		for (std::list<XMLNode*>::iterator it=fseg_nodes.begin(); it!=fseg_nodes.end(); ++it) {
			XMLNode* fseg = *it;

			// Quick & dirty bugfix: Skip non "filtersegmentation" nodes
			//if (fseg->getName() != "filtersegmentation") continue;

			double samplerate = 0;
			int length = -1;
			int numparts = -1;

			// The "samplerate" attribute is mandatory
			samplerate = fseg->getAttributeAsDouble("samplerate");

			if (fseg->hasAttribute("length"))
				length = fseg->getAttributeAsInt("length");

			if (fseg->hasAttribute("parts"))
				numparts = fseg->getAttributeAsInt("parts");

			/* We known that all nodes directly below the root node are "filtersegment" nodes */
			std::list<XMLNode*> children = fseg->getChildren();
			FILTERSEGMENTATION segs;
			for (std::list<XMLNode*>::const_iterator cit=children.begin(); cit!=children.end(); ++cit) {
				XMLNode* child = *cit;
				FILTERSEGMENT seg;
				seg.iPartlength = child->getContentAsInt();

				if (child->hasAttribute("multiplicity"))
					seg.iMultiplicity = child->getAttributeAsInt("multiplicity");
				else
					seg.iMultiplicity = 1;

				segs.push_back(seg);
			}

			// More semantical checks that cannot be done via XML Schemata
			int l=0;
			int p=0;
			for (FILTERSEGMENTATION::const_iterator cit=segs.begin(); cit!=segs.end(); ++cit) {
				l += (*cit).iPartlength * (*cit).iMultiplicity;
				p += (*cit).iMultiplicity;
			}

			// Check and correct the segmentation
			segs_checked = fseg_tidy(segs);

			addSegmentation(segs_checked, fseg->getAttributeAsDouble("samplerate"));
		}

		// Free the XML document
		delete root;

	} catch (XMLException& e) {
		delete root;
		std::cerr << "XML-Exception: " << e.toString() << std::endl;
		ITA_EXCEPT1( UNKNOWN, std::string( "XML-Exception: " ) + e.toString() );
}

#else // ITA_CONVOLUTION_NUPCONV_WITH_XML_READER
	ITA_EXCEPT1( NOT_IMPLEMENTED, "Read/write of filter segmentation with XML file format not supported" );
#endif
}

void FSegCollection::store( const std::string& sFilename )
{

#ifdef ITA_CONVOLUTION_NUPCONV_WITH_XML_READER

	XMLNode* root = 0;

	// Initialize the XML parser library
	try {
		root = XMLNode::createEmptyXMLDocument("filtersegmentation_collection");

		for (std::vector<Item>::const_iterator cit=m_vItems.begin(); cit!=m_vItems.end(); ++cit) {
			XMLNode* segnode = root->addChild("filtersegmentation");
			segnode->setAttribute("samplerate", cit->dSamplerate);
			segnode->setAttribute("length", cit->iLength);
			segnode->setAttribute("parts", (int) cit->vSeg.size());

			/* Write a child node for each filter segment */
			for (FILTERSEGMENTATION::const_iterator cit2=cit->vSeg.begin(); cit2 != cit->vSeg.end(); ++cit2) {
				XMLNode* child = segnode->addChild("filtersegment", cit2->iPartlength);
				if (cit2->iMultiplicity > 0)
					child->setAttribute("multiplicity", cit2->iMultiplicity);
			}
		}

		// Write the XML document into the file. Afterwards free it...
		XMLNode::storeXMLDocument(root, sFilename);

	} catch (XMLException& e) {
		delete root;
		ITA_EXCEPT1( IO_ERROR, e.toString() );
	}

#else // ITA_CONVOLUTION_NUPCONV_WITH_XML_READER
	ITA_EXCEPT1( NOT_IMPLEMENTED, "Read/write of filter segmentation with XML file format not supported" );
#endif
}

int FSegCollection::size() const {
	return ( int ) m_vItems.size();
}

void FSegCollection::getSegmentationByIndex( int iIndex, FILTERSEGMENTATION& vDest, double* pdSamplerate, int* piLength ) const{
	if( ( iIndex < 0 ) || ( iIndex >= ( int ) m_vItems.size() ) )
		ITA_EXCEPT1( INVALID_PARAMETER, "Index out of bounds" );

	vDest = m_vItems[ iIndex ].vSeg;
	if( pdSamplerate != nullptr ) *pdSamplerate = m_vItems[ iIndex ].dSamplerate;
	if( piLength != nullptr ) *piLength = m_vItems[ iIndex ].iLength;
}

int FSegCollection::getSegmentation( int iLength, double dSamplerate, FILTERSEGMENTATION& vDest ) const {
	// Search all items for the segmentation having the smallest length greater or equal
	for( std::vector<Item>::const_iterator cit = m_vItems.begin(); cit != m_vItems.end(); ++cit )
		if( ( cit->iLength >= iLength ) && ( cit->dSamplerate == dSamplerate ) ) {
		// Exact match
		vDest = cit->vSeg;
		return ( cit->iLength == iLength ? EXACT_MATCH : NEXT_LONGER );
		}

	return NO_MATCH;
}

void FSegCollection::addSegmentation( const FILTERSEGMENTATION& vSeg, double dSamplerate ) {
	int iLength = fseg_len( vSeg );

	if( iLength == 0 )
		ITA_EXCEPT1( INVALID_PARAMETER, "Empty segmentations may not be added" );

	// Search if a segmentation of the exact length is already contained. If so: Replace it.
	for( std::vector<Item>::iterator it = m_vItems.begin(); it != m_vItems.end(); ++it )
		if( ( it->iLength == iLength ) && ( it->dSamplerate == dSamplerate ) ) {
		it->vSeg = vSeg;
		return;
		}

	// New length: Insert and maintain the order.
	Item item;
	item.iLength = iLength;
	item.dSamplerate = dSamplerate;
	item.vSeg = vSeg;
	m_vItems.push_back( item );
	std::sort( m_vItems.begin(), m_vItems.end(), ItemOrder() );
}

void FSegCollection::removeSegmentationByIndex( int iIndex ) {
	if( ( iIndex < 0 ) || ( iIndex >= ( int ) m_vItems.size() ) )
		ITA_EXCEPT1( INVALID_PARAMETER, "Index out of bounds" );

	m_vItems.erase( m_vItems.begin() + iIndex );
}

void FSegCollection::removeSegmentation( int iLength, double dSamplerate ) {
	// Search the segmentation of the exact length
	for( std::vector<Item>::iterator it = m_vItems.begin(); it != m_vItems.end(); ++it )
		if( ( it->iLength == iLength ) && ( it->dSamplerate == dSamplerate ) ) {
		m_vItems.erase( it );
		return;
		}

	ITA_EXCEPT1( INVALID_PARAMETER, "No segmentation of the given length contained" );
}

std::string FSegCollection::toString() const {
	if( m_vItems.empty() )
		return "Empty filter segmentation collection";

	std::string s = "Filter segmentatation collection:\n\n";
	for( std::vector<Item>::const_iterator cit = m_vItems.begin(); cit != m_vItems.end(); ++cit )
		s += IntToString( cit->iLength ) + ":\t" + fseg_str( cit->vSeg ) + "\n";

	return s;
}