Beispiel #1
0
/*----------------------------------------------------------------------------------------------------------------------
|	Called when an error is encountered in a NEXUS file. Allows program to give user details of the error as well as 
|	the precise location of the error.
*/
void GarliReader::NexusError(
  NxsString msg,	/* the error message */
  file_pos ,		/* the point in the NEXUS file where the error occurred */
  long line,		/* the line in the NEXUS file where the error occurred */
  long col,			/* the column in the NEXUS file where the error occurred */
  bool throwExcept /*=true*/)	/* whether to throw an actual exception or just output the error message */
	{
	message = "\n";
	message += msg;
	PrintMessage();

	if (1)
		{
		message = "Line:   ";
		message += line;
		PrintMessage();

		message = "Column: ";
		message += col;
		PrintMessage();
		}
	if(throwExcept)
		throw ErrorException("NCL encountered a problem reading the dataset.");
	}
Beispiel #2
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++;
			}
		}
	}
Beispiel #3
0
 void Globals::Globals_Init() {
   if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
     throw ErrorException(SDL_GetError());
   }
   screen = SDL_SetVideoMode(800, 600, 32, SDL_SWSURFACE | SDL_DOUBLEBUF);
 }
Beispiel #4
0
bool DisjunctiveCombinationProcessor::next()
{
	if (index < 0) {
		init();
		index = 0;
	}

	size_t size = inputs.size();
	if (!dimCount || !size) {
		return false;
	}

	bool hasNext = false;
	while (index < (int)size) {
		if (pos[index] == (int32_t)dimCount) {
			if (first[index]) {
				hasNext = true;
				first[index] = false;
			} else {
				hasNext = inputs[index]->next();
				if (!hasNext) {
					throw ErrorException(ErrorException::ERROR_INTERNAL, "internal error in DisjunctiveCombinationProcessor::next!");
				}
			}
			pos[index]--;
			break;
		}

		int32_t iDim;
		for (iDim = (int32_t)dimCount - 1; iDim >= 0; iDim--) {
			counter[index][iDim]++;
			if (counter[index][iDim] < setSize[iDim]) {
				break;
			}
		}
		pos[index] = iDim;
		if (iDim < 0) { // all keys from this stream are already returned
			index++;
		} else {
			if (index >= (int)firstDiff.size() || iDim > (int)firstDiff[index]) { // there is a set after firstDiff -> go back, if it is possible, otherwise continue with the same stream
				int i;
				for (i = index; i >= 0; i--) {
					if (index >= (int)firstDiff.size()) {
						if (pos[i] == -1) {
							break;
						} else if (i && pos[i] > pos[i - 1]) { // continue with the same stream
							i--;
							break;
						}
					} else {
						if (pos[i] < (int32_t)firstDiff[index]) {
							break;
						} else if (i && pos[i] > pos[i - 1]) { // continue with the same stream
							i--;
							break;
						}
					}
				}
				for (int j = i + 1; j <= index; j++) {
					for (size_t k = pos[j] + 1; k < dimCount; k++) {
						counter[j][k] = 0;
					}
					pos[j] = (int32_t)dimCount;
				}
				index = i + 1;
			} else { // there is a set before firstDiff -> check the next stream
				index++;
			}
		}
	}
	return hasNext;
}
Beispiel #5
0
bool FileUtils::copyFile(const std::string& fromFile,
                         const std::string &toFile) {
  throw ErrorException(ErrorException::ERROR_COPY_FAILED,
                       "file copy not implemented");
  // return true;
}
Beispiel #6
0
	//DJZ this is my function, replacing an old one that appeared in funcs.cpp
	//simpler now, since it uses NxsMultiFormatReader
