Exemplo n.º 1
0
/*----------------------------------------------------------------------------------------------------------------------
	Begins with the command just entered by the user, which is stored in the data member `next_command', adds a
	semicolon (if the user failed to supply one), and then adds the string "end;" so the whole bundle looks like a
	very short BASICCMDLINE block. This is then passed to HandleNextCommand, which processes it just like a real
	BASICCMDLINE block in a NEXUS data file.
*/
void BASICCMDLINE::PreprocessNextCommand()
	{
	// If user failed to add the terminating semicolon, we'll do it now. We will also remove the line feed
	// at the end and add the command "end;" to the end of the line (see explanation below).
	unsigned len = (unsigned)strlen(next_command);
	NCL_ASSERT(len > 0);

	// Remove any whitespace characters from end of string entered by user
	//
	unsigned i = len;
	while (i > 0 && next_command[i-1] == ' ' || next_command[i-1] == '\t' || next_command[i-1] == '\n')
		i--;

	// If character at position i - 1 is a semicolon, put '\0' terminator at position i;
	// otherwise, put a semicolon at position i and terminator at i + 1
	if (next_command[i-1] != ';')
		{
		next_command[i] = ';';
		i++;
		}
	NCL_ASSERT(i <= COMMAND_MAXLEN);
	next_command[i] = '\0';

	// Now add a semicolon at the beginning and terminate with an "END;" command
	// so that we can pretend this is simply a very short private NEXUS block
	// containing only one command.  This allows us to simply use the Read
	// function we inherited from the base class BstBase to process the command.
	len = (unsigned)strlen(next_command);
	NCL_ASSERT(len < COMMAND_MAXLEN-2);
	NxsString tmp = ";";
	tmp += next_command;
	tmp += "end;";
	strcpy(next_command, tmp.c_str());
	}
Exemplo n.º 2
0
bool constructSafeLabels(const NxsTaxaBlock & tb, std::vector<std::string> * vs, std::set<std::string> & safeLabelSet)
{
    if (vs == 0L)
        return false;
    const unsigned numTaxa = tb.GetNTaxTotal();
    bool changed = false;
    for (unsigned i = 0; i < numTaxa; ++i)
    {
        NxsString oldName = tb.GetTaxonLabel(i);
        unsigned oldOffset = 0;
        unsigned newOffset = 0;
        std::string prefix;
        for (; newOffset < 10 && oldOffset < oldName.length(); ++oldOffset)
        {
            char c = oldName[oldOffset];
            if ((isgraph(c)) && (strchr("!@#$%^&*.?|()[]{}/\\,;:=*\'\"`-+<>", c) == NULL))
            {
                if (newOffset == 0 && isdigit(c))
                {
                    prefix.append(1, 't');
                    newOffset += 1;
                }
                prefix.append(1, toupper(c));
                newOffset += 1;
            }
        }
        std::string newLabel = assignUniqueName(prefix, 10, safeLabelSet);
        safeLabelSet.insert(newLabel);
        vs->push_back(newLabel);
        if (newLabel != oldName)
            changed = true;

    }
    return changed;
}
Exemplo n.º 3
0
/*----------------------------------------------------------------------------------------------------------------------
|	Overrides the NxsToken::OutputComment virtual function (which does nothing) to display output comments [!comments
|	like this one beginning with an exclamation point]. The output comment is passed through the OutputManager
*/
void MyNexusToken::OutputComment(
  const NxsString &msg)	/* the output comment to be displayed */
	{
	unsigned pos;
	string s;
	//changing this again - just eating the Garli output comments
	s = "GarliScore";
	pos = msg.find(s);
	if(pos != string::npos){
		//outman.UserMessage("This is apparently a tree inferred by Garli in a previous run.  Its score was %s", msg.substr(s.length()).c_str());
		return;
		}
	s = "GarliModel";
	pos = msg.find(s);
	if(pos != string::npos){
		//outman.UserMessage("Garli's model parameter values used in inferring this tree:\n\t%s", msg.substr(s.length()).c_str());
		return;
		}
	
	s =	"****NOTE";//this is a note about the parameter values either being from a run that was terimated early or that 
					//they are only optimal for a certain tree. This is mainly for output when reading the trees in PAUP
					//and we will just ignore them here
	pos = msg.find(s);
	if(pos != string::npos) return;
	
	outman.UserMessage("\nCOMMENT FOUND IN NEXUS FILE (output verbatim):");
	outman.UserMessage(msg);
	outman.UserMessage("(END OF NEXUS COMMENT)");
	}
