Exemplo n.º 1
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.º 2
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.º 3
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.º 4
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.º 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
/*----------------------------------------------------------------------------------------------------------------------
	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.º 7
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.º 8
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.º 9
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.º 10
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.º 11
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.º 12
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.º 13
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.º 14
0
/*!
	Writes out the information in the MATRIX command in NEXUS format to the specified std::ostream.
*/
void NxsUnalignedBlock::WriteMatrixCommand(
  std::ostream & out)	/* is the output stream on which to print the matrix */
  const
	{
	NCL_ASSERT(taxa);
	const unsigned ntax = taxa->GetNTax();
	unsigned width = taxa->GetMaxTaxonLabelLength();
	out << "Matrix";

	//std::vector<unsigned> origIndexVec = this->GetOrigMatrixIndicesToWrite();
	bool first = true;
	for (unsigned i = 0; i < ntax; ++i)
		{
		if (!uMatrix[i].empty())
			{
			if (first)
				out << "\n";
			else
				out << ",\n";
			first = false;
			NxsString nm = taxa->GetTaxonLabel(i); /*v2.1to2.2 4 */
			std::string s = nm.c_str();
			const std::string currTaxonLabel = NxsString::GetEscaped(taxa->GetTaxonLabel(i));
			out << currTaxonLabel;

			// Print out enough spaces to even up the left edge of the matrix output
			unsigned currTaxonLabelLen = (unsigned)currTaxonLabel.size();
			unsigned diff = width - currTaxonLabelLen;
			for (unsigned k = 0; k < diff + 5; k++)
				out << ' ';

			WriteStatesForMatrixRow(out, i);
			}
		}
	out << "\n;\n";
	}
Exemplo n.º 15
0
/*!
	Reads rest of comment (starting '[' already input) and acts accordingly. If comment is an output comment, and if
	an output stream has been attached, writes the output comment to the output stream. Otherwise, output comments are
	simply ignored like regular comments.
	If the labileFlag bit saveCommandComments is in effect, and we are NOT in the middle of a token then the comment
		(without the [] braces) will be stored in token.
	All other comments are stored as embeddedComments.
	Returns true if a command comment was read and stored as the token
*/
bool NxsToken::GetComment()
	{
	// Set comment level to 1 initially.  Every ']' encountered reduces
	// level by one, so that we know we can stop when level becomes 0.
	//
	NxsString currentComment;
	bool command = false;

	bool formerEOFAllowed = eofAllowed;
	eofAllowed = false;
	try
		{
		char ch = GetNextChar();
		// See if first character is the output comment symbol ('!')
		// or command comment symbol (&)
		//
		int printing = 0;
		if (ch == '!')
			printing = 1;
		else if (ch == '&' && (labileFlags & saveCommandComments) && token.empty())
			command = true;
		currentComment.push_back(ch);
		if (ch != ']')
			{
			int level = 1;
			for(;;)
				{
				ch = GetNextChar();
				if (ch == ']')
					{
					level--;
					if (level == 0)
						break;
					}
				else if (ch == '[')
					level++;
				currentComment.push_back(ch);
				}

			if (printing)
				{
				// Allow output comment to be printed or displayed in most appropriate
				// manner for target operating system
				//
				NxsString foroutput(currentComment.c_str() + 1);
				comment = foroutput;
				OutputComment(foroutput);
				}
			if (command)
				token = currentComment;
			else
				embeddedComments.push_back(NxsComment(currentComment, GetFileLine(), GetFileColumn()));
			}
		}
	catch (NxsX_UnexpectedEOF & x)
		{
		x.msg << " (end-of-file inside comment)";
		eofAllowed = formerEOFAllowed;
		throw x;
		}
	eofAllowed = formerEOFAllowed ;
	return command;
	}