bool GarliReader::ReadData(const char* filename, const ModelSpecification &modspec){
	//first use a few of my crappy functions to try to diagnose the type of file and data
	//then call the NxsMultiFormatReader functions to process it
	if (!FileExists(filename))	{
		throw ErrorException("data file not found: %s!", filename);
		}
	//if it is Nexus, don't need to specify anything else in advance
	if(FileIsNexus(filename)){
		outman.UserMessage("Attempting to read data file in Nexus format (using NCL):\n\t%s ...", filename);
		ReadFilepath(filename, NEXUS_FORMAT);
		}
	else{//if this isn't nexus we'll try a bunch of formats to see if we can get something to work
		//the idea here is that we create an ordered list of formats to try, then we try them 
		typedef pair<MultiFormatReader::DataFormatType, NxsString> FormatPair;
		list<FormatPair> formatsToTry;
		NxsString name;
		if(FileIsFasta(filename)){
			if(modspec.IsAminoAcid()){
				formatsToTry.push_back(FormatPair(FASTA_AA_FORMAT, "Fasta amino acid"));
				}
			else{
				if(modSpec.IsRna() == false)
					formatsToTry.push_back(FormatPair(FASTA_DNA_FORMAT, "Fasta DNA"));
				formatsToTry.push_back(FormatPair(FASTA_RNA_FORMAT, "Fasta RNA"));
				}
			}
		else{//otherwise assume phylip format
			if(modSpec.IsAminoAcid()){
				formatsToTry.push_back(FormatPair(RELAXED_PHYLIP_AA_FORMAT, "relaxed Phylip amino acid"));
				formatsToTry.push_back(FormatPair(INTERLEAVED_RELAXED_PHYLIP_AA_FORMAT, "interleaved relaxed Phylip amino acid"));
				formatsToTry.push_back(FormatPair(PHYLIP_AA_FORMAT, "strict Phylip amino acid"));
				formatsToTry.push_back(FormatPair(INTERLEAVED_PHYLIP_AA_FORMAT, "interleaved strict Phylip amino acid"));
				}
			else{
				if(modSpec.IsRna() == false){
					formatsToTry.push_back(FormatPair(RELAXED_PHYLIP_DNA_FORMAT, "relaxed Phylip DNA"));
					formatsToTry.push_back(FormatPair(INTERLEAVED_RELAXED_PHYLIP_DNA_FORMAT, "interleaved relaxed Phylip DNA"));
					formatsToTry.push_back(FormatPair(PHYLIP_DNA_FORMAT, "strict Phylip DNA"));
					formatsToTry.push_back(FormatPair(INTERLEAVED_PHYLIP_DNA_FORMAT, "interleaved strict Phylip DNA"));
					}

				formatsToTry.push_back(FormatPair(RELAXED_PHYLIP_RNA_FORMAT, "relaxed Phylip RNA"));
				formatsToTry.push_back(FormatPair(INTERLEAVED_RELAXED_PHYLIP_RNA_FORMAT, "interleaved relaxed Phylip RNA"));
				formatsToTry.push_back(FormatPair(PHYLIP_RNA_FORMAT, "strict Phylip RNA"));
				formatsToTry.push_back(FormatPair(INTERLEAVED_PHYLIP_RNA_FORMAT, "interleaved strict Phylip RNA"));
				}
			}
		//now start trying formats
		bool success;
		for(list<FormatPair>::iterator formIt = formatsToTry.begin();formIt != formatsToTry.end();formIt++){
			success = true;
			try{
				outman.UserMessage("Attempting to read data file %s as\n\t%s format (using NCL) ...", filename, (*formIt).second.c_str());
				ReadFilepath(filename, (*formIt).first);
				}catch(NxsException err){
					NexusError(err.msg, err.pos, err.line, err.col, false);
					outman.UserMessage("Problem reading data file as %s format...\n", (*formIt).second.c_str());
					success = false;
					}
			if(success) break;
			}
		if(success == false)
			throw ErrorException("\nUnable to read data file %s in any format.\n", filename);
		else 
			outman.UserMessage("\nData read successfully.");
		}
	return true;
	}
		SEM::TypeInstance* AddTypeInstance(Context& context, const AST::Node<AST::TypeInstance>& astTypeInstanceNode, const SEM::ModuleScope& moduleScope) {
			const auto parentNamespace = context.scopeStack().back().nameSpace();
			
			const auto& typeInstanceName = astTypeInstanceNode->name;
			
			const Name fullTypeName = parentNamespace->name() + typeInstanceName;
			
			// Check if there's anything with the same name.
			const auto iterator = parentNamespace->items().find(typeInstanceName);
			if (iterator != parentNamespace->items().end()) {
				const auto& existingTypeInstance = iterator->second.typeInstance();
				const auto& debugInfo = *(existingTypeInstance.debugInfo());
				throw ErrorException(makeString("Type instance name '%s', at position %s, clashes with existing name, at position %s.",
					fullTypeName.toString().c_str(), astTypeInstanceNode.location().toString().c_str(),
					debugInfo.location.toString().c_str()));
			}
			
			const auto typeInstanceKind = ConvertTypeInstanceKind(astTypeInstanceNode->kind);
			
			// Create a placeholder type instance.
			std::unique_ptr<SEM::TypeInstance> semTypeInstance(new SEM::TypeInstance(context.semContext(), fullTypeName.copy(), typeInstanceKind, moduleScope.copy()));
			
			if (semTypeInstance->isPrimitive()) {
				semTypeInstance->setPrimitiveID(context.sharedMaps().primitiveIDMap().getPrimitiveID(typeInstanceName));
			}
			
			switch (moduleScope.kind()) {
				case SEM::ModuleScope::INTERNAL: {
					if (semTypeInstance->isClassDecl()) {
						throw ErrorException(makeString("Definition required for internal class '%s', at location %s.",
							fullTypeName.toString().c_str(), astTypeInstanceNode.location().toString().c_str()));
					}
					break;
				}
				case SEM::ModuleScope::IMPORT: {
					if (semTypeInstance->isClassDef()) {
						throw ErrorException(makeString("Implementation not allowed of imported class '%s', at location %s.",
							fullTypeName.toString().c_str(), astTypeInstanceNode.location().toString().c_str()));
					}
					break;
				}
				case SEM::ModuleScope::EXPORT: {
					if (semTypeInstance->isClassDecl()) {
						throw ErrorException(makeString("Definition required for exported class '%s', at location %s.",
							fullTypeName.toString().c_str(), astTypeInstanceNode.location().toString().c_str()));
					}
					break;
				}
			}
			
			semTypeInstance->setDebugInfo(Debug::TypeInstanceInfo(astTypeInstanceNode.location()));
			
			// Add template variables.
			size_t templateVarIndex = 0;
			for (const auto& astTemplateVarNode: *(astTypeInstanceNode->templateVariables)) {
				const auto& templateVarName = astTemplateVarNode->name;
				// TODO!
				const bool isVirtual = (typeInstanceName == "__ref");
				const auto semTemplateVar =
					new SEM::TemplateVar(context.semContext(),
						fullTypeName + templateVarName,
						templateVarIndex++, isVirtual);
				
				const auto templateVarIterator = semTypeInstance->namedTemplateVariables().find(templateVarName);
				if (templateVarIterator != semTypeInstance->namedTemplateVariables().end()) {
					throw ErrorException(makeString("More than one template variable shares name '%s' in type '%s', at location %s.",
						templateVarName.c_str(), fullTypeName.toString().c_str(),
						astTemplateVarNode.location().toString().c_str()));
				}
				
				semTemplateVar->setDebugInfo(makeTemplateVarInfo(astTemplateVarNode));
				
				semTypeInstance->templateVariables().push_back(semTemplateVar);
				semTypeInstance->namedTemplateVariables().insert(std::make_pair(templateVarName, semTemplateVar));
			}
			
			if (semTypeInstance->isUnionDatatype()) {
				for (auto& astVariantNode: *(astTypeInstanceNode->variants)) {
					const auto variantTypeInstance = AddTypeInstance(context, astVariantNode, moduleScope);
					variantTypeInstance->setParent(semTypeInstance.get());
					variantTypeInstance->templateVariables() = semTypeInstance->templateVariables().copy();
					variantTypeInstance->namedTemplateVariables() = semTypeInstance->namedTemplateVariables().copy();
					semTypeInstance->variants().push_back(variantTypeInstance);
				}
			}
			
			if (!astTypeInstanceNode->noTagSet.isNull()) {
				SEM::TemplateVarArray noTagSet;
				
				for (const auto& astNoTagName: *(astTypeInstanceNode->noTagSet)) {
					const auto templateVarIterator = semTypeInstance->namedTemplateVariables().find(astNoTagName);
					if (templateVarIterator == semTypeInstance->namedTemplateVariables().end()) {
						throw ErrorException(makeString("Can't find template variable '%s' in notag() set in type '%s', at location %s.",
										astNoTagName.c_str(), fullTypeName.toString().c_str(),
										astTypeInstanceNode->noTagSet.location().toString().c_str()));
					}
					
					noTagSet.push_back(templateVarIterator->second);
				}
				
				semTypeInstance->setNoTagSet(std::move(noTagSet));
			}
			
			const auto typeInstancePtr = semTypeInstance.get();
			
			parentNamespace->items().insert(std::make_pair(typeInstanceName, SEM::NamespaceItem::TypeInstance(std::move(semTypeInstance))));
			
			return typeInstancePtr;
		}