Exemplo n.º 4
0
void NxsReader::BlockReadHook(const NxsString &currBlockName, NxsBlock *currentBlock, NxsToken * token)
	{
	VecBlockPtr implied = currentBlock->GetImpliedBlocks();
	for (VecBlockPtr::iterator impIt = implied.begin(); impIt != implied.end(); ++impIt)
		{
		NxsBlock * nb = *impIt;
		NCL_ASSERT(nb);
		NxsString impID = nb->GetID();
		bool storeBlock = true;
		if (destroyRepeatedTaxaBlocks && impID.EqualsCaseInsensitive("TAXA"))
			{
			NxsTaxaBlockAPI * oldTB = this->GetOriginalTaxaBlock((NxsTaxaBlockAPI *) nb);
			if (oldTB)
				{
				storeBlock = ! currentBlock->SwapEquivalentTaxaBlock(oldTB);
				const std::string altTitle = nb->GetTitle();
				this->RegisterAltTitle(oldTB, altTitle);
				if (!storeBlock)
					{
					delete nb;
					}
				
				}
			}
		if (storeBlock) 
			{
			std::cerr << "storing implied block: " << impID << std::endl;
			this->AddBlockToUsedBlockList(impID, nb, token);
			}
		}
	std::cerr << "storing read block: " << currentBlock->GetID() << std::endl;
	this->AddBlockToUsedBlockList(currBlockName, currentBlock, token);
	}
Exemplo n.º 5
0
void Individual::GetStartingTreeFromNCL(NxsTreesBlock *treesblock, int rank, int nTax, bool restart /*=false*/){
	assert(treeStruct == NULL);

	int totalTrees = treesblock->GetNumTrees();

	int effectiveRank = rank % totalTrees;
	
	//we will get the tree string from NCL with names rather than numbers, regardless of how it was initially read in 
	NxsString treestr = treesblock->GetTranslatedTreeDescription(effectiveRank);
	treestr.BlanksToUnderscores();
	
	treeStruct=new Tree(treestr.c_str(), false, true);
	//treeStruct=new Tree(treesblock->GetTreeDescription(effectiveRank).c_str(), false);

	//check that any defined constraints are present in the starting tree
	int conNum=1;
	for(vector<Constraint>::iterator conit=treeStruct->constraints.begin();conit!=treeStruct->constraints.end();conit++){
		TreeNode *check = NULL;
		if((*conit).IsBackbone())
			check = treeStruct->ContainsMaskedBipartitionOrComplement(*(*conit).GetBipartition(), *(*conit).GetBackboneMask());
		else
			check = treeStruct->ContainsBipartitionOrComplement(*(*conit).GetBipartition());
		if(((*conit).IsPositive() && check == NULL) || ((*conit).IsPositive() == false  && check != NULL))
			throw ErrorException("Starting tree not compatible with constraint number %d!!!", conNum);
		}
	treeStruct->AssignCLAsFromMaster();

	for(int m=0;m < modPart.NumModels();m++){
		modPart.GetModel(m)->UpdateQMat();
		}
	}