Exemplo n.º 16
0
void NucleotideData::CreateMatrixFromNCL(GarliReader &reader){
	NxsCharactersBlock *charblock;

	int num=0, numNuc = -1;
	do{
		charblock = reader.GetCharactersBlock(num);
		if(charblock->GetDataType() == NxsCharactersBlock::nucleotide ||
			charblock->GetDataType() == NxsCharactersBlock::dna ||
			charblock->GetDataType() == NxsCharactersBlock::rna){
			if(numNuc < 0) numNuc = num;
			else{
				throw ErrorException("Multiple characters/data blocks containing nucleotide data found in Nexus datafile!\n\tEither combine the blocks or comment one out.");
				}
			}
		else outman.UserMessage("Ignoring non-nucleotide characters block from Nexus datafile");
		num++;
		}while(num < reader.NumCharBlocks());
	if(numNuc < 0) throw ErrorException("No characters/data blocks containing nucleotide data found in Nexus datafile!");
	charblock = reader.GetCharactersBlock(numNuc);

	if(charblock->GetNumActiveChar() < charblock->GetNChar()){
		outman.UserMessageNoCR("Excluded characters:\n\t");
		for(int c=0;c<charblock->GetNCharTotal();c++)
			if(charblock->IsExcluded(c)) outman.UserMessageNoCR("%d ", c+1);
		outman.UserMessage("");
		}

//	vector<unsigned> reducedToOrigCharMap = charblock->GetOrigIndexVector();
	NxsTaxaBlock *taxablock = reader.GetTaxaBlock();
	
	int numOrigTaxa = charblock->GetNTax();
	int numActiveTaxa = charblock->GetNumActiveTaxa();
	int numOrigChar = charblock->GetNChar();
	int numActiveChar = charblock->GetNumActiveChar();
	//int num_chars = reducedToOrigCharMap.size();
	//cout << num_chars << endl;

	NewMatrix( numActiveTaxa, numActiveChar );

	// read in the data, including taxon names
	int i=0;
	for( int origTaxIndex = 0; origTaxIndex < numOrigTaxa; origTaxIndex++ ) {
		if(charblock->IsActiveTaxon(origTaxIndex)){
			//internally, blanks in taxon names will be stored as underscores
			NxsString tlabel = taxablock->GetTaxonLabel(origTaxIndex);
			tlabel.BlanksToUnderscores();
			SetTaxonLabel( i, tlabel.c_str());
			
			int j = 0;
			for( int origIndex = 0; origIndex < numOrigChar; origIndex++ ) {
				if(charblock->IsActiveChar(origIndex)){	
					unsigned char datum = '\0';
					if(charblock->IsGapState(origTaxIndex, origIndex) == true) datum = 15;
					else if(charblock->IsMissingState(origTaxIndex, origIndex) == true) datum = 15;
					else{
						int nstates = charblock->GetNumStates(origTaxIndex, origIndex);
						for(int s=0;s<nstates;s++){
							datum += CharToBitwiseRepresentation(charblock->GetState(origTaxIndex, origIndex, s));
							}
						}
					SetMatrix( i, j++, datum );
					}
				}
			i++;
			}
		}
	}