Beispiel #8
0
void error(std::string msg) {
    throw ErrorException(msg);
}
Beispiel #9
0
void LegacyRule::reset()
{
	vkey.clear();
	throw ErrorException(ErrorException::ERROR_INTERNAL, "No reset for LegacyRule!");
}
Beispiel #10
0
void LegacyRule::setValue(const CellValue &value)
{
	throw ErrorException(ErrorException::ERROR_INTERNAL, "No setValue for LegacyRule");
}
Beispiel #11
0
		void Error(const char* text)
		{
			mprintf(("\n%s\n", text));

			if (Cmdline_noninteractive) {
				abort();
				return;
			}

			if (running_unittests) {
				throw ErrorException(text);
			}

			SCP_stringstream messageStream;
			messageStream << text << "\n";
			messageStream << dump_stacktrace();

			SCP_string fullText = messageStream.str();
			set_clipboard_text(fullText.c_str());

			fullText = truncateLines(messageStream, Messagebox_lines);

			fullText += "\n[ This info is in the clipboard so you can paste it somewhere now ]\n";
			fullText += "\n\nUse Debug to break into Debugger, Exit will close the application.\n";

			const SDL_MessageBoxButtonData buttons[] = {
				{ SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT, 1, "Exit" },
				{ /* .flags, .buttonid, .text */        0, 0, "Debug" },
			};

			SDL_MessageBoxData boxData;
			memset(&boxData, 0, sizeof(boxData));

			boxData.buttons = buttons;
			boxData.numbuttons = 2;
			boxData.colorScheme = nullptr;
			boxData.flags = SDL_MESSAGEBOX_ERROR;
			boxData.message = text;
			boxData.title = "Error!";
			boxData.window = os::getSDLMainWindow();

			gr_activate(0);

			int buttonId;
			if (SDL_ShowMessageBox(&boxData, &buttonId) < 0)
			{
				// Call failed
				exit(1);
			}

			switch (buttonId)
			{
			case 1:
				exit(1);

			default:
				Int3();
				break;
			}
			gr_activate(1);
		}
