Exemplo n.º 1
0
void writeSystemInformation(TextWriter *writer, const gmx_mtop_t &top, bool writeFormattedText)
{
    int                       nmol, nvsite = 0;
    gmx_mtop_atomloop_block_t aloop;
    const t_atom             *atom;

    writeHeader(writer, "Simulation system", "subsection", writeFormattedText);
    aloop = gmx_mtop_atomloop_block_init(&top);
    while (gmx_mtop_atomloop_block_next(aloop, &atom, &nmol))
    {
        if (atom->ptype == eptVSite)
        {
            nvsite += nmol;
        }
    }
    {
        writer->writeLine(formatString("A system of %d molecules (%d atoms) was simulated.",
                                       gmx_mtop_num_molecules(top), top.natoms-nvsite));
    }
    if (nvsite)
    {
        writer->writeLine(formatString("Virtual sites were used in some of the molecules."));
    }
    writer->ensureEmptyLine();
}
Exemplo n.º 2
0
void HelpWriterContext::writeOptionItem(const std::string &name,
                                        const std::string &args,
                                        const std::string &description) const
{
    File &file = outputFile();
    switch (outputFormat())
    {
        case eHelpOutputFormat_Console:
            // TODO: Generalize this when there is need for it; the current,
            // special implementation is in CommandLineHelpWriter.
            GMX_THROW(NotImplementedError("Option item formatting for console output not implemented"));
            break;
        case eHelpOutputFormat_Man:
            file.writeLine(formatString(".BI \"\\%s\" \" %s\"", name.c_str(), args.c_str()));
            file.writeString("    ");
            writeTextBlock(description);
            file.writeLine();
            break;
        case eHelpOutputFormat_Html:
        {
            std::string substArgs =
                substituteMarkupAndWrapToString(TextLineWrapperSettings(), args);
            file.writeLine(formatString("<dt><b><tt>%s</tt></b> %s</dt>", name.c_str(),
                                        substArgs.c_str()));
            file.writeLine("<dd>");
            writeTextBlock(description);
            file.writeLine("</dd>");
            break;
        }
        default:
            GMX_THROW(NotImplementedError(
                              "This output format is not implemented"));
    }
}
Exemplo n.º 3
0
CAssemblerCommand* ArmElfRelocator::generateCtorStub(std::vector<ElfRelocatorCtor>& ctors)
{
	std::wstring ctorText;

	Parser parser;
	if (ctors.size() != 0)
	{
		bool simpleMode = arm9 == false && Arm.GetThumbMode();

		// create constructor table
		std::wstring table;
		for (size_t i = 0; i < ctors.size(); i++)
		{
			if (i != 0)
				table += ',';
			table += formatString(L"%s,%s+0x%08X",ctors[i].symbolName,ctors[i].symbolName,ctors[i].size);
		}

		return parser.parseTemplate(ctorTemplate,{
			{ L"%ctorTable%",		Global.symbolTable.getUniqueLabelName() },
			{ L"%ctorTableSize%",	formatString(L"%d",ctors.size()*8) },
			{ L"%outerLoopLabel%",	Global.symbolTable.getUniqueLabelName() },
			{ L"%innerLoopLabel%",	Global.symbolTable.getUniqueLabelName() },
			{ L"%stubName%",		Global.symbolTable.getUniqueLabelName() },
			{ L"%simpleMode%",		simpleMode ? L"1" : L"0" },
			{ L"%ctorContent%",		table },
		});
	} else {
		return parser.parseTemplate(L"bx r14");
	}
}
Exemplo n.º 4
0
void MainWindow::handle_pushButton_decrypt_onClick()
{
  int size = 0;
  QString q_key = ui->textEdit_key->toPlainText();
  string s_key = string((const char *)q_key.toLocal8Bit()); 
  size = formatString(s_key);
  byte key[size];
  hexStringToBytes(s_key,key);
  //pnt_byte(key,16);

  QString q_in = ui->textEdit_input->toPlainText();
  string s_in = string((const char *)q_in.toLocal8Bit()); 
  size = formatString(s_in);
  byte in[size];
  hexStringToBytes(s_in,in);
  //pnt_byte(in,70);

  byte *out = NULL;
  CRYPTER *crypter = new CRYPTER(key);	
  int len = crypter->decrypt(in,size,out);
  //pnt_byte(out,len);

  string s_out = bytesToHexString(out,len);
  QString q_out = QString(QString::fromLocal8Bit(s_out.c_str()));
  ui->textEdit_output->setPlainText(q_out);
  //std::cout << "handle_pushButton_decrypt_onClick" << std::endl;

  delete out;
  delete crypter;
}
Exemplo n.º 5
0
void HelpManager::enterTopic(const char *name)
{
    const HelpTopicInterface &topic = impl_->currentTopic();
    if (!topic.hasSubTopics())
    {
        GMX_THROW(InvalidInputError(
                    formatString("Help topic '%s' has no subtopics",
                                 impl_->currentTopicAsString().c_str())));
    }
    const HelpTopicInterface *newTopic = topic.findSubTopic(name);
    if (newTopic == NULL)
    {
        if (impl_->isAtRootTopic())
        {
            GMX_THROW(InvalidInputError(
                        formatString("No help available for '%s'", name)));
        }
        else
        {
            GMX_THROW(InvalidInputError(
                        formatString("Help topic '%s' has no subtopic '%s'",
                                     impl_->currentTopicAsString().c_str(), name)));
        }
    }
    impl_->topicStack_.push_back(newTopic);
}
std::string FloatingPointTolerance::toString() const
{
    std::string result;
    if (absoluteTolerance_ > 0.0)
    {
        result.append(formatString("abs. %g", absoluteTolerance_));
    }
    if (ulpTolerance_ >= 0)
    {
        if (!result.empty())
        {
            result.append(", ");
        }
        result.append(formatString("%d ULPs", ulpTolerance_));
    }
    if (bSignMustMatch_)
    {
        if (!result.empty())
        {
            result.append(", ");
        }
        result.append("sign must match");
    }
    return result;
}
Exemplo n.º 7
0
String XmippError::getMessage() const
{
      String error = formatString("XMIPP_ERROR %d: %s\n   ", __errno, getDefaultMessage().c_str());
      error += msg;
      error += formatString("\n   File: %s line: %ld\n", file.c_str(), line);
      return error;
}
Exemplo n.º 8
0
void PropertyTreePrinter::printStep(const PropertyNode & node, int level) const {
	std::string outerIndent = getLevelIndent(level);
	std::string innerIndent = getLevelIndent(level + 1);
	
	output << outerIndent << formatString(node.getName()) << " ";
	
	for (int i = 0; i < node.getNumAttributes(); ++i)
		output << formatString(node.getAttribute(i)) << " ";
	
	if (bracketOwnLine)
		output << "\n" << outerIndent << "{\n";
	else
		output << "{\n";
	
	for (int i = 0; i < node.getNumProperties(); ++i) {
		Property property = node.getProperty(i);

		output << innerIndent << formatString(property.first) << " " << formatString(property.second) << "\n";
	}
		
	if (node.getNumProperties() > 0 && node.getNumNodes() > 0)
		output << "\n";
	
	for (int i = 0; i < node.getNumNodes(); ++i) {
		printStep(node.getNode(i), level + 1);
		
		if (i < node.getNumNodes() - 1)
			output << "\n";
	}
	
	output << outerIndent << "}\n";
}
Exemplo n.º 9
0
string IseServerInspector::outputHelpPage()
{
    string result;

    for (InspectInfo::iterator i = inspectInfo_.begin(); i != inspectInfo_.end(); ++i)
    {
        string category = i->first;
        CommandList& commandList = i->second;

        for (CommandList::iterator j = commandList.begin(); j != commandList.end(); ++j)
        {
            string command = j->first;
            CommandItem& commandItem = j->second;

            string help;
            if (!commandItem.help.empty())
                help = formatString("<span style=\"color:#cfcfcf\">(%s)</span>", commandItem.help.c_str());

            string path = formatString("/%s/%s", category.c_str(), command.c_str());
            string line = formatString("<a href=\"%s\">[%s]</a> %s",
                path.c_str(), path.c_str(), help.c_str());
            if (!result.empty()) result += "</br>";
            result += line;
        }

        result += "</br>";
    }

    return result;
}
Exemplo n.º 10
0
// Continuous assignment ===================================================
double ProgNmaAlignment::performContinuousAssignment(const FileName &fnRandom,
		int pyramidLevel) const {
	// Perform alignment
	const char * randStr = fnRandom.c_str();
	String fnResults=formatString("%s_anglecont.xmd", randStr);
	bool costSource=true;
	String program = "xmipp_angular_continuous_assign";
	String arguments =
			formatString(
					"-i %s_angledisc.xmd --ref %s_deformedPDB.vol -o %s --gaussian_Fourier %f --gaussian_Real %f --zerofreq_weight %f -v 0",
					randStr, randStr, fnResults.c_str(), gaussian_DFT_sigma,
					gaussian_Real_sigma, weight_zero_freq);
	runSystem(program, arguments, false);

	// Pick up results
	MetaData DF(fnResults);
	MDRow row;
	DF.getRow(row, DF.firstObject());
	row.getValue(MDL_ANGLE_ROT, trial(VEC_XSIZE(trial) - 5));
	row.getValue(MDL_ANGLE_TILT, trial(VEC_XSIZE(trial) - 4));
	row.getValue(MDL_ANGLE_PSI, trial(VEC_XSIZE(trial) - 3));
	row.getValue(MDL_SHIFT_X, trial(VEC_XSIZE(trial) - 2));
	trial(VEC_XSIZE(trial) - 2) *= pow(2.0, (double) pyramidLevel);
	row.getValue(MDL_SHIFT_Y, trial(VEC_XSIZE(trial) - 1));
	trial(VEC_XSIZE(trial) - 1) *= pow(2.0, (double) pyramidLevel);
	double tempvar;
	if (!costSource) {
		row.getValue(MDL_MAXCC, tempvar);
		tempvar = -tempvar;
	} else
		row.getValue(MDL_COST, tempvar);
	return tempvar;
}
Exemplo n.º 11
0
void CommandLineHelpModuleImpl::exportHelp(HelpExportInterface *exporter) const
{
    // TODO: Would be nicer to have the file names supplied by the build system
    // and/or export a list of files from here.
    const char *const program = binaryName_.c_str();

    exporter->startModuleExport();
    CommandLineModuleMap::const_iterator module;
    for (module = modules_.begin(); module != modules_.end(); ++module)
    {
        if (module->second->shortDescription() != NULL)
        {
            const char *const moduleName = module->first.c_str();
            std::string       tag(formatString("%s-%s", program, moduleName));
            std::string       displayName(formatString("%s %s", program, moduleName));
            exporter->exportModuleHelp(*module->second, tag, displayName);
        }
    }
    exporter->finishModuleExport();

    exporter->startModuleGroupExport();
    CommandLineModuleGroupList::const_iterator group;
    for (group = groups_.begin(); group != groups_.end(); ++group)
    {
        exporter->exportModuleGroup((*group)->title(), (*group)->modules());
    }
    exporter->finishModuleGroupExport();
}
Exemplo n.º 12
0
void Date::setFormatStrings(const QString &fullFormat, const QString &partialFormat)
{
    if (fullFormat != formatString(Full) || partialFormat != formatString(Partial)) {
        QSettings().setValue("Date/FullFormat", fullFormat);
        QSettings().setValue("Date/PartialFormat", partialFormat);
        loadFormatStrings();
        ChangeManager::bump();
    }
}
Exemplo n.º 13
0
// Show message
std::ostream& operator << (std::ostream& o, XmippError& xe)
{
    String error = formatString("XMIPP_ERROR %d: %s", xe.__errno, xe.getDefaultMessage().c_str());
    o << colorString(error.c_str(), RED) << std::endl;
    o << colorString(xe.msg.c_str(), RED) << std::endl;
    error = formatString("File: %s line: %ld", xe.file.c_str(), xe.line);
    o << colorString(error.c_str(), RED) << std::endl;
    return o;
}
Exemplo n.º 14
0
 void compile(const char *value)
 {
     std::string buf(formatString("^%s$", value));
     int         rc = regcomp(&regex_, buf.c_str(), REG_EXTENDED | REG_NOSUB);
     if (rc != 0)
     {
         // TODO: Better error messages.
         GMX_THROW(InvalidInputError(formatString(
                                             "Error in regular expression \"%s\"", value)));
     }
 }