Exemplo n.º 17
0
void AminoacidData::CreateMatrixFromNCL(GarliReader &reader){
	NxsCharactersBlock *charblock;
	int num=0, numNuc = -1;
	do{
		charblock = reader.GetCharactersBlock(num);
		if(charblock->GetDataType() == NxsCharactersBlock::protein){
			if(numNuc < 0) numNuc = num;
			else{
				throw ErrorException("Multiple characters/data blocks containing protein data found in Nexus datafile!\n\tEither combine the blocks or comment one out.");
				}
			}
		else outman.UserMessage("Ignoring non-protein characters block from Nexus datafile");
		num++;
		}while(num < reader.NumCharBlocks());
	if(numNuc < 0) throw ErrorException("No characters/data blocks containing protein data found in Nexus datafile!");
	charblock = reader.GetCharactersBlock(numNuc);

	if(charblock->GetNumActiveChar() < charblock->GetNChar()){
		outman.UserMessageNoCR("Excluded characters:\n\t");
		for(int c=0;c<charblock->GetNCharTotal();c++)
			if(charblock->IsExcluded(c)) outman.UserMessageNoCR("%d ", c+1);
		outman.UserMessage("");
		}

//	vector<unsigned> reducedToOrigCharMap = charblock->GetOrigIndexVector();
	NxsTaxaBlock *taxablock = reader.GetTaxaBlock();
	
	int numOrigTaxa = charblock->GetNTax();
	int numActiveTaxa = charblock->GetNumActiveTaxa();
	int numOrigChar = charblock->GetNChar();
	int numActiveChar = charblock->GetNumActiveChar();
	//int num_chars = reducedToOrigCharMap.size();
	//cout << num_chars << endl;

	NewMatrix( numActiveTaxa, numActiveChar );

	// read in the data, including taxon names
	int i=0;
	for( int origTaxIndex = 0; origTaxIndex < numOrigTaxa; origTaxIndex++ ) {
		if(charblock->IsActiveTaxon(origTaxIndex)){
			//internally, blanks in taxon names will be stored as underscores
			NxsString tlabel = taxablock->GetTaxonLabel(origTaxIndex);
			tlabel.BlanksToUnderscores();
			SetTaxonLabel( i, tlabel.c_str());
			
			int j = 0;
			bool firstAmbig = true;
			for( int origIndex = 0; origIndex < numOrigChar; origIndex++ ) {
				if(charblock->IsActiveChar(origIndex)){	
					unsigned char datum = '\0';
					if(charblock->IsGapState(origTaxIndex, origIndex) == true) datum = 20;
					else if(charblock->IsMissingState(origTaxIndex, origIndex) == true) datum = 20;
					else{
						int nstates = charblock->GetNumStates(origTaxIndex, origIndex);
						//assert(nstates == 1);
						//need to deal with the possibility of multiple states represented in matrix
						//just convert to full ambiguity
						if(nstates == 1)
							datum = CharToDatum(charblock->GetState(origTaxIndex, origIndex, 0));
						else{
							if(firstAmbig){
								outman.UserMessageNoCR("Partially ambiguous characters of taxon %s converted to full ambiguity:\n\t", TaxonLabel(origTaxIndex));
								firstAmbig = false;
								}
							outman.UserMessageNoCR("%d ", origIndex+1);
							datum = CharToDatum('?');
							}
						}
					SetMatrix( i, j++, datum );
					}
				}
			if(firstAmbig == false) outman.UserMessage("");
			i++;
			}
		}
	}
Exemplo n.º 18
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();
		}
	}
Exemplo n.º 19
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;
		}
	}