const GpuBinPath &SessionInfoProcessor::getBinKey() const
{
	throw ErrorException(ErrorException::ERROR_INTERNAL, "SessionInfoProcessor::getBinKey not implemented");
}
void SessionInfoProcessor::setValue(const CellValue &value)
{
	throw ErrorException(ErrorException::ERROR_INTERNAL, "SessionInfoProcessor::setValue not implemented");
}
double SessionInfoProcessor::getDouble()
{
	throw ErrorException(ErrorException::ERROR_INTERNAL, "SessionInfoProcessor::getDouble not implemented");
}
Beispiel #15
0
void error(std::string str) {
  throw ErrorException(str);
}
Beispiel #16
0
		SEM::Value GetTemplatedMethodWithoutResolution(Context& context, SEM::Value value, const SEM::Type* const type, const String& methodName, SEM::ValueArray templateArguments, const Debug::SourceLocation& location) {
			assert(value.type()->isRef() && value.type()->isBuiltInReference());
			if (!type->isObjectOrTemplateVar()) {
				throw ErrorException(makeString("Cannot get method '%s' for non-object type '%s' at position %s.",
					methodName.c_str(), type->toString().c_str(), location.toString().c_str()));
			}
			
			const auto methodSet = getTypeMethodSet(context, type);
			const auto& objectConstPredicate = methodSet->constPredicate();
			
			const auto canonicalMethodName = CanonicalizeMethodName(methodName);
			const auto methodIterator = methodSet->find(canonicalMethodName);
			
			if (methodIterator == methodSet->end()) {
				throw ErrorException(makeString("Cannot find method '%s' for type '%s' at position %s.",
					methodName.c_str(),
					type->toString().c_str(),
					location.toString().c_str()));
			}
			
			const auto& methodElement = methodIterator->second;
			if (methodElement.isStatic()) {
				throw ErrorException(makeString("Cannot access static method '%s' for value of type '%s' at position %s.",
					methodName.c_str(),
					type->toString().c_str(),
					location.toString().c_str()));
			}
			
			auto templateVariableAssignments = type->generateTemplateVarMap();
			
			const auto function = type->isObject() ? type->getObjectType()->functions().at(canonicalMethodName).get() : nullptr;
			
			if (function != nullptr) {
				const auto& templateVariables = function->templateVariables();
				if (templateVariables.size() != templateArguments.size()) {
					// Try to apply some basic deduction...
					if (templateVariables.size() == 1 && templateArguments.size() == 0 &&
						function->constPredicate().isVariable() &&
						function->constPredicate().variableTemplateVar() == templateVariables[0]
					) {
						const auto boolType = getBuiltInType(context, context.getCString("bool"), {});
						templateArguments.push_back(SEM::Value::PredicateExpr(objectConstPredicate.copy(), boolType));
					} else {
						throw ErrorException(makeString("Incorrect number of template "
							"arguments provided for method '%s'; %llu were required, "
							"but %llu were provided at position %s.",
							function->name().toString().c_str(),
							(unsigned long long) templateVariables.size(),
							(unsigned long long) templateArguments.size(),
							location.toString().c_str()));
					}
				}
				
				// Add function template variable => argument mapping.
				for (size_t i = 0; i < templateArguments.size(); i++) {
					const auto templateVariable = templateVariables.at(i);
					const auto& templateValue = templateArguments.at(i);
					
					if (templateValue.isTypeRef()) {
						const auto templateTypeValue = templateValue.typeRefType()->resolveAliases();
						
						if (!templateTypeValue->isObjectOrTemplateVar() || templateTypeValue->isInterface()) {
							throw ErrorException(makeString("Invalid type '%s' passed "
								"as template parameter '%s' for method '%s' at position %s.",
								templateTypeValue->toString().c_str(),
								templateVariable->name().toString().c_str(),
								function->name().toString().c_str(),
								location.toString().c_str()));
						}
						
						templateVariableAssignments.insert(std::make_pair(templateVariable, SEM::Value::TypeRef(templateTypeValue, templateValue.type())));
					} else {
						templateVariableAssignments.insert(std::make_pair(templateVariable, templateValue.copy()));
					}
				}
			} else {
				assert(templateArguments.empty());
			}
			
			const auto methodConstPredicate = methodElement.constPredicate().substitute(templateVariableAssignments);
			
			if (!objectConstPredicate.implies(methodConstPredicate)) {
				throw ErrorException(makeString("Cannot refer to mutator method '%s' from const object of type '%s' at position %s.",
					methodName.c_str(),
					type->toString().c_str(),
					location.toString().c_str()));
			}
			
			// Now check the template arguments satisfy the requires predicate.
			const auto& requirePredicate = methodElement.requirePredicate();
			
			// Conservatively assume require predicate is not satisified if result is undetermined.
			const bool satisfiesRequireDefault = false;
			
			if (!evaluatePredicateWithDefault(context, requirePredicate, templateVariableAssignments, satisfiesRequireDefault)) {
				throw ErrorException(makeString("Template arguments do not satisfy "
					"require predicate '%s' of method '%s' at position %s.",
					requirePredicate.substitute(templateVariableAssignments).toString().c_str(),
					methodName.c_str(),
					location.toString().c_str()));
			}
			
			if (function != nullptr) {
				const auto functionType = simplifyFunctionType(context, function->type().substitute(templateVariableAssignments));
				const auto functionRefType = createFunctionPointerType(context, functionType);
				
				auto functionRef = addDebugInfo(SEM::Value::FunctionRef(type, function, std::move(templateArguments), functionRefType), location);
				
				if (type->isInterface()) {
					const auto interfaceMethodType = createInterfaceMethodType(context, functionType);
					return addDebugInfo(SEM::Value::InterfaceMethodObject(std::move(functionRef), std::move(value), interfaceMethodType), location);
				} else {
					const auto methodType = createMethodType(context, functionType);
					return addDebugInfo(SEM::Value::MethodObject(std::move(functionRef), std::move(value), methodType), location);
				}
			} else {
				const bool isTemplated = true;
				const auto functionType = methodElement.createFunctionType(isTemplated);
				const auto functionRefType = createFunctionPointerType(context, functionType);
				auto functionRef = addDebugInfo(SEM::Value::TemplateFunctionRef(type, methodName, functionRefType), location);
				
				const auto methodType = createMethodType(context, functionType);
				return addDebugInfo(SEM::Value::MethodObject(std::move(functionRef), std::move(value), methodType), location);
			}
		}