Exemplo n.º 6
0
void NxsReader::NewBlockTitleCheckHook(const std::string &blockname, NxsBlock *p, NxsToken *token)
	{
	NxsBlockTitleHistoryMap::iterator mIt = blockTitleHistoryMap.find(blockname);
	if (mIt == blockTitleHistoryMap.end())
		{
		std::list<std::string> mt;
		blockTitleHistoryMap[blockname] = NxsBlockTitleHistory(1, mt);
		mIt = blockTitleHistoryMap.find(blockname);
		NCL_ASSERT(mIt != blockTitleHistoryMap.end());
		}
	NxsBlockTitleHistory & titleHist = mIt->second;
	unsigned n = titleHist.first;
	std::list<std::string> & previousTitles = titleHist.second;
	std::list<std::string>::iterator lsIt;
	std::string pTitle = p->GetTitle();
	std::string origTitle = pTitle;
	NxsString::to_upper(pTitle);
	if (pTitle.empty())
		{
		while (pTitle.empty())
			{
			NxsString autoName = "Untitled ";
			autoName += p->GetID().c_str();
			autoName += " Block ";
			autoName += n++;
			pTitle.assign(autoName.c_str());
			NxsString::to_upper(pTitle);
            lsIt = find(previousTitles.begin(), previousTitles.end(), pTitle);
			if (lsIt == previousTitles.end())
				{
				p->SetTitle(autoName, true);
				titleHist.first = n;
				}
			else
				pTitle.clear();
			}
		}
	else
		{
        lsIt = find(previousTitles.begin(), previousTitles.end(), pTitle);
		if (lsIt != previousTitles.end())
			{
			NxsString msg = "Block titles cannot be repeated. The TITLE ";
			msg += origTitle;
			msg += " has already been used for a ";
			msg += blockname;
			msg += " block.";
			if (token)
				throw NxsException(msg, *token);
			else
				throw NxsException(msg, 0, -1, -1);
			}
		}
	previousTitles.push_back(pTitle);
	}
Exemplo n.º 7
0
std::vector<std::string> NxsTaxaBlockAPI::GetAllLabels() const
	{
	const unsigned n = GetNTaxTotal();
	std::vector<std::string> v(n);
	for (unsigned i = 0; i < n; ++i)
		{
		NxsString nextLabel = GetTaxonLabel(i);  /*v2.1to2.2 4 */
		v[i] = std::string(nextLabel.c_str());
		}
	return v;
	}
Exemplo n.º 8
0
/*!
	Convenience function.
 	Raises an aprropriate NxsException (by appending  `contextString` to the phrase Unexpected ; "), if incrementing
		`tokIt` makes it equal to `endIt`
*/
void ProcessedNxsToken::IncrementNotLast(std::vector<ProcessedNxsToken>::const_iterator & tokIt, const std::vector<ProcessedNxsToken>::const_iterator &endIt, const char * contextString)
	{
	++tokIt;
	if (tokIt == endIt)
		{
		NxsString errormsg = "Unexpected ; ";
		if (contextString)
			errormsg.append(contextString);
		--tokIt;
		throw NxsException(errormsg, *tokIt);
		}
	}
Exemplo n.º 9
0
int GarliReader::HandleExecute(const char *filename)	/* the token used to read from `in' */
{
    // 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)
    //

    NxsString fn = filename;
    int ret = 0;

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

        PurgeBlocks();

        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);
            ret = 1;//error
        }

        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;
        ret = 1;
    }
    return ret;
}
Exemplo n.º 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.
			}
		}
	}
Exemplo n.º 11
0
int GarliReader::HandleExecute(const char *filename, bool )	
	{
	// The filename to execute is passed in
	//

	NxsString fn = filename;
	int ret = 0;

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

		inf_open = true;

		MyNexusToken ftoken(inf);

		try{
			Execute(ftoken);
			}
		catch(NxsException x){
			//DJZ 3/24/08 this was a bug that I inherited from the NCL example BasicCmdLine
			//the actual error message in x.msg was never getting printed because the empty
			//errormsg member of NexusBlock was being passed instead of the error stored in the
			//NxsException
			//NexusError(errormsg, x.pos, x.line, x.col);
			NexusError(x.msg, x.pos, x.line, x.col);
			ret = 1;//error
			}

		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
		{
		outman.UserMessage("Sorry, could not find specified file: %s", fn.c_str());
		ret = 1;
		}
	return ret;
	}