Exemplo n.º 15
0
string PredefinedInspector::getBasicInfo(const PropertyList& argList,
    string& contentType)
{
    contentType = "text/plain";

    StrList strList;
    strList.add(formatString("path: %s", getAppExeName().c_str()));
    strList.add(formatString("pid: %d", ::getpid()));

    return strList.getText();
}
Exemplo n.º 16
0
void CDirectivePosition::writeTempData(TempData& tempData)
{
	switch (type)
	{
	case Physical:
		tempData.writeLine(g_fileManager->getVirtualAddress(),formatString(L".orga 0x%08X",position));
		break;
	case Virtual:
		tempData.writeLine(g_fileManager->getVirtualAddress(),formatString(L".org 0x%08X",position));
		break;
	}
}
Exemplo n.º 17
0
void SelectionTreeElement::resolveIndexGroupReference(
    gmx_ana_indexgrps_t *grps, int natoms)
{
    GMX_RELEASE_ASSERT(type == SEL_GROUPREF,
                       "Should only be called for index group reference elements");
    if (grps == NULL)
    {
        std::string message = formatString(
                                  "Cannot match '%s', because index groups are not available.",
                                  name().c_str());
        GMX_THROW(InconsistentInputError(message));
    }

    gmx_ana_index_t foundGroup;
    std::string     foundName;
    if (u.gref.name != NULL)
    {
        if (!gmx_ana_indexgrps_find(&foundGroup, &foundName, grps, u.gref.name))
        {
            std::string message = formatString(
                                      "Cannot match '%s', because no such index group can be found.",
                                      name().c_str());
            GMX_THROW(InconsistentInputError(message));
        }
    }
    else
    {
        if (!gmx_ana_indexgrps_extract(&foundGroup, &foundName, grps, u.gref.id))
        {
            std::string message = formatString(
                                      "Cannot match '%s', because no such index group can be found.",
                                      name().c_str());
            GMX_THROW(InconsistentInputError(message));
        }
    }

    if (!gmx_ana_index_check_sorted(&foundGroup))
    {
        flags |= SEL_UNSORTED;
    }

    sfree(u.gref.name);
    type = SEL_CONST;
    gmx_ana_index_set(&u.cgrp, foundGroup.isize, foundGroup.index,
                      foundGroup.nalloc_index);
    setName(foundName);

    if (natoms > 0)
    {
        checkIndexGroup(natoms);
    }
}
Exemplo n.º 18
0
// Compute fitness =========================================================
double ObjFunc_nma_alignment::eval(Vector X, int *nerror) {
	int dim = global_nma_prog->numberOfModes;

	for (int i = 0; i < dim; i++) {
		global_nma_prog->trial(i) = X[i];
	}

	int pyramidLevelDisc = 1;
	int pyramidLevelCont = (global_nma_prog->currentStage == 1) ? 1 : 0;

	FileName fnRandom = global_nma_prog->createDeformedPDB(pyramidLevelCont);
	const char * randStr = fnRandom.c_str();

	if (global_nma_prog->currentStage == 1) {
		global_nma_prog->performCompleteSearch(fnRandom, pyramidLevelDisc);
	} else {
		double rot, tilt, psi, xshift, yshift;
		MetaData DF;

		rot = global_nma_prog->bestStage1(
				VEC_XSIZE(global_nma_prog->bestStage1) - 5);
		tilt = global_nma_prog->bestStage1(
				VEC_XSIZE(global_nma_prog->bestStage1) - 4);
		psi = global_nma_prog->bestStage1(
				VEC_XSIZE(global_nma_prog->bestStage1) - 3);
		xshift = global_nma_prog->bestStage1(
				VEC_XSIZE(global_nma_prog->bestStage1) - 2);
		yshift = global_nma_prog->bestStage1(
				VEC_XSIZE(global_nma_prog->bestStage1) - 1);

		size_t objId = DF.addObject();
		FileName fnDown = formatString("%s_downimg.xmp", randStr);
		DF.setValue(MDL_IMAGE, fnDown, objId);
		DF.setValue(MDL_ENABLED, 1, objId);
		DF.setValue(MDL_ANGLE_ROT, rot, objId);
		DF.setValue(MDL_ANGLE_TILT, tilt, objId);
		DF.setValue(MDL_ANGLE_PSI, psi, objId);
		DF.setValue(MDL_SHIFT_X, xshift, objId);
		DF.setValue(MDL_SHIFT_Y, yshift, objId);

		DF.write(formatString("%s_angledisc.xmd", randStr));
		copyImage(global_nma_prog->currentImgName.c_str(), fnDown.c_str());
	}
	double fitness = global_nma_prog->performContinuousAssignment(fnRandom,
			pyramidLevelCont);

	runSystem("rm", formatString("-rf %s* &", randStr));

	global_nma_prog->updateBestFit(fitness, dim);
	return fitness;
}
Exemplo n.º 19
0
// Create deformed PDB =====================================================
FileName ProgNmaAlignment::createDeformedPDB(int pyramidLevel) const {
	String program;
	String arguments;
	FileName fnRandom;
	fnRandom.initUniqueName(nameTemplate,fnOutDir);
	const char * randStr = fnRandom.c_str();

	program = "xmipp_pdb_nma_deform";
	arguments = formatString(
			"--pdb %s -o %s_deformedPDB.pdb --nma %s --deformations ",
			fnPDB.c_str(), randStr, fnModeList.c_str());
	for (size_t i = 0; i < VEC_XSIZE(trial) - 5; ++i)
		arguments += floatToString(trial(i)) + " ";
	runSystem(program, arguments, false);

	program = "xmipp_volume_from_pdb";
	arguments = formatString(
			"-i %s_deformedPDB.pdb --size %i --sampling %f -v 0", randStr,
			imgSize, sampling_rate);

	if (do_centerPDB)
		arguments.append(" --centerPDB ");

	if (useFixedGaussian) {
		arguments.append(" --intensityColumn Bfactor --fixed_Gaussian ");
		if (sigmaGaussian >= 0)
			arguments += formatString("%f",sigmaGaussian);
	}
	//else
		//arguments +=" --poor_Gaussian"; // Otherwise, a detailed conversion of the atoms takes too long in this context
		
	progVolumeFromPDB->read(arguments);
	progVolumeFromPDB->tryRun();

	if (do_FilterPDBVol) {
		program = "xmipp_transform_filter";
		arguments = formatString(
						"-i %s_deformedPDB.vol --sampling %f --fourier low_pass %f  -v 0",
						randStr, sampling_rate, cutoff_LPfilter);
		runSystem(program, arguments, false);
	}

	if (pyramidLevel != 0) {
		Image<double> I;
		FileName fnDeformed = formatString("%s_deformedPDB.vol",randStr);
		I.read(fnDeformed);
		selfPyramidReduce(BSPLINE3, I(), pyramidLevel);
		I.write(fnDeformed);
	}
	return fnRandom;
}
Exemplo n.º 20
0
void writeParameterInformation(TextWriter *writer, const t_inputrec &ir, bool writeFormattedText)
{
    writeHeader(writer, "Simulation settings", "subsection", writeFormattedText);
    writer->writeLine(formatString("A total of %g ns were simulated with a time step of %g fs.",
                                   ir.nsteps*ir.delta_t*0.001, 1000*ir.delta_t));
    writer->writeLine(formatString("Neighbor searching was performed every %d steps.", ir.nstlist));
    writer->writeLine(formatString("The %s algorithm was used for electrostatic interactions.",
                                   EELTYPE(ir.coulombtype)));
    writer->writeLine(formatString("with a cut-off of %g nm.", ir.rcoulomb));
    if (ir.coulombtype == eelPME)
    {
        writer->writeLine(formatString("A reciprocal grid of %d x %d x %d cells was used with %dth order B-spline interpolation.", ir.nkx, ir.nky, ir.nkz, ir.pme_order));
    }
    writer->writeLine(formatString("A single cut-off of %g nm was used for Van der Waals interactions.", ir.rlist));
    if (ir.etc != 0)
    {
        writer->writeLine(formatString("Temperature coupling was done with the %s algorithm.",
                                       etcoupl_names[ir.etc]));
    }
    if (ir.epc != 0)
    {
        writer->writeLine(formatString("Pressure coupling was done with the %s algorithm.",
                                       epcoupl_names[ir.epc]));
    }
    writer->ensureEmptyLine();
}
Exemplo n.º 21
0
void Stringifier::stringify(const Var& any, std::ostream& out, unsigned int indent, int step, int options)
{
	bool escapeUnicode = ((options & Poco::JSON_ESCAPE_UNICODE) != 0);

	if (step == -1) step = indent;

	if (any.type() == typeid(Object))
	{
		Object& o = const_cast<Object&>(any.extract<Object>());
		o.setEscapeUnicode(escapeUnicode);
		o.stringify(out, indent == 0 ? 0 : indent, step);
	}
	else if (any.type() == typeid(Array))
	{
		Array& a = const_cast<Array&>(any.extract<Array>());
		a.setEscapeUnicode(escapeUnicode);
		a.stringify(out, indent == 0 ? 0 : indent, step);
	}
	else if (any.type() == typeid(Object::Ptr))
	{
		Object::Ptr& o = const_cast<Object::Ptr&>(any.extract<Object::Ptr>());
		o->setEscapeUnicode(escapeUnicode);
		o->stringify(out, indent == 0 ? 0 : indent, step);
	}
	else if (any.type() == typeid(Array::Ptr))
	{
		Array::Ptr& a = const_cast<Array::Ptr&>(any.extract<Array::Ptr>());
		a->setEscapeUnicode(escapeUnicode);
		a->stringify(out, indent == 0 ? 0 : indent, step);
	}
	else if (any.isEmpty())
	{
		out << "null";
	}
	else if (any.isNumeric() || any.isBoolean())
	{
		std::string value = any.convert<std::string>();
		if (any.type() == typeid(char)) formatString(value, out, options);
		else out << value;
	}
	else if (any.isString() || any.isDateTime() || any.isDate() || any.isTime())
	{
		std::string value = any.convert<std::string>();
		formatString(value, out, options);
	}
	else
	{
		out << any.convert<std::string>();
	}
}
Exemplo n.º 22
0
std::string FileNameOptionManager::completeDefaultFileName(
        const std::string &prefix, const FileNameOptionInfo &option)
{
    if (option.isDirectoryOption())
    {
        return std::string();
    }
    const bool        bInput = option.isInputFile() || option.isInputOutputFile();
    const std::string realPrefix
        = !impl_->defaultFileName_.empty() ? impl_->defaultFileName_ : prefix;
    if (bInput && !impl_->bInputCheckingDisabled_)
    {
        const std::string completedName
            = findExistingExtension(realPrefix, option, impl_->redirector_);
        if (!completedName.empty())
        {
            return completedName;
        }
        if (option.allowMissing())
        {
            return realPrefix + option.defaultExtension();
        }
        else if (option.isLibraryFile())
        {
            // TODO: Treat also library files here.
            return realPrefix + option.defaultExtension();
        }
        else if (option.isSet())
        {
            std::string message
                = formatString("No file name was provided, and the default file "
                               "'%s' does not exist or is not accessible.\n"
                               "The following extensions were tried to complete the file name:\n  %s",
                               prefix.c_str(), joinStrings(option.extensions(), ", ").c_str());
            GMX_THROW(InvalidInputError(message));
        }
        else if (option.isRequired())
        {
            std::string message
                = formatString("Required option was not provided, and the default file "
                               "'%s' does not exist or is not accessible.\n"
                               "The following extensions were tried to complete the file name:\n  %s",
                               prefix.c_str(), joinStrings(option.extensions(), ", ").c_str());
            GMX_THROW(InvalidInputError(message));
        }
        // We get here with the legacy optional behavior.
    }
    return realPrefix + option.defaultExtension();
}
Exemplo n.º 23
0
void CDirectiveArea::writeTempData(TempData& tempData) const
{
	tempData.writeLine(position,formatString(L".area 0x%08X",areaSize));
	content->applyFileInfo();
	content->writeTempData(tempData);

	if (fillExpression.isLoaded())
	{
		std::wstring fillString = formatString(L".fill 0x%08X,0x%02X",areaSize-contentSize,fillValue);
		tempData.writeLine(position+contentSize,fillString);
		tempData.writeLine(position+areaSize,L".endarea");
	} else {
		tempData.writeLine(position+contentSize,L".endarea");
	}
}
Exemplo n.º 24
0
/*! \brief Get the path to the main folder storing OpenCL kernels.
 *
 * By default, this function constructs the full path to the OpenCL from
 * the known location of the binary that is running, so that we handle
 * both in-source and installed builds. The user can override this
 * behavior by defining GMX_OCL_FILE_PATH environment variable.
 *
 * \return OS-normalized path string to the main folder storing OpenCL kernels
 *
 * \throws std::bad_alloc    if out of memory.
 *         FileIOError  if GMX_OCL_FILE_PATH does not specify a readable path
 */