Beispiel #17
0
int MPIMain(int argc, char** argv)	{

	MPI_Init(&argc, &argv);
	
	int rank, nprocs;
	MPI_Comm_rank(MPI_COMM_WORLD, &rank);
	MPI_Comm_size(MPI_COMM_WORLD, &nprocs);

	bool poo=true;
	//if(rank==0) while (poo) ;

	try{
	if (rank == 0)	{
        	MasterGamlConfig conf;
	        int err=conf.Read("garli.conf", true);
		if(err != 0){
			throw ErrorException("Error in config file (Master)...aborting.");
			}
		
		LogConfig(conf);

	        // Create the data object
        	HKYData data;
        	ReadData(conf.datafname.c_str(), &data);

	        // start the remote nodes going...
        	StartProcs(conf, data);

	        // start yourself!
        	MasterMaster(conf, data);

		}
	else	{ // rank != 0
	
		int from, tag, size;
		char* buf;
		HKYData data;
		GeneralGamlConfig conf;
		if (conf.Read("garli.conf") < 0)	{
			throw ErrorException("Error in config file (Remote)...aborting.");
			}

		//no longer sending the conf, just letting the remote read it from file
//		for (int i = 0; i < 2; ++i)	{
			RecvMPIMessage(&buf, &size, &from, &tag, true);
			assert(from == 0); // sanity check
			if (tag == TAG_DATA)	{
				data.Deserialize(buf, size);
				debug_mpi("receieved data from %d", from);
				}
/*			else if (tag == TAG_CONFIG)	{
				conf.Deserialize(buf, size);
				debug_mpi("received conf from %d", from);
				}
*/			else	{
				debug_mpi("ERROR: received unexpected message from %d with tag %d", from, tag);
				debug_mpi("aborting from MPIMain()");
				}
			delete [] buf;
//		}
		
//		LogConfig(conf);
		RemoteMaster(conf, data);
		}
	}catch(ErrorException err){
		err.Print(cout);
		}
	// time to kill some global vars
	delete [] node_results;
	
	MPI_Finalize();
	return 0;
}
Beispiel #18
0
 int StackValue::integerValue() const
 {
     if (_type != Type::INTEGER) throw ErrorException(std::string("StackValue::integerValue() - stack value is not integer, it is ") + typeName(_type));
     return _intValue;
 }
		void AddNamespaceData(Context& context, const AST::Node<AST::NamespaceData>& astNamespaceDataNode, const SEM::ModuleScope& moduleScope) {
			const auto semNamespace = context.scopeStack().back().nameSpace();
			
			for (const auto& astChildNamespaceNode: astNamespaceDataNode->namespaces) {
				const auto& childNamespaceName = astChildNamespaceNode->name;
				
				SEM::Namespace* semChildNamespace = nullptr;
				
				const auto iterator = semNamespace->items().find(childNamespaceName);
				if (iterator == semNamespace->items().end()) {
					std::unique_ptr<SEM::Namespace> childNamespace(new SEM::Namespace(semNamespace->name() + childNamespaceName, *semNamespace));
					semChildNamespace = childNamespace.get();
					semNamespace->items().insert(std::make_pair(childNamespaceName, SEM::NamespaceItem::Namespace(std::move(childNamespace))));
				} else {
					semChildNamespace = &(iterator->second.nameSpace());
				}
				
				PushScopeElement pushScopeElement(context.scopeStack(), ScopeElement::Namespace(semChildNamespace));
				AddNamespaceData(context, astChildNamespaceNode->data, moduleScope);
			}
			
			for (const auto& astModuleScopeNode: astNamespaceDataNode->moduleScopes) {
				if (!moduleScope.isInternal()) {
					throw ErrorException(makeString("Cannot nest module scopes, at position %s.",
						astModuleScopeNode.location().toString().c_str()));
				}
				AddNamespaceData(context, astModuleScopeNode->data, ConvertModuleScope(astModuleScopeNode));
			}
			
			for (const auto& astAliasNode: astNamespaceDataNode->aliases) {
				const auto& aliasName = astAliasNode->name;
				const auto fullTypeName = semNamespace->name() + aliasName;
				const auto iterator = semNamespace->items().find(aliasName);
				if (iterator != semNamespace->items().end()) {
					throw ErrorException(makeString("Type alias name '%s' clashes with existing name, at position %s.",
						fullTypeName.toString().c_str(), astAliasNode.location().toString().c_str()));
				}
				
				std::unique_ptr<SEM::Alias> semAlias(new SEM::Alias(context.semContext(), *semNamespace, fullTypeName.copy()));
				
				// Add template variables.
				size_t templateVarIndex = 0;
				for (auto astTemplateVarNode: *(astAliasNode->templateVariables)) {
					const auto& templateVarName = astTemplateVarNode->name;
					
					// TODO!
					const bool isVirtual = false;
					const auto semTemplateVar =
						new SEM::TemplateVar(context.semContext(),
							fullTypeName + templateVarName,
							templateVarIndex++, isVirtual);
					
					const auto templateVarIterator = semAlias->namedTemplateVariables().find(templateVarName);
					if (templateVarIterator != semAlias->namedTemplateVariables().end()) {
						throw TemplateVariableClashException(fullTypeName.copy(), templateVarName);
					}
					
					semAlias->templateVariables().push_back(semTemplateVar);
					semAlias->namedTemplateVariables().insert(std::make_pair(templateVarName, semTemplateVar));
				}
				
				PushScopeElement pushScopeElement(context.scopeStack(), ScopeElement::Alias(semAlias.get()));
				context.aliasTypeResolver().addAlias(*semAlias, astAliasNode->value, context.scopeStack().copy());
				
				semNamespace->items().insert(std::make_pair(aliasName, SEM::NamespaceItem::Alias(std::move(semAlias))));
			}
			
			for (const auto& astTypeInstanceNode: astNamespaceDataNode->typeInstances) {
				(void) AddTypeInstance(context, astTypeInstanceNode, moduleScope);
			}
		}