Exemplo n.º 12
0
void DataMatrix::BeginNexusTreesBlock(ofstream &treeout) const{
	//this outputs everything up through the translate table
	treeout << "#NEXUS\n\nbegin trees;\ntranslate\n";
	for(int k=0;k<nTax;k++){
		treeout << "  " << (k+1);
		NxsString tnstr = TaxonLabel(k);
		tnstr.BlanksToUnderscores();
		treeout << "  " << tnstr.c_str();
		if( k == nTax-1 )
			treeout << ";\n";
		else
			treeout << ",\n";
		}
	}
Exemplo n.º 13
0
std::string getLegalRelaxedPhylipTaxonName(const std::string & origName, const std::set<std::string> & used)
{
    NxsString numericExtension;
    std::string toReturn;
    const std::string cleanedName(purgeIllegalCharactersFromRelaxedPhylipName(origName));

    for (unsigned i = 1;; ++i)
    {
        if (formLegalRelaxedPhylipName(cleanedName, numericExtension, used, toReturn))
            return toReturn;
        numericExtension.clear();
        numericExtension << i;
    }
}
Exemplo n.º 14
0
void processNexusBlock(ostream & out, NxsBlock *nb)
	{
	NxsString identifier = nb->GetID();
	if (NxsString::case_insensitive_equals(identifier.c_str(), "DATA")
		|| NxsString::case_insensitive_equals(identifier.c_str(), "CHARACTERS"))
		{
		NxsCharactersBlock * ncb = static_cast<NxsCharactersBlock *>(nb);
		WriteCharactersBlock(out, ncb);
		}
	else if (NxsString::case_insensitive_equals(identifier.c_str(), "SETS")
		|| NxsString::case_insensitive_equals(identifier.c_str(), "ASSUMPTIONS"))
		{}
	else
		nb->WriteAsNexus(out);
	}
Exemplo n.º 15
0
bool formLegalRelaxedPhylipName(const std::string & origName, const NxsString & numericExtension, const std::set<std::string> & used, std::string & toReturn)
{
    toReturn = origName;
    toReturn.append(numericExtension.c_str());
    const std::string cap = NxsString::get_upper(toReturn);
    return (used.find(cap) == used.end());
}
Exemplo n.º 16
0
/*!
	Returns true if token NxsString begins with the NxsString `s'. This function should be used instead of the Equals
	function if you wish to allow for abbreviations of commands.
*/
bool NxsToken::Begins(
  NxsString s,			/* the comparison string */
  bool respect_case)	/* determines whether comparison is case sensitive */
	{
	unsigned k;
	char tokenChar, otherChar;

	unsigned slen = (unsigned)s.size();
	if (slen > token.size())
		return false;

	for (k = 0; k < slen; k++)
		{
		if (respect_case)
			{
			tokenChar = token[k];
			otherChar = s[k];
			}
		else
			{
			tokenChar = (char)toupper( token[k]);
			otherChar = (char)toupper( s[k]);
			}

		if (tokenChar != otherChar)
			return false;
		}

	return true;
	}
Exemplo n.º 17
0
/*----------------------------------------------------------------------------------------------------------------------
|	Returns true if token NxsString exactly equals `s'. If abbreviations are to be allowed, either Begins or 
|	Abbreviation should be used instead of Equals.
*/
bool NxsToken::Equals(
  NxsString s,			/* the string for comparison to the string currently stored in this token */
  bool respect_case)	/* if true, comparison will be case-sensitive */
	{
	unsigned k;
	char tokenChar, otherChar;

	unsigned slen = (unsigned)s.size();
	if (slen != token.size())
		return false;

	for (k = 0; k < token.size(); k++)
		{
		if (respect_case)
			{
			tokenChar = token[k];
			otherChar = s[k];
			}
		else
			{
			tokenChar = (char)toupper( token[k]);
			otherChar = (char)toupper( s[k]);
			}
		if (tokenChar != otherChar)
			return false;
		}

	return true;
	}