static std::string
getKernelRootPath()
{
    std::string kernelRootPath;
    /* Use GMX_OCL_FILE_PATH if the user has defined it */
    const char *gmxOclFilePath = getenv("GMX_OCL_FILE_PATH");

    if (gmxOclFilePath == nullptr)
    {
        /* Normal way of getting ocl_root_dir. First get the right
           root path from the path to the binary that is running. */
        InstallationPrefixInfo      info           = getProgramContext().installationPrefix();
        std::string                 dataPathSuffix = (info.bSourceLayout ?
                                                      "src/gromacs/mdlib/nbnxn_ocl" :
                                                      OCL_INSTALL_DIR);
        kernelRootPath = Path::join(info.path, dataPathSuffix);
    }
    else
    {
        if (!Directory::exists(gmxOclFilePath))
        {
            GMX_THROW(FileIOError(formatString("GMX_OCL_FILE_PATH must point to the directory where OpenCL"
                                               "kernels are found, but '%s' does not exist", gmxOclFilePath)));
        }
        kernelRootPath = gmxOclFilePath;
    }

    // Make sure we return an OS-correct path format
    return Path::normalize(kernelRootPath);
}
Exemplo n.º 25
0
	SerializedMesh(const Properties &props) : TriMesh(props) {
		fs::path filePath = Thread::getThread()->getFileResolver()->resolve(
			props.getString("filename"));

		/* Object-space -> World-space transformation */
		Transform objectToWorld = props.getTransform("toWorld", Transform());

		/// When the file contains multiple meshes, this index specifies which one to load
		int shapeIndex = props.getInteger("shapeIndex", 0);

		m_name = (props.getID() != "unnamed") ? props.getID()
			: formatString("%s@%i", filePath.stem().string().c_str(), shapeIndex);

		/* Load the geometry */
		Log(EInfo, "Loading shape %i from \"%s\" ..", shapeIndex, filePath.filename().string().c_str());
		ref<FileStream> stream = new FileStream(filePath, FileStream::EReadOnly);
		ref<Timer> timer = new Timer();
		loadCompressed(stream, shapeIndex);
		Log(EDebug, "Done (" SIZE_T_FMT " triangles, " SIZE_T_FMT " vertices, %i ms)",
			m_triangleCount, m_vertexCount, timer->getMilliseconds());

		/* By default, any existing normals will be used for
		   rendering. If no normals are found, Mitsuba will
		   automatically generate smooth vertex normals.
		   Setting the 'faceNormals' parameter instead forces
		   the use of face normals, which will result in a faceted
		   appearance.
		*/
		m_faceNormals = props.getBoolean("faceNormals", false);

		/* Causes all normals to be flipped */
		m_flipNormals = props.getBoolean("flipNormals", false);

		if (!objectToWorld.isIdentity()) {
			m_aabb.reset();
			for (size_t i=0; i<m_vertexCount; ++i) {
				Point p = objectToWorld(m_positions[i]);
				m_positions[i] = p;
				m_aabb.expandBy(p);
			}
			if (m_normals) {
				for (size_t i=0; i<m_vertexCount; ++i)
					m_normals[i] = objectToWorld(m_normals[i]);
			}
		}

		if (objectToWorld.det3x3() < 0) {
			for (size_t i=0; i<m_triangleCount; ++i) {
				Triangle &t = m_triangles[i];
				std::swap(t.idx[0], t.idx[1]);
			}
		}

		if (props.hasProperty("maxSmoothAngle")) {
			if (m_faceNormals)
				Log(EError, "The properties 'maxSmoothAngle' and 'faceNormals' "
				"can't be specified at the same time!");
			rebuildTopology(props.getFloat("maxSmoothAngle"));
		}
	}
