예제 #1
0
/*----------------------------------------------------------------------------------------------------------------------
|	This function provides the ability to read everything following the block name (which is read by the NxsReader 
|	object) to the END or ENDBLOCK statement. Characters are read from the input stream `in'. Overrides the pure 
|	virtual function in the base class.
*/
void NxsEmptyBlock::Read(
  NxsToken &token)	/* the token used to read from `in'*/
	{
	isEmpty = false;

	// This should be the semicolon after the block name
	//
	token.GetNextToken();

	if (!token.Equals(";"))
		{
		errormsg = "Expecting ';' after ";
		errormsg += id;
		errormsg += " block name, but found ";
		errormsg += token.GetToken();
		errormsg += " instead";
		throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
		}

	for(;;)
		{
		token.GetNextToken();

		if (token.Equals("END"))
			{
			HandleEndblock(token);
			break;
			}

		else if(token.Equals("ENDBLOCK"))
			{
			HandleEndblock(token);
			break;
			}

		else
			{
			SkippingCommand(token.GetToken());

			do
				{
				token.GetNextToken();
				}
			while (!token.AtEOF() && !token.Equals(";"));

			if (token.AtEOF())
				{
				errormsg = "Unexpected end of file encountered";
				throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
				}
			}
		}
	}
예제 #2
0
/*!
	Called from HandleMatrix function to read in the next state. Returns true if next token encountered is a comma,
	false otherwise. A comma signals the end of data for the current taxon in an UNALIGNED block.
*/
bool NxsUnalignedBlock::HandleNextState(
  NxsToken & token,			/* is the token used to read from `in' */
  unsigned taxNum,				/* is the row in range [0..ntax) (used for error reporting only) */
  unsigned charNum,				/* is the column (used for error reporting only) */
  NxsDiscreteStateRow & row, const NxsString &nameStr)	/* is the container for storing new state */
	{
	token.SetLabileFlagBit(NxsToken::parentheticalToken);
	token.SetLabileFlagBit(NxsToken::curlyBracketedToken);
	token.SetLabileFlagBit(NxsToken::singleCharacterToken);

	token.GetNextToken();

	if (token.Equals(",") || token.Equals(";"))
		return false;
	const NxsString stateAsNexus = token.GetToken();
	const NxsDiscreteStateCell stateCode = mapper.EncodeNexusStateString(stateAsNexus, token, taxNum, charNum, NULL, nameStr);
	if (charNum < row.size())
		row[charNum] = stateCode;
	else
		{
		while (charNum < row.size())
			row.push_back(NXS_INVALID_STATE_CODE);
		row.push_back(stateCode);
		}
	return true;
	}
예제 #3
0
void NxsTaxaAssociationBlock::Read(
    NxsToken &token) /* the token used to read from `in' */
{
    isEmpty = false;

    DemandEndSemicolon(token, "BEGIN TAXAASSOCIATION");

    for (;; )
    {
        token.GetNextToken();
        NxsBlock::NxsCommandResult res = HandleBasicBlockCommands(token);
        if (res == NxsBlock::NxsCommandResult(STOP_PARSING_BLOCK))
        {
            return;
        }
        if (res != NxsBlock::NxsCommandResult(HANDLED_COMMAND))
        {
            if (token.Equals("TAXA"))
            {
                HandleTaxaCommand(token);
            }
            else if (token.Equals("ASSOCIATES"))
            {
                HandleAssociatesCommand(token);
            }
            else
            {
                SkipCommand(token);
            }
        }
    }
}
예제 #4
0
/*----------------------------------------------------------------------------------------------------------------------
|	Called when the HELP command needs to be parsed from within the GarliReader block.
*/
void GarliReader::HandleHelp(
  NxsToken &token)	/* the token used to read from `in' */
	{
	// Retrieve all tokens for this command, stopping only in the event
	// of a semicolon or an unrecognized keyword
	//
	for (;;)
		{
		token.GetNextToken();

		if (token.Equals(";"))
			{
			break;
			}
		else
			{
			errormsg = "Unexpected keyword (";
			errormsg += token.GetToken();
			errormsg += ") encountered reading HELP command";
			throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
			}
		}

	message = "\nExamples of use of available commands:";
	message += "\n  help                     -> shows this message";
	message += "\n  log file=mylog.txt start -> opens log file named mylog.txt";
	message += "\n  log stop                 -> closes current log file";
	message += "\n  exe mydata.nex           -> executes nexus file mydata.nex";
	message += "\n  show                     -> reports on blocks currently stored";
	message += "\n  quit                     -> terminates application";
	message += "\n";
	PrintMessage();
	}
예제 #5
0
/*----------------------------------------------------------------------------------------------------------------------
|	Stores the next token as the this->blockid field.
*/
void NxsBlock::HandleBlockIDCommand(NxsToken & token)
	{
	token.GetNextToken();
	if (token.Equals(";"))
		GenerateUnexpectedTokenNxsException(token, "an id for the block");
	blockIDString = token.GetToken();
	DemandEndSemicolon(token, "BLOCKID");
	}
예제 #6
0
/*----------------------------------------------------------------------------------------------------------------------
	Called whenever a file name needs to be read from either the command line or a file. Expects next token to be "="
	followed by the token representing the file name. Call this function after, say, the keyword "file" has been read
	in the following LOG command:
>
	log file=doofus.txt start replace;
>
	Note that this function will read only the "=doofus.txt " leaving "start replace;" in the stream for reading at
	a later time.
*/
NxsString BASICCMDLINE::GetFileName(
  NxsToken & token)	/* is the token used to read from `in' */
	{
	// Eat the equals sign
	token.GetNextToken();

	if (!token.Equals("="))
		{
		errormsg = "Expecting an equals sign, but found ";
		errormsg += token.GetToken();
		errormsg += " instead";
		throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
		}

	// Now get the filename itself
	token.GetNextToken();

	return token.GetToken();
	}