Exemplo n.º 20
0
void writeCharactersAsGapped(ostream &out, NxsCharactersBlock * cb)
{
	if (!cb )
		return;
	NxsTaxaBlockAPI *tb = cb->GetTaxaBlockPtr(NULL);
	if (tb == NULL)
		return;
	NxsCharactersBlock::DataTypesEnum dt = cb->GetDataType();
	const char g = cb->GetGapSymbol();
	const std::string baseTitle = cb->GetTitle();
	if (tb == NULL
		|| dt == NxsCharactersBlock::standard
		|| dt == NxsCharactersBlock::continuous
		|| dt == NxsCharactersBlock::mixed
		|| (g == '\0' &&  !gGapCodeAllPresentSites))
		{
		cb->WriteAsNexus(out);
		writeCoreAssumptions(out, cb, baseTitle.c_str());
		return;
		}
	bool isAutogen = cb->IsAutoGeneratedTitle();
	std::string newTitle = baseTitle;
	newTitle.append("GapsAsMissing");
	cb->SetTitle(newTitle, isAutogen);

	std::set<unsigned> gappedColumns;
	std::set<unsigned> residueColumns;

	out << "BEGIN CHARACTERS;\n";
	cb->WriteBasicBlockCommands(out);

	const unsigned ntaxTotal = tb->GetNTax();
	out << "    DIMENSIONS";
	if (tb)
		{
		const unsigned wod = cb->GetNTaxWithData();
		if (wod > 0 && wod != ntaxTotal)
			out << " NTax=" << wod;
		}
	const unsigned nc = cb->GetNCharTotal();
	out << " NChar=" << nc << ";\n";
	cb->WriteEliminateCommand(out);
	cb->SetGapSymbol('\0');
	cb->WriteFormatCommand(out);
	cb->SetGapSymbol(g);

	cb->WriteCharStateLabelsCommand(out);

	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();

	unsigned width = tb->GetMaxTaxonLabelLength();
	out << "Matrix\n";
	unsigned begCharInd = 0;
	unsigned endCharInd = nc;
	for (unsigned i = 0; i < ntaxTotal; i++)
		{
		if (cb->TaxonIndHasData(i))
			{
			const std::string currTaxonLabel = NxsString::GetEscaped(tb->GetTaxonLabel(i));
			out << currTaxonLabel;
			unsigned currTaxonLabelLen = (unsigned)currTaxonLabel.size();
			unsigned diff = width - currTaxonLabelLen;
			for (unsigned k = 0; k < diff + 5; k++)
				out << ' ';

			const NxsDiscreteStateRow & row = cb->GetDiscreteMatrixRow(i);
			if (!row.empty())
				{
				const NxsDiscreteDatatypeMapper * dm = cb->GetDatatypeMapperForChar(0);
				if (dm == NULL)
					throw NxsNCLAPIException("No DatatypeMapper in WriteStatesForTaxonAsNexus");
				if (cb->IsMixedType())
					throw NxsNCLAPIException("Mixed datatypes are not supported by the NEXUSgapcode program.");
				if (cb->IsTokens())
					{
					for (unsigned charInd = begCharInd; charInd < endCharInd; ++charInd)
						{
						int sc = row[charInd];
						out << ' ';
						if (sc == NXS_GAP_STATE_CODE)
							out << dm->GetMissingSymbol();
						else
							{
							NxsString sl = cb->GetStateLabel(charInd, sc); /*v2.1to2.2 2 */
							if (sl == " ")
								{
								NxsString errormsg = "Writing character state ";
								errormsg << 1 + sc << " for character " << 1+charInd << ", but no appropriate chararcter label or symbol was found.";
								throw NxsNCLAPIException(errormsg);
								}
							else
								out  << NxsString::GetEscaped(sl);
							}
						}
					}
				else
					{
					std::vector<NxsDiscreteStateCell>::const_iterator endIt = row.begin() + begCharInd;
					std::vector<NxsDiscreteStateCell>::const_iterator begIt = endIt;
					if (endCharInd == row.size())
						endIt = row.end();
					else
						endIt += endCharInd - begCharInd;
					unsigned j = begCharInd;
					for (; begIt != endIt; ++begIt, ++j)
						{
						NxsDiscreteStateCell c;
						if (*begIt == NXS_GAP_STATE_CODE)
							{
							c = NXS_MISSING_CODE;
							gappedColumns.insert(j);
							}
						else
							{
							c = *begIt;
							if (gGapCodeAllPresentSites)
								gappedColumns.insert(j);
							residueColumns.insert(j);
							}
						dm->WriteStateCodeAsNexusString(out, c, true);
						}
					}
				}
			out << '\n';
			}
		}
	out << ";\n";
	cb->WriteSkippedCommands(out);
	out << "END;\n";


	writeCoreAssumptions(out, cb, newTitle.c_str());
	const unsigned nGappedCols = gappedColumns.size();
	if (nGappedCols > 0)
		{
		newTitle = baseTitle;
		newTitle.append("GapsAsBinary");
		cb->SetTitle(newTitle, isAutogen);
			out << "BEGIN CHARACTERS;\n";
		cb->WriteBasicBlockCommands(out);

		out << "    DIMENSIONS";
		if (tb)
			{
			const unsigned wod = cb->GetNTaxWithData();
			if (wod > 0 && wod != ntaxTotal)
				out << " NTax=" << wod;
			}
		out << " NChar=" << nGappedCols << ";\n";
		out << " CharStateLabels " ;
		unsigned currChNumber = 1;
		std::set<unsigned>::iterator gcIt = gappedColumns.begin();
		out << currChNumber++ << " col_" << (1 + *gcIt);
		for (++gcIt ; gcIt != gappedColumns.end(); ++gcIt)
			out << ",\n    " << currChNumber++ << " col_" << (1 + *gcIt);
		out << " ;\n" ;
		out << "Format Datatype = Standard Symbols=\"01\" missing = '?' ;\n";

		out << "Matrix\n";
		for (unsigned i = 0; i < ntaxTotal; i++)
			{
			if (cb->TaxonIndHasData(i))
				{
				const std::string currTaxonLabel = NxsString::GetEscaped(tb->GetTaxonLabel(i));
				out << currTaxonLabel;
				unsigned currTaxonLabelLen = (unsigned)currTaxonLabel.size();
				unsigned diff = width - currTaxonLabelLen;
				for (unsigned k = 0; k < diff + 5; k++)
					out << ' ';

				const NxsDiscreteStateRow & row = cb->GetDiscreteMatrixRow(i);
				for (std::set<unsigned>::iterator cIt = gappedColumns.begin(); cIt != gappedColumns.end(); ++cIt)
					{
					NxsDiscreteStateCell sc = row[*cIt];
					if (sc == NXS_GAP_STATE_CODE)
						{
						if (gGapCodeAllAbsentSites || (residueColumns.find(*cIt) != residueColumns.end()))
							out << '0';
						else
							out << '?';
						}
					else if (sc == NXS_MISSING_CODE) 
						{
						out << '?';
						}
					else 
						{
						out << '1';
						}
					}
				out << '\n';
				}
			}
		out << ";\n";
		cb->WriteSkippedCommands(out);
		out << "END;\n";
		}

	std::vector<int>			gapintWts;
	std::vector<double>			gapdblWts;
	std::set<unsigned>			gapactiveExSet;
	if (!activeExSet.empty())
		{
		unsigned gapind = 0;
		for (std::set<unsigned>::iterator cIt = gappedColumns.begin(); cIt != gappedColumns.end(); ++cIt, ++gapind)
			{
			if (activeExSet.find(*cIt) != activeExSet.end())
				gapactiveExSet.insert(gapind);
			}
		}
	if (!intWts.empty())
		{
		for (std::set<unsigned>::iterator cIt = gappedColumns.begin(); cIt != gappedColumns.end(); ++cIt)
			gapintWts.push_back(intWts[*cIt]);
		}
	if (!dblWts.empty())
		{
		for (std::set<unsigned>::iterator cIt = gappedColumns.begin(); cIt != gappedColumns.end(); ++cIt)
			gapdblWts.push_back(dblWts[*cIt]);
		}

	if (!(gapactiveExSet.empty() && gapintWts.empty() && gapdblWts.empty()))
		{
		out << "BEGIN ASSUMPTIONS; \n    LINK CHARACTERS = ";
		out << NxsString::GetEscaped(newTitle) << " ;\n";
		if (!gapactiveExSet.empty())
			{
			NxsString exsetName;
			exsetName << newTitle;
			exsetName.append("GapExSet");
			NxsUnsignedSetMap m;
			m[exsetName] = gapactiveExSet;
			NxsWriteSetCommand("EXSET", m, out, exsetName.c_str());;
			}
		if (!(gapintWts.empty() && gapdblWts.empty()))
			{
			NxsTransformationManager &cbntm = cb->GetNxsTransformationManagerRef();
			std::string wtSetName =  cbntm.GetDefaultWeightSetName();
			wtSetName.append("GapWtSet");
			NxsTransformationManager ntm;
			if (!gapintWts.empty())
				{
				NxsTransformationManager::ListOfIntWeights iw;
				vecToListOfIntWeights(gapintWts, iw);
				ntm.AddIntWeightSet(wtSetName, iw, true);
				}
			else
				{
				NxsTransformationManager::ListOfDblWeights dw;
				vecToListOfDblWeights(gapdblWts, dw);
				ntm.AddRealWeightSet(wtSetName, dw, true);
				}
			ntm.WriteWtSet(out);
			}
		out << "END;\n";
		}


	cb->SetTitle(baseTitle, isAutogen);
}