Exemplo n.º 26
0
Checksum Scenario::load(const string &path) {
    Checksum scenarioChecksum;
	try {
		scenarioChecksum.addFile(path);
		checksumValue.addFile(path);

		string name= cutLastExt(lastDir(path));
		Logger::getInstance().add("Scenario: " + formatString(name), true);

		//parse xml
		XmlTree xmlTree;
		xmlTree.load(path);
		const XmlNode *scenarioNode= xmlTree.getRootNode();
		const XmlNode *scriptsNode= scenarioNode->getChild("scripts");

		for(int i= 0; i<scriptsNode->getChildCount(); ++i){
			const XmlNode *scriptNode = scriptsNode->getChild(i);

			scripts.push_back(Script(getFunctionName(scriptNode), scriptNode->getText()));
		}
	}
	//Exception handling (conversions and so on);
	catch(const exception &e) {
		SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,e.what());
		throw runtime_error("Error: " + path + "\n" + e.what());
	}

	return scenarioChecksum;
}
Exemplo n.º 27
0
void ProgXrayImport::getDarkfield(const FileName &fnDir, Image<double> &IavgDark)
{
    IavgDark.clear();
    std::vector<FileName> listDir;
    fnDir.getFiles(listDir);

    for (size_t i=0; i<listDir.size(); i++)
        if (listDir[i]=="darkfields")
        {
            std::cout << formatString("Getting darkfield from %s/darkfields",fnDir.c_str()) << " ..." << std::endl;

            darkFix = true;
            std::vector<FileName> listDirDark;
            FileName(fnDir+"/darkfields").getFiles(listDirDark);
            int N = 0;

            for (size_t j=0; j<listDirDark.size(); j++)
            {
                if (!listDirDark[j].hasImageExtension())
                    continue;
                Image<double> Iaux;
                readAndCrop(fnDir+"/darkfields/"+listDirDark[j],Iaux, cropSizeX, cropSizeY);
                if (N==0)
                    IavgDark()=Iaux();
                else
                    IavgDark()+=Iaux();
                N++;
            }
            if (N==0)
                REPORT_ERROR(ERR_IO_NOTEXIST,"darkfields directory is empty");
            IavgDark()*=1.0/N;
            break;
        }
}
Exemplo n.º 28
0
/*! \brief Builds a string with build options for the OpenCL kernels
 *
 * \throws std::bad_alloc  if out of memory. */