Exemplo n.º 18
0
void NxsTaxaBlock::ChangeTaxonLabel(
  unsigned i,	/* the taxon label number to change */
  NxsString s)	/* the string used to replace label i */ /*v2.1to2.2 4 */
	{
	if (i >= (unsigned)taxLabels.size())
		{
		NxsString e = "The label for taxon ";
		e << (i+1) << " cannot be changed, because the only " << (unsigned)taxLabels.size() << " taxlabel(s) have been assigned.";
		throw NxsNCLAPIException(e);
		}
	RemoveTaxonLabel(i);
	std::string x(s.c_str());
	NxsString::to_upper(x);
	CheckCapitalizedTaxonLabel(x);
	taxLabels[i] = NxsString(s.c_str()); /* odd construct for v2.1->v2.2 translation */
	labelToIndex[x] = i;
	}
Exemplo n.º 19
0
void writeCoreAssumptions(ostream &out, NxsCharactersBlock * cb, const char * newTitle)
{
	std::vector<int>			intWts;
	std::vector<double>			dblWts;
	NxsUnsignedSet activeExSet = cb->GetExcludedIndexSet();

	const NxsTransformationManager &tm = cb->GetNxsTransformationManagerRef();
	intWts = tm.GetDefaultIntWeights();
	if (intWts.empty())
		dblWts = tm.GetDefaultDoubleWeights();

	if (!(activeExSet.empty() && intWts.empty() && dblWts.empty()))
		{
		out << "BEGIN ASSUMPTIONS; \n    LINK CHARACTERS = ";
		out << NxsString::GetEscaped(newTitle) << " ;\n";
		if (!activeExSet.empty())
			{
			NxsString exsetName;
			exsetName << newTitle;
			exsetName.append("ExSet");
			NxsUnsignedSetMap m;
			m[exsetName] = activeExSet;
			NxsWriteSetCommand("EXSET", m, out, exsetName.c_str());;
			}
		if (!(intWts.empty() && dblWts.empty()))
			{
			NxsTransformationManager &cbntm = cb->GetNxsTransformationManagerRef();
			const std::string &wtSetName =  cbntm.GetDefaultWeightSetName();
			NxsTransformationManager ntm;
			if (!intWts.empty())
				{
				NxsTransformationManager::ListOfIntWeights iw;
				vecToListOfIntWeights(intWts, iw);
				ntm.AddIntWeightSet(wtSetName, iw, true);
				}
			else
				{
				NxsTransformationManager::ListOfDblWeights dw;
				vecToListOfDblWeights(dblWts, dw);
				ntm.AddRealWeightSet(wtSetName, dw, true);
				}
			ntm.WriteWtSet(out);
			}
		out << "END;\n";
		}
}
Exemplo n.º 20
0
void Individual::ReadTreeFromFile(istream & inf)
{	char tmp[256];
	char ch = ' ';
	NxsString s;

	while( inf )
	{
		inf.get( tmp, 255, '\n' );
		inf.get(ch);
		tmp[255] = '\0';
		s += tmp;
		if( ch == '\n' ) 
			break;
		else
			s += ch;
	}
	treeStruct=new Tree(s.c_str(), true);
	}