예제 #7
0
void NxsTaxaAssociationBlock::HandleTaxaCommand(
    NxsToken &token)
{
    if (!this->nexusReader)
    {
        NxsNCLAPIException("No NxsReader when reading TaxaAssociation block.");
    }

    token.GetNextToken();
    this->firstTaxaBlock = this->ProcessTaxaBlockName(token.GetTokenReference(), token);
    token.GetNextToken();
    if (!token.Equals(","))
    {
        errormsg << "Expecting comma in the TAXA command, found \"" << token.GetTokenReference() << "\".";
        throw NxsException(errormsg, token);
    }
    token.GetNextToken();
    this->secondTaxaBlock = this->ProcessTaxaBlockName(token.GetTokenReference(), token);
    NxsToken::DemandEndSemicolon(token, this->errormsg, "TAXA");
}
예제 #8
0
bool NxsReader::ReadUntilEndblock(NxsToken &token, const std::string & )
	{
	for (;;)
		{
		token.GetNextToken();
		if (token.Equals("END") || token.Equals("ENDBLOCK")) 
			{
			token.GetNextToken();
			if (!token.Equals(";")) 
				{
				std::string errormsg = "Expecting ';' after END or ENDBLOCK command, but found ";
				errormsg += token.GetToken();
				errormsg += " instead";
				NexusError(NxsString(errormsg.c_str()), token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
				return false;
				}
			return true;
			}
		}
	}
예제 #9
0
/*!
	This function provides the ability to read everything following the block name (which is read by the NxsReader
	object) to the END or ENDBLOCK statement. Characters are read from the input stream `in'. Overrides the abstract
	virtual function in the base class.
*/
void NxsUnalignedBlock::Read(
  NxsToken & token)	/* is the token used to read from `in' */
	{
	isEmpty = false;
	isUserSupplied = true;

	// This should be the semicolon after the block name
	token.GetNextToken();
	if (!token.Equals(";"))
		{
		errormsg = "Expecting ';' after ";
		errormsg += NCL_BLOCKTYPE_ATTR_NAME;
		errormsg += " block name, but found ";
		errormsg += token.GetToken();
		errormsg += " instead";
		throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
		}
	nTaxWithData = 0;

	for (;;)
		{
		token.GetNextToken();
		NxsBlock::NxsCommandResult res = HandleBasicBlockCommands(token);
		if (res == NxsBlock::NxsCommandResult(STOP_PARSING_BLOCK))
			return;
		if (res != NxsBlock::NxsCommandResult(HANDLED_COMMAND))
			{
			if (token.Equals("DIMENSIONS"))
				HandleDimensions(token);
			else if (token.Equals("FORMAT"))
				HandleFormat(token);
			else if (token.Equals("TAXLABELS"))
				HandleTaxLabels(token);
			else if (token.Equals("MATRIX"))
				HandleMatrix(token);
			else
				SkipCommand(token);
			}
		}	// for (;;)
	}
예제 #10
0
/*only used it the linkAPI is enabled*/
void NxsTaxaBlockSurrogate::HandleLinkTaxaCommand(NxsToken & token)
	{
	token.GetNextToken();
	const std::map<std::string, std::string> kv = token.ProcessAsSimpleKeyValuePairs("LINK");
	std::map<std::string, std::string>::const_iterator pairIt = kv.begin();
	for (;pairIt != kv.end(); ++pairIt)
		{
		NxsTaxaBlockAPI *entryTaxa = taxa;
		int entryTaxaLinkStatus = taxaLinkStatus;
		NxsString key(pairIt->first.c_str());
		key.ToUpper();
		NxsString value(pairIt->second.c_str());
		if (key == "TAXA")
			{
			if (taxa && !taxa->GetID().EqualsCaseInsensitive(value))
				{
				if (GetTaxaLinkStatus() & NxsBlock::BLOCK_LINK_USED)
					{
					NxsString errormsg = "LINK to a Taxa block must occur before commands that use a taxa block";
					throw NxsException(errormsg, token);
					}
				SetTaxaBlockPtr(NULL, NxsBlock::BLOCK_LINK_UNINITIALIZED);
				}
			if (!taxa)
				{
				if (!nxsReader)
					{
					NxsString errormsg =  "API Error: No nxsReader during parse in NxsTaxaBlockSurrogate::HandleLinkTaxaCommand";
					throw NxsNCLAPIException(errormsg, token);
					}
				NxsTaxaBlockAPI * cb = nxsReader->GetTaxaBlockByTitle(value.c_str(), NULL);
				if (cb == NULL)
					{
					NxsString errormsg = "Unknown TAXA block (";
					errormsg += value;
					errormsg +=") referred to in the LINK command";
					taxa = entryTaxa;
					taxaLinkStatus = entryTaxaLinkStatus;
					throw NxsException(errormsg, token);
					}
				SetTaxaBlockPtr(cb, NxsBlock::BLOCK_LINK_FROM_LINK_CMD);
				}				
			}
		else
			{
			NxsString errormsg = "Skipping unknown LINK subcommand: ";
			errormsg += pairIt->first.c_str();
			nxsReader->NexusWarnToken(errormsg, NxsReader::SKIPPING_CONTENT_WARNING, token);
			errormsg.clear(); //this token pos will be off a bit.
			}
		}
	}
예제 #11
0
/*!
	Advances the token, and returns the unsigned int that the token represents

 	Sets errormsg and raises a NxsException on failure.
	`contextString` is used in error messages:
		"Expecting ';' to terminate the ${contextString} command"
*/
void NxsToken::DemandEndSemicolon(NxsToken &token, NxsString & errormsg, const char *contextString)
	{
	token.GetNextToken();
	if (!token.Equals(";"))
		{
		errormsg = "Expecting ';' to terminate the ";
		errormsg += contextString;
		errormsg += " command, but found ";
		errormsg += token.GetToken();
		errormsg += " instead";
		throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
		}
	}
예제 #12
0
파일: nxstaxablock.cpp 프로젝트: cran/rncl
/*! Other than the commands handled by NxsBlock::HandleBasicBlockCommands(), this
	function will deal with Dimensions and call NxsTaxaBlock::HandleTaxLabels()
	to parse the TaxLabels commands.

	All other commands will be skipped
*/
void NxsTaxaBlock::Read(
  NxsToken &token)	/* the token used to read from in */
	{
	Reset();
	isEmpty				= false;
	isUserSupplied		= true;

	DemandEndSemicolon(token, "BEGIN TAXA");

	for (;;)
		{
		token.GetNextToken();
		NxsBlock::NxsCommandResult res = HandleBasicBlockCommands(token);
		if (res == NxsBlock::NxsCommandResult(STOP_PARSING_BLOCK))
			return;
		if (res != NxsBlock::NxsCommandResult(HANDLED_COMMAND))
			{
			if (token.Equals("DIMENSIONS"))
				{
				token.GetNextToken();
				if (!token.Equals("NTAX"))
					{
					errormsg = "Expecting NTAX keyword, but found ";
					errormsg += token.GetToken();
					errormsg += " instead";
					throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
					}
				DemandEquals(token, "after NTAX");
				dimNTax = DemandPositiveInt(token, "NTAX");
				taxLabels.reserve(dimNTax);
				DemandEndSemicolon(token, "DIMENSIONS");
				}	// if (token.Equals("DIMENSIONS"))
			else if (token.Equals("TAXLABELS"))
				HandleTaxLabels(token);
			else
				SkipCommand(token);
			}
		}	// GetNextToken loop
	}
예제 #13
0
/*!
	Called when DIMENSIONS command needs to be parsed from within the UNALIGNED block. Deals with everything after the
	token DIMENSIONS up to and including the semicolon that terminates the DIMENSIONS command.
*/
void NxsUnalignedBlock::HandleDimensions(
  NxsToken & token)			/* the token used to read from `in' */
	{
	unsigned ntaxRead = 0;
	for (;;)
		{
		token.GetNextToken();
		if (token.Equals("NEWTAXA"))
			newtaxa = true;
		else if (token.Equals("NTAX"))
			{
			DemandEquals(token, "after NTAX in DIMENSIONS command");
			ntaxRead = DemandPositiveInt(token, "NTAX");
			}
		else if (token.Equals(";"))
			break;
		}
	if (newtaxa)
		{
		if (ntaxRead == 0)
			{
			errormsg = "DIMENSIONS command must have an NTAX subcommand when the NEWTAXA option is in effect.";
			throw NxsException(errormsg, token);
			}
		AssureTaxaBlock(createImpliedBlock, token, "Dimensions");
		if (!createImpliedBlock)
			{
			taxa->Reset();
			if (nexusReader)
				nexusReader->RemoveBlockFromUsedBlockList(taxa);
			}
		taxa->SetNtax(ntaxRead);
		nTaxWithData = ntaxRead;
		}
	else
		{
		AssureTaxaBlock(false, token, "Dimensions");
		const unsigned ntaxinblock = taxa->GetNTax();
		if (ntaxinblock == 0)
			{
			errormsg = "A TAXA block must be read before character data, or the DIMENSIONS command must use the NEWTAXA.";
			throw NxsException(errormsg, token);
			}
		if (ntaxinblock < ntaxRead)
			{
			errormsg = "NTAX in UNALIGNED block must be less than or equal to NTAX in TAXA block\nNote: one circumstance that can cause this error is \nforgetting to specify NTAX in DIMENSIONS command when \na TAXA block has not been provided";
			throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
			}
		nTaxWithData = (ntaxRead == 0 ? ntaxinblock : ntaxRead);
		}
	}
예제 #14
0
/*----------------------------------------------------------------------------------------------------------------------
	Called when the END or ENDBLOCK command needs to be parsed from within the BASICCMDLINE block. Basically just
	checks to make sure the next token in the data file is a semicolon.
*/
void BASICCMDLINE::HandleEndblock(
  NxsToken & token)	/* is the token used to read from `in' */
	{
	// Get the semicolon following END or ENDBLOCK token
	token.GetNextToken();

	if (!token.Equals(";"))
		{
		errormsg = "Expecting ';' to terminate the END or ENDBLOCK command, but found ";
		errormsg += token.GetToken();
		errormsg += " instead";
		throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
		}
	}
예제 #15
0
/*----------------------------------------------------------------------------------------------------------------------
|	Advances the token, and returns the unsigned int that the token represents
|
| 	Sets errormsg and raises a NxsException on failure.
|	`contextString` is used in error messages:
|		"${contextString} must be a number greater than 0"
*/
unsigned NxsToken::DemandPositiveInt(NxsToken &token, NxsString & errormsg, const char *contextString)
	{
	token.GetNextToken();
	int i = atoi(token.GetToken().c_str());
	if (i <= 0)
		{
		errormsg.assign(contextString);
		errormsg += " must be a number greater than 0. Found";
		errormsg += token.GetToken();
		errormsg += " instead";
		throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
		}
	return (unsigned) i;
	}
예제 #16
0
/*----------------------------------------------------------------------------------------------------------------------
|	Stores the next token as the this->title field.
*/
void NxsBlock::HandleTitleCommand(NxsToken & token)
	{
	token.GetNextToken();
	if (token.Equals(";"))
		GenerateUnexpectedTokenNxsException(token, "a title for the block");
	if (!title.empty() && nexusReader)
		{
		errormsg = "Multiple TITLE commands were encountered the title \"";
		errormsg += title;
		errormsg += "\" will be replaced by \"";
		errormsg += token.GetToken() ;
		errormsg += '\"';
		nexusReader->NexusWarnToken(errormsg, NxsReader::OVERWRITING_CONTENT_WARNING, token);
		errormsg.clear();
		}
	title = token.GetToken();
	autoTitle = false;
	DemandEndSemicolon(token, "TITLE");
	}
예제 #17
0
void NxsTaxaBlock::HandleTaxLabels(NxsToken &token)
	{
	if (dimNTax == 0) 
		{
		errormsg = "NTAX must be specified before TAXLABELS command";
		throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
		}
	taxLabels.clear();
	labelToIndex.clear();
	for (unsigned i = 0; i < dimNTax; i++)
		{
		token.GetNextToken();
		try
			{
			NxsString t = token.GetToken();
			AddTaxonLabel(t);
			}
		catch (const NxsException & x)
			{
			throw NxsException(x.msg, token);
			}
		}
	DemandEndSemicolon(token, "TAXLABELS");
	}
예제 #18
0
void BlockParams::Read(NxsToken &token)
{
  DemandEndSemicolon(token, "PARAMS");
  nat idCtr = 0; 

  auto catsFound = std::unordered_set<Category>{}; 

  while(true)
    {
      token.GetNextToken();
      NxsBlock::NxsCommandResult res = HandleBasicBlockCommands(token); 

      if (res == NxsBlock::NxsCommandResult(STOP_PARSING_BLOCK))
	return;

      if (res != NxsBlock::NxsCommandResult(HANDLED_COMMAND))
	{	  
	  auto str = token.GetToken(false); 

	  auto cat = CategoryFuns::getCategoryFromLinkLabel(str); 	  
	  parseScheme(token, cat, idCtr); 

	  if(catsFound.find(cat) != catsFound.end())
	    {
	      cerr << "parsing error: found a linking scheme for category  " <<  CategoryFuns::getShortName(cat) << " twice. Aborting." ; 
	      exitFunction(-1, true); 
	    }

	  if( cat == Category::TOPOLOGY)
	    {
	      cerr <<  "not implemented"; 
	      assert(0); 
	    }	    
	}
    }
}
예제 #19
0
void NxsSetReader::ReadSetDefinition(
  NxsToken &token, 
  const NxsLabelToIndicesMapper & mapper, 
  const char * setType, /* "TAXON" or "CHARACTER" -- for error messages only */ 
  const char * cmdName, /* command name -- "TAXSET" or "EXSET"-- for error messages only */ 
  NxsUnsignedSet * destination, /** to be filled */
  const NxsUnsignedSet * taboo)
	{
	NxsString errormsg;
	NxsUnsignedSet tmpset;
	NxsUnsignedSet dummy;
	if (destination == NULL)
		destination = & dummy;
	unsigned previousInd = UINT_MAX;
	std::vector<unsigned> intersectVec;
	while (!token.Equals(";"))
		{
		if (taboo && token.Equals(","))
			return;
		if (token.Equals("-"))
			{
			if (previousInd == UINT_MAX)
				{
				errormsg = "The '-' must be preceded by number or a ";
				errormsg << setType << " label in the " << cmdName << " command.";
				throw NxsException(errormsg, token);
				}
			token.GetNextToken();
			if (token.Equals(";") || token.Equals("\\"))
				{
				errormsg = "Range in the ";
				errormsg << setType << " set definition in the " << cmdName << " command must be closed with a number or label.";
				throw NxsException(errormsg, token);
				}
			unsigned endpoint;
			if (token.Equals("."))
				endpoint = mapper.GetMaxIndex();
			else
				{
				tmpset.clear();
				unsigned nAdded = NxsSetReader::InterpretTokenAsIndices(token, mapper, setType, cmdName, &tmpset);
				if (nAdded != 1)
					{
					errormsg = "End of a range in a ";
					errormsg << setType << " set definition in the " << cmdName << " command must be closed with a single number or label (not a set).";
					throw NxsException(errormsg, token);
					}
				endpoint = *(tmpset.begin());
				if (endpoint < previousInd)
					{
					errormsg = "End of a range in a ";
					errormsg << setType << " set definition in the " << cmdName << " command must be a larger index than the start of the range (found ";
					errormsg << previousInd + 1 << " - " << token.GetToken();
					throw NxsException(errormsg, token);
					}
				}
			token.GetNextToken();
			if (token.Equals("\\"))
				{
				token.GetNextToken();
				NxsString t = token.GetToken(); 
				unsigned stride = 0;
				try
					{
					stride = t.ConvertToUnsigned();
					}
				catch (const NxsString::NxsX_NotANumber &)
					{}
				if (stride == 0)
					{
					errormsg = "Expecting a positive number indicating the 'stride' after the \\ in the ";
					errormsg << setType << " set definition in the " << cmdName << " command. Encountered ";
					errormsg << t;
					throw NxsException(errormsg, token);
					}
				AddRangeToSet(previousInd, endpoint, stride, destination, taboo, token);
				token.GetNextToken();
				}
			else
				AddRangeToSet(previousInd, endpoint, 1, destination, taboo, token);
			previousInd = UINT_MAX;
			}
		else 
			{
			tmpset.clear();
			const unsigned nAdded = NxsSetReader::InterpretTokenAsIndices(token, mapper, setType, cmdName, &tmpset);
			if (taboo != NULL)
				{
				set_intersection(taboo->begin(), taboo->end(), tmpset.begin(), tmpset.end(), back_inserter(intersectVec));
				if (!intersectVec.empty())
					{
					errormsg << "Illegal repitition of an index (" << 1 + *(intersectVec.begin()) << ") in multiple subsets.";
					throw NxsException(errormsg, token);
					}
				}
			if (nAdded == 1 )
				{
				previousInd = *(tmpset.begin());
				destination->insert(previousInd);
				}
			else
				{
				previousInd = UINT_MAX;
				destination->insert(tmpset.begin(), tmpset.end());
				}
			token.GetNextToken();
			}
		}
	}
예제 #20
0
/*----------------------------------------------------------------------------------------------------------------------
|	This function provides the ability to read everything following the block name (which is read by the NxsReader 
|	object) to the end or endblock statement. Characters are read from the input stream in. Overrides the abstract 
|	virtual function in the base class. 
*/
void NxsTaxaBlock::Read(
  NxsToken &token)	/* the token used to read from in */
	{
	ntax				= 0;
	unsigned nominal_ntax	= 0;
	isEmpty				= false;
	isUserSupplied		= true;

	DemandEndSemicolon(token, "BEGIN TAXA");

	for (;;)
		{
		token.GetNextToken();

		if (token.Equals("DIMENSIONS"))
			{
			// This should be the NTAX keyword
			//
			token.GetNextToken(); 

			if (!token.Equals("NTAX"))
				{
				errormsg = "Expecting NTAX keyword, but found ";
				errormsg += token.GetToken();
				errormsg += " instead";
				throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
				}

			DemandEquals(token, "after NTAX");
			nominal_ntax = DemandPositiveInt(token, "NTAX");
			DemandEndSemicolon(token, "DIMENSIONS");
			}	// if (token.Equals("DIMENSIONS"))

		else if (token.Equals("TAXLABELS")) 
			{
			if (nominal_ntax <= 0) 
				{
				errormsg = "NTAX must be specified before TAXLABELS command";
				throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
				}

			for (unsigned i = 0; i < nominal_ntax; i++)
				{
				token.GetNextToken();
				//@pol should check to make sure this is not punctuation
				AddTaxonLabel(token.GetToken());
				}
			DemandEndSemicolon(token, "TAXLABELS");
			}	// if (token.Equals("TAXLABELS")) 

		else if (token.Equals("END") || token.Equals("ENDBLOCK"))
			{
			DemandEndSemicolon(token, "ENDBLOCK");
			break;
			}	// if (token.Equals("END") || token.Equals("ENDBLOCK"))

		else
			{
			SkippingCommand(token.GetToken());
			do
				{
				token.GetNextToken();
				}
			while (!token.AtEOF() && !token.Equals(";"));

			if (token.AtEOF())
				{
				errormsg = "Unexpected end of file encountered";
				throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
				}
			}	// token not END, ENDBLOCK, TAXLABELS, or DIMENSIONS
		}	// GetNextToken loop
	}
예제 #21
0
/*----------------------------------------------------------------------------------------------------------------------
|	Called when the LOG command needs to be parsed from within the GarliReader block.
*/
void GarliReader::HandleLog(
  NxsToken &token)	/* the token used to read from `in' */
	{
	bool starting = false;
	bool stopping = false;
	bool appending = false;
	bool replacing = false;
	bool name_provided = false;
	NxsString logfname;

	// Retrieve all tokens for this command, stopping only in the event
	// of a semicolon or an unrecognized keyword
	//
	for (;;)
		{
		token.GetNextToken();

		if (token.Equals(";"))
			{
			break;
			}
		else if (token.Abbreviation("STOp"))
			{
			stopping = true;
			}
		else if (token.Abbreviation("STArt"))
			{
			starting = true;
			}
		else if (token.Abbreviation("Replace"))
			{
			replacing = true;
			}
		else if (token.Abbreviation("Append"))
			{
			appending = true;
			}
		else if (token.Abbreviation("File"))
			{
			logfname = GetFileName(token);
			name_provided = true;
			}
		else
			{
			errormsg = "Unexpected keyword (";
			errormsg += token.GetToken();
			errormsg += ") encountered reading LOG command";
			throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
			}
		}

	// Check for incompatible combinations of keywords
	//
	if (stopping && (starting || appending || replacing || name_provided))
		{
		errormsg = "Cannot specify STOP with any of the following START, APPEND, REPLACE, FILE";
		throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
		}

	if (appending && replacing)
		{
		errormsg = "Cannot specify APPEND and REPLACE at the same time";
		throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
		}

	if (logf_open && (starting || name_provided || appending || replacing))
		{
		errormsg = "Cannot start log file since log file is already open";
		throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
		}

	// Is user closing an open log file?
	//
	if (stopping)
		{
		logf.close();
		logf_open = false;

		message = "\nLog file closed";
		PrintMessage();

		return;
		}

	// If this far, must be attempting to open a log file
	//
	if (!name_provided)
		{
		errormsg = "Must provide a file name when opening a log file\n";
		errormsg += "e.g., log file=doofus.txt start replace;";
		throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
		}   

	if (appending)
		{
		logf_open = true;
		logf.open(logfname.c_str(), ios::out | ios::app);

		message = "\nAppending to log file ";
		message += logfname;
		PrintMessage();
		}

	else if (replacing)
		{
		logf_open = true;
		logf.open(logfname.c_str());

		message = "\nReplacing log file ";
		message += logfname;
		PrintMessage();
		}

	else 
		{
		bool exists = FileExists(logfname.c_str());
		bool userok = true;
		if (exists && !UserQuery("Ok to replace?", "Log file specified already exists", GarliReader::UserQueryEnum(GarliReader::uq_yes | GarliReader::uq_no)))
			userok = false;

		if (userok)
			{
			logf_open = true;
			logf.open(logfname.c_str());
			}

		if (exists && userok)
			{
			message = "\nReplacing log file ";
			message += logfname;
			}

		else if (userok)
			{
			message = "\nLog file ";
			message += logfname;
			message += " opened";
			}

		else
			{
			message = "\nLog command aborted";
			}

		PrintMessage();
		}
	}
예제 #22
0
/*----------------------------------------------------------------------------------------------------------------------
	Called when the HELP command needs to be parsed from within the BASICCMDLINE block.
*/
void BASICCMDLINE::HandleShow(
  NxsToken & token)	/* is the token used to read from `in' */
	{
	// Retrieve all tokens for this command, stopping only in the event
	// of a semicolon or an unrecognized keyword
	for (;;)
		{
		token.GetNextToken();

		if (token.Equals(";"))
			break;
		else
			{
			errormsg = "Unexpected keyword (";
			errormsg += token.GetToken();
			errormsg += ") encountered reading HELP command";
			throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
			}
		}

	bool taxaStored			= !taxa->IsEmpty();
	bool treesStored		= !trees->IsEmpty();
	bool assumptionsStored	= !assumptions->IsEmpty();
	bool distancesStored	= !distances->IsEmpty();
	bool charactersStored	= !characters->IsEmpty();
	bool dataStored			= !data->IsEmpty();
	bool unalignedStored	= !unaligned->IsEmpty();
	bool isAnythingStored = (taxaStored || treesStored || assumptionsStored || distancesStored || charactersStored || dataStored || unalignedStored);

	if (isAnythingStored)
		message = "\nNexus blocks currently stored:";
	else
		message = "\nNo Nexus blocks are currently stored.";
	PrintMessage();

	if (!taxa->IsEmpty())
		{
		cerr << "\n  TAXA block found" << endl;
		taxa->Report(cerr);
		if (logf_open)
			taxa->Report(logf);
		}

	if (!trees->IsEmpty())
		{
		cerr << "\n  TREES block found" << endl;
		trees->Report(cerr);
		if (logf_open)
			trees->Report(logf);
		}

	if (!assumptions->IsEmpty())
		{
		cerr << "\n  ASSUMPTIONS block found" << endl;
		assumptions->Report(cerr);
		if (logf_open)
			assumptions->Report(logf);
		}

	if (!distances->IsEmpty())
		{
		cerr << "\n  DISTANCES block found" << endl;
		distances->Report(cerr);
		if (logf_open)
			distances->Report(logf);
		}

	if (!characters->IsEmpty())
		{
		cerr << "\n  CHARACTERS block found" << endl;
		characters->Report(cerr);
		if (logf_open)
			characters->Report(logf);
		}

	if (!data->IsEmpty())
		{
		cerr << "\n  DATA block found" << endl;
		data->Report(cerr);
		if (logf_open)
			data->Report(logf);
		}

	if (!unaligned->IsEmpty())
		{
		cerr << "\n  UNALIGNED block found" << endl;
		unaligned->Report(cerr);
		if (logf_open)
			unaligned->Report(logf);
		}
	}
예제 #23
0
/*----------------------------------------------------------------------------------------------------------------------
	This function provides the ability to read everything following the block name (which is read by the NxsReader
	object) to the END or ENDBLOCK statement. Characters are read from the input stream `in'. Overrides the virtual
	function in the base class.
*/
void BASICCMDLINE::Read(
  NxsToken & token)	/* is the token used to read from `in' */
	{
	isEmpty = false;

	// This should be the semicolon after the block name
	token.GetNextToken();

	if (!token.Equals(";"))
		{
		errormsg = "Expecting ';' after ";
		errormsg += NCL_BLOCKTYPE_ATTR_NAME;
		errormsg += " block name, but found ";
		errormsg += token.GetToken();
		errormsg += " instead";
		throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
		}

	for (;;)
		{
		token.GetNextToken();

		if (token.Abbreviation("ENdblock"))
			{
			HandleEndblock(token);
			break;
			}
		else if (token.Abbreviation("Help"))
			{
			HandleHelp(token);
			}
		else if (token.Abbreviation("Log"))
			{
			HandleLog(token);
			}
		else if (token.Abbreviation("EXecute"))
			{
			HandleExecute(token);
			}
		else if (token.Abbreviation("Show"))
			{
			HandleShow(token);
			}
		else if (token.Abbreviation("Quit"))
			{
			quit_now = true;

			message = "\nBASICCMDLINE says goodbye\n";
			PrintMessage();

			break;
			}
		else
			{
			SkippingCommand(token.GetToken());
			do
				{
				token.GetNextToken();
				}
			while (!token.AtEOF() && !token.Equals(";"));

			if (token.AtEOF())
				{
				errormsg = "Unexpected end of file encountered";
				throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
				}
			}
		}
	}
예제 #24
0
/*----------------------------------------------------------------------------------------------------------------------
|	This function provides the ability to read everything following the block name (which is read by the NxsReader 
|	object) to the END or ENDBLOCK statement. Characters are read from the input stream `in'. Overrides the virtual 
|	function in the base class.
*/
void GarliBlock::Read(
  NxsToken &token)	/* the token used to read from `in' */
	{
	isEmpty = false;
	//if we already read a garli block with a model string, clear it
	modelString.clear();

	// This should be the semicolon after the block name
	//
	token.GetNextToken();

	if (!token.Equals(";"))
		{
		errormsg = "Expecting ';' after ";
		errormsg += id;
		errormsg += " block name, but found ";
		errormsg += token.GetToken();
		errormsg += " instead";
		throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
		}

	for (;;)
		{//only allowing three things to happen here 
		//1. endblock is reached, sucessfully exiting the garli block
		//2. something besides an endblock is read.  This is interpreted as part of the model string, with minimal error checking
		//3. eof is hit before an endblock
		token.GetNextToken();

		if (token.Abbreviation("ENdblock"))
			{
			HandleEndblock(token);
			break;
			}
		else if(token.AtEOF() == false){
			NxsString s = token.GetToken();
			if(s.size() > 1 && (s.IsADouble() == false && s.IsALong() == false)){
				errormsg = "Unexpected character(s) in Garli block.\n     See manual for model parameter format.";
				throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
				}
			if(token.IsPunctuationToken() == false){//toss semicolons and such
				modelString += token.GetToken();
				modelString += ' ';
				}
			}
		else
			{
			errormsg = "Unexpected end of file encountered before \"end;\" or\n     \"endblock;\" command in Garli block";
			throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
			}
		}
/*
		else if (token.Abbreviation("GarliReader"))
			{
			HandleGarliReader(token);
			}
		else if (token.Abbreviation("Help"))
			{
			HandleHelp(token);
			}
		else if (token.Abbreviation("Log"))
			{
			HandleLog(token);
			}
		else if (token.Abbreviation("EXecute"))
			{
			HandleExecute(token);
			}
		else if (token.Abbreviation("Show"))
			{
			HandleShow(token);
			}
		else if (token.Abbreviation("Quit"))
			{
			quit_now = true;

			message = "\nGarliReader says goodbye\n";
			PrintMessage();

			break;
			}
		else
			{
			SkippingCommand(token.GetToken());
			do
				{
				token.GetNextToken();
				}
			while (!token.AtEOF() && !token.Equals(";"));

			if (token.AtEOF())
				{
				errormsg = "Unexpected end of file encountered";
				throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
				}
			}
*/
	}
예제 #25
0
/*!
	Called when FORMAT command needs to be parsed from within the DIMENSIONS block. Deals with everything after the
	token FORMAT up to and including the semicolon that terminates the FORMAT command.
*/
void NxsUnalignedBlock::HandleFormat(
  NxsToken & token)	/* is the token used to read from `in' */
	{
	bool standardDataTypeAssumed = false;
	bool ignoreCaseAssumed = false;

	for (;;)
		{
		token.GetNextToken();

		if (token.Equals("DATATYPE"))
			{
			DemandEquals(token, "after keyword DATATYPE");
			// This should be one of the following: STANDARD, DNA, RNA, NUCLEOTIDE or PROTEIN
			token.GetNextToken();

			if (token.Equals("STANDARD"))
				datatype = NxsCharactersBlock::standard;
			else if (token.Equals("DNA"))
				datatype = NxsCharactersBlock::dna;
			else if (token.Equals("RNA"))
				datatype = NxsCharactersBlock::rna;
			else if (token.Equals("NUCLEOTIDE"))
				datatype = NxsCharactersBlock::nucleotide;
			else if (token.Equals("PROTEIN"))
				datatype = NxsCharactersBlock::protein;
			else
				{
				errormsg = token.GetToken();
				errormsg += " is not a valid DATATYPE within a ";
				errormsg += NCL_BLOCKTYPE_ATTR_NAME;
				errormsg += " block";
				throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
				}
			if (standardDataTypeAssumed && datatype != NxsCharactersBlock::standard)
				{
				errormsg = "DATATYPE must be specified first in FORMAT command";
				throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
				}
			originalDatatype = datatype;
			ResetSymbols();
			}
		else if (token.Equals("RESPECTCASE"))
			{
			if (ignoreCaseAssumed)
				{
				errormsg = "RESPECTCASE must be specified before MISSING and SYMBOLS in FORMAT command";
				throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
				}
			standardDataTypeAssumed = true;
			respectingCase = true;
			}
		else if (token.Equals("MISSING"))
			{
			DemandEquals(token, "after keyword MISSING");
			// This should be the missing data symbol (single character)
			token.GetNextToken();

			if (token.GetTokenLength() != 1)
				{
				errormsg = "MISSING symbol should be a single character, but ";
				errormsg += token.GetToken();
				errormsg += " was specified";
				throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
				}
			else if (token.IsPunctuationToken() && !token.IsPlusMinusToken())
				{
				errormsg = "MISSING symbol specified cannot be a punctuation token (";
				errormsg += token.GetToken();
				errormsg += " was specified)";
				throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
				}
			else if (token.IsWhitespaceToken())
				{
				errormsg = "MISSING symbol specified cannot be a whitespace character (";
				errormsg += token.GetToken();
				errormsg += " was specified)";
				throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
				}

			missing = token.GetToken()[0];

			ignoreCaseAssumed = true;
			standardDataTypeAssumed = true;
			}
		else if (token.Equals("SYMBOLS") || token.Equals("SYMBOL"))
			{
			NxsDiscreteStateCell numDefStates;
			unsigned maxNewStates;
			switch(datatype)
				{
				case NxsCharactersBlock::dna:
				case NxsCharactersBlock::rna:
				case NxsCharactersBlock::nucleotide:
					numDefStates = 4;
					maxNewStates = NCL_MAX_STATES-4;
					break;
				case NxsCharactersBlock::protein:
					numDefStates = 21;
					maxNewStates = NCL_MAX_STATES-21;
					break;
				default:
					numDefStates = 0; // replace symbols list for standard datatype
					symbols[0] = '\0';
					maxNewStates = NCL_MAX_STATES;
				}
			DemandEquals(token, "after keyword SYMBOLS");

			// This should be the symbols list
			token.SetLabileFlagBit(NxsToken::doubleQuotedToken);
			token.GetNextToken();

			token.StripWhitespace();
			unsigned numNewSymbols = token.GetTokenLength();

			if (numNewSymbols > maxNewStates)
				{
				errormsg = "SYMBOLS defines ";
				errormsg += numNewSymbols;
				errormsg += " new states but only ";
				errormsg += maxNewStates;
				errormsg += " new states allowed for this DATATYPE";
				throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
				}

			NxsString to = token.GetToken();
			unsigned tlen = (unsigned)to.size();
			NxsString processedS;
			// Check to make sure user has not used any symbols already in the
			// default symbols list for this data type
			for (unsigned i = 0; i < tlen; i++)
				{
				if (IsInSymbols(to[i]))
					{
					errormsg = "The character ";
					errormsg << to[i] << " defined in SYMBOLS is predefined for this DATATYPE and shoud not occur in a SYMBOLS subcommand of a FORMAT command.";
					if (nexusReader)
						{
						nexusReader->NexusWarnToken(errormsg, NxsReader::SKIPPING_CONTENT_WARNING, token);
						errormsg.clear();
						}
					}
				else
					processedS += to[i];
				}

			// If we've made it this far, go ahead and add the user-defined
			// symbols to the end of the list of predefined symbols
			symbols.append(processedS);

			ignoreCaseAssumed = true;
			standardDataTypeAssumed = true;
			}

		else if (token.Equals("EQUATE"))
			{
			DemandEquals(token, "after keyword EQUATE");

			// This should be a double-quote character
			token.GetNextToken();

			if (!token.Equals("\""))
				{
				errormsg = "Expecting '\"' after keyword EQUATE but found ";
				errormsg += token.GetToken();
				errormsg += " instead";
				throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
				}

			// Loop until second double-quote character is encountered
			for (;;)
				{
				token.GetNextToken();
				if (token.Equals("\""))
					break;

				// If token is not a double-quote character, then it must be the equate symbol (i.e., the
				// character to be replaced in the data matrix)
				if (token.GetTokenLength() != 1)
					{
					errormsg = "Expecting single-character EQUATE symbol but found ";
					errormsg += token.GetToken();
					errormsg += " instead";
					throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
					}

				// Check for bad choice of equate symbol
				NxsString t = token.GetToken();
				const char ch = t[0];
				bool badEquateSymbol = false;

				// The character '^' cannot be an equate symbol
				if (ch == '^')
					badEquateSymbol = true;

				// Equate symbols cannot be punctuation (except for + and -)
				if (token.IsPunctuationToken() && !token.IsPlusMinusToken())
					badEquateSymbol = true;

				// Equate symbols cannot be same as matchchar, missing, or gap
				if (ch == missing || ch == gap)
					badEquateSymbol = true;

				// Equate symbols cannot be one of the state symbols currently defined
				if (IsInSymbols(ch))
					badEquateSymbol = true;

				if (badEquateSymbol)
					{
					errormsg = "EQUATE symbol specified (";
					errormsg += token.GetToken();
					errormsg += ") is not valid; must not be same as missing, \nmatchchar, gap, state symbols, or any of the following: ()[]{}/\\,;:=*'\"`<>^";
					throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
					}

				NxsString k = token.GetToken();

				DemandEquals(token, "in EQUATE definition");

				// This should be the token to be substituted in for the equate symbol
				token.SetLabileFlagBit(NxsToken::parentheticalToken);
				token.SetLabileFlagBit(NxsToken::curlyBracketedToken);
				token.GetNextToken();
				NxsString v = token.GetToken();

				// Add the new equate association to the equates list
				equates[ch] = v;
				}

			standardDataTypeAssumed = true;
			}
		else if (token.Equals("LABELS"))
			{
			labels = true;
			standardDataTypeAssumed = true;
			}
		else if (token.Equals("NOLABELS"))
			{
			labels = false;
			standardDataTypeAssumed = true;
			}
		else if (token.Equals(";"))
			{
			break;
			}
		}
	ResetDatatypeMapper();
	}
예제 #26
0
void NxsTaxaAssociationBlock::HandleAssociatesCommand(
    NxsToken &token)
{
    if (this->firstTaxaBlock == 0L || this->secondTaxaBlock == 0L)
    {
        errormsg << "Expecting TAXA command to precede an ASSOCIATES command.";
        throw NxsException(errormsg, token);
    }
    token.GetNextToken();
    for (;; )
    {
        std::set<unsigned> fSet;
        while (!token.IsPunctuationToken() || !(token.Equals(";") || token.Equals(",") || token.Equals("/")))
        {
            try {
                this->firstTaxaBlock->GetIndicesForLabel(token.GetTokenReference(), &fSet);
            }
            catch(...)
            {
                errormsg << "Unrecognized taxon \"" << token.GetTokenReference() << "\" in ASSOCIATES command";
                throw NxsException(errormsg, token);
            }
            token.GetNextToken();
        }
        if (!token.Equals("/"))
        {
            errormsg << "Expecting / in ASSOCIATES command, found \"" << token.GetTokenReference() << "\"";
            throw NxsException(errormsg, token);
        }

        if (fSet.empty())
        {
            errormsg << "Expecting taxon labels from the first TAXA block before the / in ASSOCIATES command.";
            throw NxsException(errormsg, token);
        }
        token.GetNextToken();

        std::set<unsigned> sSet;

        while (!token.IsPunctuationToken() || !(token.Equals(";") || token.Equals(",") || token.Equals("/")))
        {
            try {
                this->secondTaxaBlock->GetIndicesForLabel(token.GetTokenReference(), &sSet);
            }
            catch(...)
            {
                errormsg << "Unrecognized taxon \"" << token.GetTokenReference() << "\" in ASSOCIATES command";
                throw NxsException(errormsg, token);
            }
            token.GetNextToken();
        }

        if (!(token.Equals(";") || token.Equals(",")))
        {
            errormsg << "Expecting , or ; in ASSOCIATES command, found \"" << token.GetTokenReference() << "\"";
            throw NxsException(errormsg, token);
        }

        if (sSet.empty())
        {
            errormsg << "Expecting taxon labels from the second TAXA block after the / in ASSOCIATES command.";
            throw NxsException(errormsg, token);
        }

        for (std::set<unsigned>::const_iterator fIt = fSet.begin(); fIt != fSet.end(); ++fIt)
        {
            this->AddAssociation(*fIt, sSet);
        }
        if (token.Equals(";"))
        {
            break;
        }
        token.GetNextToken();
    }
}
예제 #27
0
/*! used internally to  do most of the work of Execute() */
void NxsReader::CoreExecutionTasks(
    NxsToken  &token,           /* the token object used to grab NxsReader tokens */
    bool notifyStartStop)       /* if true, ExecuteStarting and ExecuteStopping will be called */
{
    unsigned numSigInts = NxsReader::getNumSignalIntsCaught();
    const bool checkingSignals = NxsReader::getNCLCatchesSignals();

    lastExecuteBlocksInOrder.clear();
    currBlock = NULL;

    NxsString errormsg;
    token.SetEOFAllowed(true);

    try
    {
        token.SetLabileFlagBit(NxsToken::saveCommandComments);
        token.GetNextToken();
    }
    catch (NxsException x)
    {
        NexusError(token.errormsg, 0, 0, 0);
        return;
    }

    if (token.Equals("#NEXUS"))
    {
        token.SetLabileFlagBit(NxsToken::saveCommandComments);
        token.GetNextToken();
    }
    else
    {
        errormsg = "Expecting #NEXUS to be the first token in the file, but found ";
        errormsg += token.GetToken();
        errormsg += " instead";
        /*mth changed this to a warning instead of an error	 because of the large number
            of files that violate this requirement.
         */
        NexusWarn(errormsg,  NxsReader::AMBIGUOUS_CONTENT_WARNING, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
    }

    if (notifyStartStop)
    {
        ExecuteStarting();
    }
    bool keepReading = true;
    for (; keepReading && !token.AtEOF(); )
    {
        if (checkingSignals && NxsReader::getNumSignalIntsCaught() != numSigInts)
        {
            throw NxsSignalCanceledParseException("Reading NEXUS content");
        }
        if (token.Equals("BEGIN"))
        {
            token.SetEOFAllowed(false); /*must exit the block before and EOF*/
            token.GetNextToken();
            token.SetBlockName(token.GetTokenReference().c_str());
            for (currBlock = blockList; currBlock != NULL; currBlock = currBlock->next)
            {
                if (currBlock->CanReadBlockType(token))
                {
                    break;
                }
            }
            NxsString currBlockName = token.GetToken();
            currBlockName.ToUpper();
            NxsBlockFactory * sourceOfBlock = NULL;
            if (currBlock == NULL)
            {
                try
                {
                    currBlock = CreateBlockFromFactories(currBlockName, token, &sourceOfBlock);
                }
                catch (NxsException x)
                {
                    NexusError(x.msg, x.pos, x.line, x.col);
                    token.SetBlockName(0L);
                    token.SetEOFAllowed(true);
                    return;
                }
            }
            if (currBlock == NULL)
            {
                SkippingBlock(currBlockName);
                if (!ReadUntilEndblock(token, currBlockName))
                {
                    token.SetBlockName(0L);
                    token.SetEOFAllowed(true);
                    return;
                }
            }
            else if (currBlock->IsEnabled())
            {
                keepReading = ExecuteBlock(token, currBlockName, currBlock, sourceOfBlock);
            }
            else
            {
                SkippingDisabledBlock(token.GetToken());
                if (sourceOfBlock)
                {
                    sourceOfBlock->BlockSkipped(currBlock);
                }
                if (!ReadUntilEndblock(token, currBlockName))
                {
                    token.SetBlockName(0L);
                    token.SetEOFAllowed(true);
                    return;
                }
            }
            currBlock = NULL;
            token.SetEOFAllowed(true);
            token.SetBlockName(0L);
        }       // if (token.Equals("BEGIN"))
        else if (token.Equals("&SHOWALL"))
        {
            for (NxsBlock*  showBlock = blockList; showBlock != NULL; showBlock = showBlock->next) {
                DebugReportBlock(*showBlock);
            }
        }
        else if (token.Equals("&LEAVE"))
        {
            break;
        }
        if (keepReading)
        {
            token.SetLabileFlagBit(NxsToken::saveCommandComments);
            token.GetNextToken();
        }
    }
    if (notifyStartStop)
    {
        ExecuteStopping();
    }

    currBlock = NULL;
}
예제 #28
0
void BlockParams::parseScheme(NxsToken& token, Category cat, nat &idCtr)
{
  auto numPart = tralnPtr->getNumberOfPartitions();
  auto partAppeared = std::vector<bool>(numPart, false); 

  token.GetNextToken();
  assert(token.GetToken().EqualsCaseInsensitive("=")); 
  token.GetNextToken();
  assert(token.GetToken().EqualsCaseInsensitive("(")); 

  auto scheme = std::vector<std::vector<nat>>{}; 
  while(not token.GetToken().EqualsCaseInsensitive(")") )
    {
      auto schemePart = std::vector<nat>{}; 
      bool startingNext = true; 
      
      // parse one partition part 
      while( not token.GetToken().EqualsCaseInsensitive(")") 	     
	     && (startingNext || not token.GetToken().EqualsCaseInsensitive(",")) )
	{
	  startingNext = false; 
	  // check if the separation item is an expasion item (-)
	  auto isLinkedRange =  token.GetToken().EqualsCaseInsensitive("-") ; 
	  auto isUnlinkedRange = token.GetToken().EqualsCaseInsensitive(":") ; 

	  token.GetNextToken();
	  nat part = token.GetToken().ConvertToInt();
	  nat start = ( isLinkedRange || isUnlinkedRange )  ? schemePart.back() +1  : part; 
	  nat end = part + 1 ;  

	  for(nat i = start ;  i < end ; ++i )
	    {
	      if(not (i < numPart))
		partitionError(i, numPart); 
	      if(partAppeared.at(i))
		{
		  tout << "error: partition " << i << " occurring twice in the same scheme. Check your parameter-block!" << std::endl; 
		  exitFunction(-1, true); 
		}
	      partAppeared.at(i) = true; 

	      if(isUnlinkedRange)
		{
		  scheme.push_back(schemePart);
		  schemePart = {i}; 
		}
	      else 
		schemePart.push_back(i); 
	    }

	  token.GetNextToken(); 
	}

      scheme.push_back(schemePart); 
    }

  // instantiate the parameters 
  for(auto schemePart : scheme )
    {
      assert(schemePart.size()  > 0 ); 
      parameters.push_back(CategoryFuns::getParameterFromCategory(cat,idCtr,getNumSeen(cat), schemePart, tralnPtr->getNumberOfTaxa()));
      ++idCtr; 
    }
}
예제 #29
0
/*!
	Called when MATRIX command needs to be parsed from within the UNALIGNED block. Deals with everything after the
	token MATRIX up to and including the semicolon that terminates the MATRIX command.
*/
void NxsUnalignedBlock::HandleMatrix(
  NxsToken & token)	/* is the token used to read from `in' */
	{
	if (taxa == NULL)
		{
		AssureTaxaBlock(false, token, "Matrix");
		unsigned ntax = taxa->GetNTax();
		if (ntax == 0)
			{
			errormsg = "Must precede ";
			errormsg += NCL_BLOCKTYPE_ATTR_NAME;
			errormsg += " block with a TAXA block or specify NEWTAXA and NTAX in the DIMENSIONS command";
			throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
			}
		}
	const unsigned ntax = taxa->GetNTax();
	uMatrix.clear();
	uMatrix.resize(ntax);
	unsigned indOfTaxInMemory = 0;
	std::vector<unsigned> toInMem(nTaxWithData, UINT_MAX);
	const unsigned ntlabels = taxa->GetNumTaxonLabels();
	errormsg.clear();
	bool taxaBlockNeedsLabels = (ntlabels == 0);
	if (!taxaBlockNeedsLabels && ntlabels < nTaxWithData)
		{
		errormsg << "Not enough taxlabels are known to read characters for " << nTaxWithData << " taxa in the Matrix command.";
		throw NxsException(errormsg, token);
		}
	for (unsigned indOfTaxInCommand = 0; indOfTaxInCommand < nTaxWithData; indOfTaxInCommand++)
		{
		NxsString nameStr;
		if (labels)
			{
			token.GetNextToken();
			nameStr = token.GetToken();
			if (taxaBlockNeedsLabels)
				{
				if (taxa->IsAlreadyDefined(nameStr))
					{
					errormsg << "Data for this taxon (" << nameStr << ") has already been saved";
					throw NxsException(errormsg, token);
					}
				try {
					indOfTaxInMemory = taxa->AddTaxonLabel(nameStr);
					}
				catch (NxsException &x)
					{
					if (nameStr == ";")
						{
						errormsg << "Unexpected ; after only " << indOfTaxInCommand << " taxa were read (expecting characters for " << nTaxWithData << " taxa).";
						throw NxsException(errormsg, token);
						}
					x.addPositionInfo(token);
					throw x;
					}
				}
			else
				{
				unsigned numOfTaxInMemory = taxa->TaxLabelToNumber(nameStr);
				if (numOfTaxInMemory == 0)
					{
					if (token.Equals(";"))
						errormsg << "Unexpected ;";
					else
						errormsg << "Could not find taxon named " << nameStr << " among stored taxon labels";
					throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
					}
				indOfTaxInMemory = numOfTaxInMemory - 1;
				}
			}
		else
			{
			indOfTaxInMemory = indOfTaxInCommand;
			nameStr << 1+indOfTaxInMemory;
			}
		if (toInMem[indOfTaxInCommand] != UINT_MAX)
			{
			errormsg << "Characters for taxon " << indOfTaxInCommand << " (" << taxa->GetTaxonLabel(indOfTaxInMemory) << ") have already been stored";
			throw NxsException(errormsg, token);
			}
		toInMem[indOfTaxInCommand] = indOfTaxInMemory;
		NxsDiscreteStateRow * new_row = &uMatrix[indOfTaxInMemory];
		unsigned charInd = 0;
		while (HandleNextState(token, indOfTaxInMemory, charInd, *new_row, nameStr))
			charInd++;
		}
	}
예제 #30
0
/*----------------------------------------------------------------------------------------------------------------------
|	Handles everything after the EXECUTE keyword and the terminating semicolon. Purges all blocks before executing 
|	file specified, and no warning is given of this.
| DJZ THIS IS NOT THE VERSION OF HandleExecute USED.  See the other overloaded version below.
*/
void GarliReader::HandleExecute(
  NxsToken &token)	/* the token used to read from `in' */
	{
	// Issuing the EXECUTE command from within a file is a no-no (at least in this program)
	//
	if (inf_open)
		{
		errormsg = "Cannot issue execute command from within a GarliReader block";
		throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
		}

	// Get the file name to execute (note: if filename contains underscores, these will be
	// automatically converted to spaces; user should surround such filenames with single quotes)
	//
	token.GetNextToken();

	NxsString fn = token.GetToken();

	// Get the semicolon terminating the EXECUTE command
	//
	token.GetNextToken();

	if (!token.Equals(";"))
		{
		errormsg = "Expecting ';' to terminate the EXECUTE command, but found ";
		errormsg += token.GetToken();
		errormsg += " instead";
		throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
		}

	if (FileExists(fn.c_str()))
		{
		cerr << endl;
		cerr << "Opening " << fn << "..." << endl;

		ifstream inf(fn.c_str(), ios::binary | ios::in);

		inf_open = true;

		MyNexusToken ftoken(inf);

		try
			{
			Execute(ftoken);
			}
		catch(NxsException x)
			{
			NexusError(errormsg, x.pos, x.line, x.col);
			}

		if (inf_open)
			inf.close();
		inf_open = false;

		// Users are allowed to put DATA blocks in their NEXUS files, but internally the data is always
		// stored in a NxsCharacterBlock object.
		//
		if (characters->IsEmpty() && !data->IsEmpty())
			{
			data->TransferTo(*characters);
			}

		}	// if (FileExists(fn.c_str()))

	else
		{
		cerr << endl;
		cerr << "Oops! Could not find specified file: " << fn << endl;
		}
	}