Beispiel #20
0
 float StackValue::floatValue() const
 {
     if (_type != Type::FLOAT) throw ErrorException(std::string("StackValue::floatValue() - stack value is not float, it is ") + typeName(_type));
     return _floatValue;
 }
Beispiel #21
0
 std::string StackValue::stringValue() const
 {
     if (_type != Type::STRING) throw ErrorException(std::string("StackValue::stringValue() - stack value is not string, it is ") + typeName(_type));
     return _stringValue;
 }
Beispiel #22
0
void AminoacidData::CalcEmpiricalFreqs(){
	empStateFreqs=new FLOAT_TYPE[maxNumStates];//this is a member of the class, and where the final freqs will be stored
	
	for(int i=0;i<maxNumStates;i++) empStateFreqs[i] = 0.0;
	FLOAT_TYPE total = 0.0;
	//for codons and aminoacids this will assume no ambiguity
	
	for( int i = 0; i < NTax(); i++ ) {
		for( int j = 0; j < nChar; j++ ) {
			char thischar= matrix[i][j];

			if(thischar != maxNumStates){
				assert(thischar > -1);
				empStateFreqs[thischar] += (FLOAT_TYPE) Count(j);
				total += (FLOAT_TYPE) Count(j);
				}
			}
		}
	//check whether this might be nucleotide data in disguise
	if((empStateFreqs[0]+empStateFreqs[1]+empStateFreqs[5]+empStateFreqs[16])/total > 0.90) throw ErrorException("Model specified as aminoacid, but nucleotide data found!");
		
	FLOAT_TYPE freqTot = 0.0;
	bool allPresent = true;
	for(int j=0;j<maxNumStates;j++) if(empStateFreqs[j] == ZERO_POINT_ZERO) allPresent = false;
	if(!allPresent){
		outman.UserMessage("WARNING: Not all amino acids were observed in this dataset.\n\tOne pseudo-count will be added to each amino acid for calculation of the\n\tempirical frequencies. You should probably use\n\ta statefrequencies setting other than emprical.\n");
		for(int j=0;j<maxNumStates;j++) empStateFreqs[j] += ONE_POINT_ZERO;
		total += (FLOAT_TYPE) maxNumStates;
		}
	for(int j=0;j<maxNumStates;j++){
		empStateFreqs[j] /= total;
		freqTot += empStateFreqs[j];
		}
	assert(fabs(freqTot - 1.0) < 1e-5);
	}
Beispiel #23
0
//verifies that we got the right number/type of blocks and returns the Characters block to be used
const NxsCharactersBlock *GarliReader::CheckBlocksAndGetCorrectCharblock(const ModelSpecification &) const{
	const int numTaxaBlocks = GetNumTaxaBlocks();
	if(numTaxaBlocks > 1) 
		throw ErrorException("Either more than one taxa block was found in the data file\n\tor multiple blocks had different taxon sets.");
	else if(numTaxaBlocks == 0)
		throw ErrorException("No taxa information was provided by NCL.\n\tThere may have been a problem reading the data file.\n\tCheck output above.");
	const NxsTaxaBlock *taxablock = GetTaxaBlock(0);
	const int numCharBlocks = GetNumCharactersBlocks(taxablock);
	outman.UserMessageNoCR("");
	if(numCharBlocks == 0)
		throw ErrorException("No character data was provided by NCL. There may have been a problem reading\n\tthe data file, or the data was of the wrong type. Check output above.");
	
	//now check that we only have one of the charblock types that we want
	int correctIndex = -1;
	for(unsigned c = 0;c < GetNumCharactersBlocks(taxablock);c++){
		const NxsCharactersBlock *charblock = GetCharactersBlock(taxablock, c);
		if((charblock->GetDataType() == NxsCharactersBlock::dna || charblock->GetDataType() == NxsCharactersBlock::nucleotide)
			&& (modSpec.IsNucleotide() || modSpec.IsCodon() || modSpec.IsCodonAminoAcid())){
			if(correctIndex > -1) throw ErrorException("More than one block containing nucleotide data was found.");
			else correctIndex = c;
			}
		//rna data is not allowed as input for codon or codon-aminoacid analyses
		else if(charblock->GetDataType() == NxsCharactersBlock::rna && (modSpec.IsNucleotide() || modSpec.IsRna())){
			if(correctIndex > -1) throw ErrorException("More than one block containing nucleotide data was found.");
			else correctIndex = c;
			}
		else if(charblock->GetDataType() == NxsCharactersBlock::protein && (modSpec.IsAminoAcid())){
			if(correctIndex > -1) throw ErrorException("More than one block containing amino acid (protein) data was found.");
			else correctIndex = c;
			}
		}
	if(correctIndex == -1){
		if(modSpec.IsNucleotide()) throw ErrorException("A data file was read, but no nucleotide data was found.");
		else if(modSpec.IsRna()) throw ErrorException("A data file was read, but no RNA data was found.");
		else if(modSpec.IsAminoAcid()) throw ErrorException("A data file was read, but no amino acid (protein) data was found.");
		else if(modSpec.IsCodon()) throw ErrorException("DNA data is required as input for codon models.\n\tA data file was read, but none was found.");
		else if(modSpec.IsCodonAminoAcid()) throw ErrorException("DNA data is required as input for codon translated amino acid models.\n\tA data file was read, but none was found.");
		}
	return GetCharactersBlock(taxablock, correctIndex);
	}