Exemplo n.º 21
0
/*----------------------------------------------------------------------------------------------------------------------
|	Shortens stored string to `n' - 3 characters, making the last three characters "...". If string is already less than 
|	`n' characters in length, this function has no effect. This is useful when it is desirable to show some of the
|	contents of a string, even when the string will not fit in its entirety into the space available for displaying it.
|	Assumes that `n' is at least 4.
*/
NxsString &NxsString::ShortenTo(
  unsigned n)	/* maximum number of characters available for displaying the string */
	{
	NCL_ASSERT(n > 3);
	if (length() <= static_cast<unsigned>(n))
		return *this;
	
	NxsString s;
	for (NxsString::iterator sIt = begin(); sIt != end(); sIt++)
		{
		s += (*sIt);
		if (s.length() >= n - 3)
			break;
		}
	s += "...";

	*this = s;
	return *this;
	}
Exemplo n.º 22
0
bool formLegalPhylipName(const std::string & origName, const NxsString & numericExtension, const std::set<std::string> & used, std::string & toReturn)
{
    const unsigned MAX_PHYLIP_NAME_LENGTH = 10;
    unsigned postLen = numericExtension.length();
    if (postLen > MAX_PHYLIP_NAME_LENGTH)
        throw NxsException("Number of duplicate names exceed the capacity of our poorly thought out mechanism for avoiding name clashes");
    const unsigned unPaddedLen = postLen + origName.length();
    if (unPaddedLen <= MAX_PHYLIP_NAME_LENGTH)
        toReturn = origName;
    else if (postLen == MAX_PHYLIP_NAME_LENGTH)
        toReturn.clear();
    else
        toReturn.assign(origName.c_str(), MAX_PHYLIP_NAME_LENGTH - postLen);
    toReturn.append(numericExtension.c_str());
    if (unPaddedLen < MAX_PHYLIP_NAME_LENGTH)
        toReturn.append(MAX_PHYLIP_NAME_LENGTH - unPaddedLen, ' ');
    const std::string cap = NxsString::get_upper(toReturn);
    return (used.find(cap) == used.end());
}
Exemplo n.º 23
0
/*--------------------------------------------------------------------------------------------------------------------------
|	Returns a vector of NxsString objects that match the entire `testStr'.
*/
NxsStringVector GetVecOfPossibleAbbrevMatches(
  const NxsString		&testStr,		/* string to match */
  const NxsStringVector	&possMatches)	/* vector of possible matches */
	{
	NxsStringVector matches;
	for (unsigned i = 0; i < possMatches.size(); i++)
		{
		if (testStr.Abbreviates(possMatches[i]))
			matches.push_back(possMatches[i]);
		}
	return matches;
	}
Exemplo n.º 24
0
/*!
	Returns true if token begins with the capitalized portion of `s' and, if token is longer than `s', the remaining
	characters match those in the lower-case portion of `s'. The comparison is case insensitive. This function should be
	used instead of the Begins function if you wish to allow for abbreviations of commands and also want to ensure that
	user does not type in a word that does not correspond to any command.
*/
bool NxsToken::Abbreviation(
  NxsString s)	/* the comparison string */
	{
	int k;
	int slen = (int)s.size();
	int tlen = (int)token.size();
	char tokenChar, otherChar;

	// The variable mlen refers to the "mandatory" portion
	// that is the upper-case portion of s
	//
	int mlen;
	for (mlen = 0; mlen < slen; mlen++)
		{
		if (!isupper(s[mlen]))
			break;
		}

	// User must have typed at least mlen characters in
	// for there to even be a chance at a match
	//
	if (tlen < mlen)
		return false;

	// If user typed in more characters than are contained in s,
	// then there must be a mismatch
	//
	if (tlen > slen)
		return false;

	// Check the mandatory portion for mismatches
	//
	for (k = 0; k < mlen; k++)
		{
		tokenChar = (char)toupper( token[k]);
		otherChar = s[k];
		if (tokenChar != otherChar)
			return false;
		}

	// Check the auxiliary portion for mismatches (if necessary)
	//
	for (k = mlen; k < tlen; k++)
		{
		tokenChar = (char)toupper( token[k]);
		otherChar = (char)toupper( s[k]);
		if (tokenChar != otherChar)
			return false;
		}

	return true;
	}