static std::string
makePreprocessorOptions(const std::string   &kernelRootPath,
                        const std::string   &includeRootPath,
                        size_t               warpSize,
                        ocl_vendor_id_t      deviceVendorId,
                        const std::string   &extraDefines)
{
    std::string preprocessorOptions;

    /* Compose the complete build options */
    preprocessorOptions  = formatString("-DWARP_SIZE_TEST=%d", static_cast<int>(warpSize));
    preprocessorOptions += ' ';
    preprocessorOptions += makeVendorFlavorChoice(deviceVendorId);
    preprocessorOptions += ' ';
    preprocessorOptions += extraDefines;
    preprocessorOptions += ' ';
    preprocessorOptions += selectCompilerOptions(deviceVendorId);
    preprocessorOptions += ' ';
    preprocessorOptions += makeKernelIncludePathOption(kernelRootPath);
    preprocessorOptions += ' ';
    preprocessorOptions += makeKernelIncludePathOption(includeRootPath);

    // Mac OS (and maybe some other implementations) does not accept double spaces in options
    removeExtraSpaces(&preprocessorOptions);

    return preprocessorOptions;
}
Exemplo n.º 29
0
void renderScene() {
    FrameTimeCounter counter;
    int avgFps = 0;
    int iterations = 0;
    while (!complete) {
        counter.BeginCounting();

        physicsWorld->Simulate(1.0f / 10.0f);

        contextPtr->BeginScene();
        contextPtr->ApplyCamera(*cameraPtr);
        //contextPtr->RenderLine(vec2(0.0f, 0.0f), vec2(100.0f, 100.0f));
        for (int i = 0; i < physicsBodies.size(); ++i) {
            physicsBodies[i].DebugRender(debugRenderer);
        }

        for (int i = 0; i < physicsJoints.size(); ++i) {
            physicsJoints[i].DebugRender(debugRenderer);
        }

        contextPtr->EndScene();



        counter.EndCounting();

        avgFps += counter.GetFps();
        iterations++;
        if (iterations > 10) {
            SetWindowTextA(hWnd, formatString("fps: %d", avgFps / iterations).c_str());
            iterations = 0;
            avgFps = 0;
        }
    }
}
Exemplo n.º 30
0
/* EncodeElement is called by cat(), write.table() and deparsing. */
const char *EncodeElement(SEXP x, int indx, int quote, char dec)
{
    int w, d, e, wi, di, ei;
    const char *res;

    switch(TYPEOF(x)) {
    case LGLSXP:
	formatLogical(&LOGICAL(x)[indx], 1, &w);
	res = EncodeLogical(LOGICAL(x)[indx], w);
	break;
    case INTSXP:
	formatInteger(&INTEGER(x)[indx], 1, &w);
	res = EncodeInteger(INTEGER(x)[indx], w);
	break;
    case REALSXP:
	formatReal(&REAL(x)[indx], 1, &w, &d, &e, 0);
	res = EncodeReal(REAL(x)[indx], w, d, e, dec);
	break;
    case STRSXP:
	formatString(&STRING_PTR(x)[indx], 1, &w, quote);
	res = EncodeString(STRING_ELT(x, indx), w, quote, Rprt_adj_left);
	break;
    case CPLXSXP:
	formatComplex(&COMPLEX(x)[indx], 1, &w, &d, &e, &wi, &di, &ei, 0);
	res = EncodeComplex(COMPLEX(x)[indx], w, d, e, wi, di, ei, dec);
	break;
    case RAWSXP:
	res = EncodeRaw(RAW(x)[indx]);
	break;
    default:
	res = NULL; /* -Wall */
	UNIMPLEMENTED_TYPE("EncodeElement", x);
    }
    return res;
}