Beispiel #24
0
void CodonData::FillCodonMatrixFromDNA(const NucleotideData *dnaData){
	//first we need to convert the nucleotide data to codons numbered 0-60 or 61 and assign them back to the terminals
	//codons are ordered AAA, AAC, AAG, AAT, ACA, ... TTT
	short pos1, pos2, pos3;

	nChar = dnaData->NChar()/3;
	nTax = dnaData->NTax();
	if(dnaData->NChar() % 3 != 0) throw ErrorException("Codon datatype specified, but number of nucleotides not divisible by 3!");  
	NewMatrix(nTax, nChar);

	//this will just map from the bitwise format to the index format (A, C, G, T = 0, 1, 2, 3)
	//partial ambiguity is mapped to total ambiguity currently
	short bitwiseToIndexFormat[16] = {15,0,1,15,2,15,15,15,3,15,15,15,15,15,15,15};

	//keep track of the empirical base freqs at the codon positions, for possible use 
	//in the F1x4 or F3x4 methods of calculating the equilibrium codon freqs
	empBaseFreqsPos1[0]=empBaseFreqsPos1[1]=empBaseFreqsPos1[2]=empBaseFreqsPos1[3]=ZERO_POINT_ZERO;
	empBaseFreqsPos2[0]=empBaseFreqsPos2[1]=empBaseFreqsPos2[2]=empBaseFreqsPos2[3]=ZERO_POINT_ZERO;
	empBaseFreqsPos3[0]=empBaseFreqsPos3[1]=empBaseFreqsPos3[2]=empBaseFreqsPos3[3]=ZERO_POINT_ZERO;

	FLOAT_TYPE total = ZERO_POINT_ZERO;

	int tax=0, thisCodonNum;
	for(int tax=0;tax<NTax();tax++){
		bool firstAmbig = true;
		for(int cod=0;cod<nChar;cod++){
			short p1 = dnaData->Matrix(tax, cod*3);
			short p2 = dnaData->Matrix(tax, cod*3+1);
			short p3 = dnaData->Matrix(tax, cod*3+2);

			pos1 = bitwiseToIndexFormat[p1];
			pos2 = bitwiseToIndexFormat[p2];
			pos3 = bitwiseToIndexFormat[p3];
			
			thisCodonNum=(pos1)*16 + (pos2)*4 + pos3;
			
			if(pos1==15||pos2==15||pos3==15){//check for gaps or ambiguity
				if(pos1+pos2+pos3 != 45){
					//warn about gaps or ambiguity in codons
					if(firstAmbig){
						outman.UserMessageNoCR("Gaps or ambiguity codes found within codon for taxon %s.\n\tCodons coded as missing for that taxon: ", dnaData->TaxonLabel(tax));
						firstAmbig = false;
						}
					outman.UserMessageNoCR("%d ", cod+1);
					}
				thisCodonNum=64;
				}
			else{
				empBaseFreqsPos1[pos1] += ONE_POINT_ZERO;
				empBaseFreqsPos2[pos2] += ONE_POINT_ZERO;
				empBaseFreqsPos3[pos3] += ONE_POINT_ZERO;
				total += ONE_POINT_ZERO;
				}

			char prot;
			//note that a return code of 20 from the codon lookup indicates a stop codon, but a protein code of 20 generally means total ambiguity
			if(thisCodonNum != 64){
				prot = code.CodonLookup(thisCodonNum);
				if(prot == 20){
					string c;
					char b[4]={'A','C','G','T'};
					c += b[pos1];
					c += b[pos2];
					c += b[pos3];
					throw ErrorException("stop codon %s found at codon site %d (nuc site %d) in taxon %s.  Bailing out.", c.c_str(), cod+1, cod*3+1,  dnaData->TaxonLabel(tax));
					}
				}

			if(thisCodonNum == 64)//missing or ambiguous 
				matrix[tax][cod] = maxNumStates;
			else 
				matrix[tax][cod] = code.Map64stateToNonStops(thisCodonNum);
			}
		if(firstAmbig == false) outman.UserMessage("");
		}
	for(int b=0;b<4;b++){
		empBaseFreqsAllPos[b] = (empBaseFreqsPos1[b] + empBaseFreqsPos2[b] + empBaseFreqsPos3[b]) / (3.0 * total);

		empBaseFreqsPos1[b] /= total;
		empBaseFreqsPos2[b] /= total;
		empBaseFreqsPos3[b] /= total;
		}
	}