Exemplo n.º 25
0
/*----------------------------------------------------------------------------------------------------------------------
|	Changes the label for taxon 'i' to 's'.
*/
void NxsTaxaBlock::ChangeTaxonLabel(
  unsigned i,	/* the taxon label number to change */
  NxsString s)	/* the string used to replace label i */
	{
	assert(i < (unsigned)taxonLabels.size());

	if (s.QuotesNeeded())
		needsQuotes[i] = true;
	else
		needsQuotes[i] = false;

	taxonLabels[i] = s;
	}
Exemplo n.º 26
0
/*----------------------------------------------------------------------------------------------------------------------
|	Adds taxon label 's' to end of list of taxon labels and increments ntax by 1. Returns index of taxon label just 
|	added.
*/
unsigned NxsTaxaBlock::AddTaxonLabel(
  NxsString s)	/* the taxon label to add */
	{
	isEmpty = false;
	if (s.QuotesNeeded())
		needsQuotes.push_back(true);
	else
		needsQuotes.push_back(false);
	
	taxonLabels.push_back(s);
	ntax++;
	return (ntax-1);
	}
Exemplo n.º 27
0
/*--------------------------------------------------------------------------------------------------------------------------
|	Written to make it easy to initialize a vector of strings. Similar to the perl split function. Converts a string like
|	this -- "A|bro|ken strin|g" -- to a vector of strings with four elements:  "A", "bro", "ken string", and "g".
*/
NxsStringVector BreakPipeSeparatedList(
  const NxsString &strList)	/* the string submitted for splitting */
  	{
	NxsString::const_iterator p = strList.begin();
	NxsString ss;
	NxsStringVector retVec;
	for (;;)
		{
		bool done = (p == strList.end());
		if (done || (*p == '|')) 
			{
			retVec.push_back(ss);
			ss.clear();
			if (done)
				break;
			p++;
			}
		ss += *p;
		p++;
		}
	return retVec;
	}
Exemplo n.º 28
0
/*----------------------------------------------------------------------------------------------------------------------
|	Right-justifies `x' in a field `w' characters wide with precision `p', using blank spaces to fill in unused 
|	portions on the left-hand side of the field. Specify true for `clear_first' to first empty the string. Assumes that
|	the specified width is enough to accommodate the string representation of `x'.
*/
NxsString &NxsString::RightJustifyDbl(
  double x,				/* double value to right justify */
  unsigned w,			/* width of field */
  unsigned p,			/* precision to use when displaying `x' */
  bool clear_first)		/* if true, initialize stored string first to the empty string */
	{
	if (clear_first)
		erase();

	char fmtstr[81];
	sprintf(fmtstr, "%%.%df", p);
	NxsString tmp;
	tmp.PrintF(fmtstr, x);

	NCL_ASSERT(w >= tmp.length());
	unsigned num_spaces = w - tmp.length();

	for (unsigned k = 0; k < num_spaces; k++)
		*this += ' ';

	*this += tmp;
	return *this;
	}
Exemplo n.º 29
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;
	}
Exemplo n.º 30
0
std::string assignUniqueName(const std::string & prefix, unsigned maxLen, const std::set<std::string> & safeLabelSet)
{
    NxsString s;
    s << prefix;
    std::set<std::string>::const_iterator sIt = safeLabelSet.find(s);
    if (sIt == safeLabelSet.end())
        return s;
    unsigned i = 1;
    for (;;)
    {
        NxsString numAsStr;
        numAsStr << i++;
        s.clear();
        unsigned concatLen = numAsStr.length() + prefix.length();
        if (concatLen > maxLen)
            s << prefix.substr(0, 2*maxLen - 1 - concatLen);
        else
            s << prefix;
        s << numAsStr;
        sIt = safeLabelSet.find(s);
        if (sIt == safeLabelSet.end())
            return s;
    }
}