Beispiel #25
0
		SEM::Var* ConvertVar(Context& context, const Debug::VarInfo::Kind varKind, const AST::Node<AST::TypeVar>& astTypeVarNode) {
			const auto& location = astTypeVarNode.location();
			
			switch (astTypeVarNode->kind()) {
				case AST::TypeVar::ANYVAR: {
					throw ErrorException("'Any' vars not yet implemented for uninitialised variables.");
				}
				
				case AST::TypeVar::NAMEDVAR: {
					const auto& varName = astTypeVarNode->name();
					
					// Search all scopes outside of the current scope.
					const auto searchStartPosition = 1;
					if (varKind != Debug::VarInfo::VAR_MEMBER && !performSearch(context, Name::Relative() + varName, searchStartPosition).isNone()) {
						throw ErrorException(makeString("Variable '%s' shadows existing object at position %s.",
							varName.c_str(), location.toString().c_str()));
					}
					
					const auto varType = ConvertType(context, astTypeVarNode->namedType());
					
					// 'final' keyword uses a different lval type (which doesn't support
					// moving or re-assignment).
					const bool isFinalLval = astTypeVarNode->isFinal();
					
					const auto lvalType = makeLvalType(context, isFinalLval, varType);
					
					const auto var = SEM::Var::Basic(varType, lvalType);
					var->setMarkedUnused(astTypeVarNode->isUnused());
					var->setOverrideConst(astTypeVarNode->isOverrideConst());
					attachVar(context, varName, astTypeVarNode, var, varKind);
					return var;
				}
				
				case AST::TypeVar::PATTERNVAR: {
					const auto varType = ConvertType(context, astTypeVarNode->patternType())->resolveAliases();
					
					if (!varType->isDatatype()) {
						throw ErrorException(makeString("Can't pattern match for non-datatype '%s' at position %s.",
							varType->toString().c_str(), location.toString().c_str()));
					}
					
					const auto& astChildTypeVars = astTypeVarNode->typeVarList();
					const auto& typeChildVars = varType->getObjectType()->variables();
					
					if (astChildTypeVars->size() != typeChildVars.size()) {
						throw ErrorException(makeString("%llu pattern match children specified; %llu expected (for type '%s') at position %s.",
								(unsigned long long) astChildTypeVars->size(),
								(unsigned long long) typeChildVars.size(),
								varType->toString().c_str(),
								location.toString().c_str()));
					}
					
					const auto templateVarMap = varType->generateTemplateVarMap();
					
					std::vector<SEM::Var*> children;
					
					for (size_t i = 0; i < typeChildVars.size(); i++) {
						const auto& astVar = astChildTypeVars->at(i);
						children.push_back(ConvertVar(context, varKind, astVar));
					}
					
					return SEM::Var::Composite(varType, children);
				}
			}
			
			std::terminate();
		}
Beispiel #26
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++;
			}
		}
	}
void CaseManager::updateCaseStatus(int faceId, double percentageMatch)
{
    string randomIdentifier = "";

    srand (time(NULL) + faceId);
    for (int i = 0; i < 10; i++)
    {
        char c;
        int j = rand() % 4;
        if (j == 0)
        {
            c = (rand() % 10) + 48;
        }
        else if (j == 1)
        {
            c = (rand() % 26) + 65;
        }
        else
        {
            c = (rand() % 26) + 97;
        }
        randomIdentifier += c;
    }

    stringstream ss;
    ss << faceId;
    string strFaceId;
    ss >> strFaceId;
    randomIdentifier += strFaceId;

    if (databaseConnection->getDatabase().open())
    {
        QSqlQuery query;
        query.prepare("INSERT INTO case_results "
                      "(face_id, case_id, percentage_match, random_identifier) "
                      "VALUES (:faceId, :caseId, :percentageMatch, :randomIdentifier)");
        query.bindValue(":faceId", faceId);
        query.bindValue(":caseId", caseId);
        query.bindValue(":percentageMatch", percentageMatch);
        QString qRandomIdentifier(randomIdentifier.c_str());
        query.bindValue(":randomIdentifier", qRandomIdentifier);
        if(!query.exec())
        {
            QString error("inserting case result.");
            throw ErrorException(error, 0);
        }

        QSqlQuery updateQuery;
        updateQuery.prepare("UPDATE cases "
                      "SET num_results = num_results +1 "
                      "WHERE id = :caseId");
        updateQuery.bindValue(":caseId", caseId);
        if(!updateQuery.exec())
        {
            QString error("updating case result.");
            throw ErrorException(error, 1);
        }
    }
    else
    {
        QString error("database closed.");
        throw ErrorException(error, 3);
    }
}
Beispiel #28
0
 void OpcodeHandler::_error(const std::string& message)
 {
     throw ErrorException(message);
 }