<commit_before>/**
 * Clever programming language
 * Copyright (c) 2011-2012 Clever Team
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#include <fstream>
#include <setjmp.h>
#include "compiler/cstring.h"
#include "interpreter/driver.h"
#include "interpreter/parser.hh"
#include "interpreter/position.hh"
#include "scanner.h"

namespace clever {

/**
 * Interpreter constructor
 */
Interpreter::Interpreter(int* argc, char*** argv)
{
}

/**
 * Executes the script
 */
void Interpreter::execute(bool interactive)
{
	/*
	if (interactive) {
		m_compiler.setInteractive();
	}

	int result = setjmp(Compiler::failure);

	if (result == 0) {
		m_compiler.buildIR();
	} else {
		m_compiler.shutdown();
	}

	VM::setOpcodes(&m_compiler.getOpcodes());

	result = setjmp(clever::fatal_error);

	if (result == 0) {
		VM::run();
	}
	VM::shutdown();*/
}

#ifdef CLEVER_DEBUG
void Interpreter::execute(bool interactive, bool dump_opcode)
{
	execute(interactive);
}
#endif

/**
 * Read the file defined in file property
 */
void Driver::readFile(std::string& source) const
{
	std::string line;
	std::fstream filep(m_file->c_str());

	if (!filep) {
		std::cerr << "Couldn't open file " << m_file->str() << std::endl;
		exit(1);
	}
	source = "";

	while (!filep.eof()) {
		getline(filep, line);
		source += line;
		source += '\n';
	}

	filep.clear();
	filep.close();
}

/**
 * Parses a file
 */
int Driver::parseFile(const std::string& filename)
{
	ScannerState* new_scanner = new ScannerState;
	Parser parser(*this, *new_scanner);
	std::string& source = new_scanner->getSource();

	m_is_file = true;
	m_file = CSTRING(filename);

	readFile(source);

	m_scanners.push(new_scanner);

	const unsigned char* s = reinterpret_cast<const unsigned char*>(source.c_str());

	m_scanners.top()->set_cursor(s);
	m_scanners.top()->set_limit(s + source.length());

	// Bison debug option
	parser.set_debug_level(m_trace_parsing);

	int result = parser.parse();

	delete new_scanner;
	m_scanners.pop();

	return result;
}

/**
 * Parses a string
 */
int Driver::parseStr(const std::string& code, bool importStd)
{
	ScannerState *new_scanner = new ScannerState;
	Parser parser(*this, *new_scanner);
	std::string& source = new_scanner->getSource();

	if (importStd) {
		source += std::string("import std.*;");
	}
	source += code;

	/* Set the source code to scanner read it */
	m_scanners.push(new_scanner);

	const unsigned char* s = reinterpret_cast<const unsigned char*>(source.c_str());
	m_scanners.top()->set_cursor(s);
	m_scanners.top()->set_limit(s + source.length());

	/* Bison debug option */
	parser.set_debug_level(m_trace_parsing);

	int result = parser.parse();

	delete new_scanner;
	m_scanners.pop();

	return result;
}

/**
 * Prints an error message and exit
 */
void Driver::error(const clever::location& location, const std::string& message) const
{
	position last = location.end - 1;

	if (last.filename) {
		std::cerr << message << " in " << *last.filename << " on line " << last.line << std::endl;
	} else {
		std::cerr << message << " on line " << last.line << std::endl;
	}
	exit(1);
}

/**
 * Prints an error message
 */
void Driver::error(const std::string& message) const
{
	std::cerr << message << std::endl;
}

} // clever
<commit_msg>- Restored if conditional to dumping opcodes<commit_after>/**
 * Clever programming language
 * Copyright (c) 2011-2012 Clever Team
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#include <fstream>
#include <setjmp.h>
#include "compiler/cstring.h"
#include "interpreter/driver.h"
#include "interpreter/parser.hh"
#include "interpreter/position.hh"
#include "scanner.h"

namespace clever {

/**
 * Interpreter constructor
 */
Interpreter::Interpreter(int* argc, char*** argv)
{
}

/**
 * Executes the script
 */
void Interpreter::execute(bool interactive)
{
	/*
	if (interactive) {
		m_compiler.setInteractive();
	}

	int result = setjmp(Compiler::failure);

	if (result == 0) {
		m_compiler.buildIR();
	} else {
		m_compiler.shutdown();
	}

	VM::setOpcodes(&m_compiler.getOpcodes());

	result = setjmp(clever::fatal_error);

	if (result == 0) {
		VM::run();
	}
	VM::shutdown();*/
}

#ifdef CLEVER_DEBUG
void Interpreter::execute(bool interactive, bool dump_opcode)
{
	if (dump_opcode) {
		//m_compiler.setOpcodeDump();
	}
	execute(interactive);
}
#endif

/**
 * Read the file defined in file property
 */
void Driver::readFile(std::string& source) const
{
	std::string line;
	std::fstream filep(m_file->c_str());

	if (!filep) {
		std::cerr << "Couldn't open file " << m_file->str() << std::endl;
		exit(1);
	}
	source = "";

	while (!filep.eof()) {
		getline(filep, line);
		source += line;
		source += '\n';
	}

	filep.clear();
	filep.close();
}

/**
 * Parses a file
 */
int Driver::parseFile(const std::string& filename)
{
	ScannerState* new_scanner = new ScannerState;
	Parser parser(*this, *new_scanner);
	std::string& source = new_scanner->getSource();

	m_is_file = true;
	m_file = CSTRING(filename);

	readFile(source);

	m_scanners.push(new_scanner);

	const unsigned char* s = reinterpret_cast<const unsigned char*>(source.c_str());

	m_scanners.top()->set_cursor(s);
	m_scanners.top()->set_limit(s + source.length());

	// Bison debug option
	parser.set_debug_level(m_trace_parsing);

	int result = parser.parse();

	delete new_scanner;
	m_scanners.pop();

	return result;
}

/**
 * Parses a string
 */
int Driver::parseStr(const std::string& code, bool importStd)
{
	ScannerState *new_scanner = new ScannerState;
	Parser parser(*this, *new_scanner);
	std::string& source = new_scanner->getSource();

	if (importStd) {
		source += std::string("import std.*;");
	}
	source += code;

	/* Set the source code to scanner read it */
	m_scanners.push(new_scanner);

	const unsigned char* s = reinterpret_cast<const unsigned char*>(source.c_str());
	m_scanners.top()->set_cursor(s);
	m_scanners.top()->set_limit(s + source.length());

	/* Bison debug option */
	parser.set_debug_level(m_trace_parsing);

	int result = parser.parse();

	delete new_scanner;
	m_scanners.pop();

	return result;
}

/**
 * Prints an error message and exit
 */
void Driver::error(const clever::location& location, const std::string& message) const
{
	position last = location.end - 1;

	if (last.filename) {
		std::cerr << message << " in " << *last.filename << " on line " << last.line << std::endl;
	} else {
		std::cerr << message << " on line " << last.line << std::endl;
	}
	exit(1);
}

/**
 * Prints an error message
 */
void Driver::error(const std::string& message) const
{
	std::cerr << message << std::endl;
}

} // clever
<|endoftext|>


<commit_before>#include <iostream>
#include <libdebug/Debugger.h>
#include <string>

using namespace std;
using namespace lldb;

int main(int argc, char** argv)
{
    if (argc < 1) {
        cerr << "Usage: ./%s binary_file" << endl;
        return -1;
    }

    string binary_file{ argv[1] };

    Debugger debugger{};
    debugger.disable_aslr();
    debugger.stop_at_entrypoint();
    debugger.process_execute(binary_file);

#if defined(DEBUG_LLDB)
// Enable lldb's internal debug log channel.
debugger.enable_debug_log("lldb", { "api", "break", "module", "platform", "process" });
#endif

    auto regions = debugger.memory_regions();
    if (!regions) {
        printf("Could not get memory regions\n");
        return -1;
    }

    for (auto i = 0; i < regions->GetSize(); i++) {
        SBMemoryRegionInfo info;
        if (!regions->GetMemoryRegionAtIndex(i, info))
            continue;

        printf("Name: %s mapped=%3s %c%c%c 0x%p 0x%p\n",
            info.GetName() ? info.GetName() : "no-name",
            info.IsMapped() ? "yes" : "no",
            info.IsReadable() ? 'R' : '-',
            info.IsWritable() ? 'W' : '-',
            info.IsExecutable() ? 'X' : '-',
            (void*)info.GetRegionBase(),
            (void*)info.GetRegionEnd());
    }

    printf("Dumping instructions from PC=0x%.16llx\n", *debugger.get_pc());

    auto target = debugger.get_target();
    for (auto i = 0; i < 128; i++) {
        auto ins = *debugger.instruction_get();
        std::string comment = ins.GetComment(target);
        if (!comment.empty()) {
            comment = "; " + comment;
        }

        printf("0x%.16llx: %-8s %-40s %s\n",
            ins.GetAddress().GetLoadAddress(target),
            ins.GetMnemonic(target),
            ins.GetOperands(target),
            comment.c_str());

        if (ins.DoesBranch()) {
            puts("----------------------------------------------------------------------");
        }

        debugger.step_instruction();
    }

    std::string library_path = "/usr/local/lib/libunicorn.dylib";
    if (!debugger.library_load(library_path)) {
        printf("Could not load library\n");
        return -1;
    }

    printf("Loaded library\n");

    if (!debugger.library_unload(library_path)) {
        printf("Could not unload library\n");
        return -1;
    }

    printf("Unloaded library\n");

    debugger.registers_set({
        { "rax", "0x44444444" },
        { "rbx", "0x88888888" }
    });

    if (auto reg_value = debugger.register_get("rax")) {
        printf("Register value: name=%s value=%s\n", reg_value->GetName(), reg_value->GetValue());
    }

    if (auto reg_value = debugger.register_get("rbx")) {
        printf("Register value: name=%s value=%s\n", reg_value->GetName(), reg_value->GetValue());
    }

    return 0;
}
<commit_msg>Adds test code to play with expressions<commit_after>#include <iostream>
#include <libdebug/Debugger.h>
#include <string>

using namespace std;
using namespace lldb;

int main(int argc, char** argv)
{
    if (argc < 1) {
        cerr << "Usage: ./%s binary_file" << endl;
        return -1;
    }

    string binary_file{ argv[1] };

    Debugger debugger{};
    debugger.disable_aslr();
    debugger.stop_at_entrypoint();
    debugger.process_execute(binary_file);

#if defined(DEBUG_LLDB)
// Enable lldb's internal debug log channel.
debugger.enable_debug_log("lldb", { "api", "break", "module", "platform", "process" });
#endif

    auto regions = debugger.memory_regions();
    if (!regions) {
        printf("Could not get memory regions\n");
        return -1;
    }

    for (auto i = 0; i < regions->GetSize(); i++) {
        SBMemoryRegionInfo info;
        if (!regions->GetMemoryRegionAtIndex(i, info))
            continue;

        printf("Name: %s mapped=%3s %c%c%c 0x%p 0x%p\n",
            info.GetName() ? info.GetName() : "no-name",
            info.IsMapped() ? "yes" : "no",
            info.IsReadable() ? 'R' : '-',
            info.IsWritable() ? 'W' : '-',
            info.IsExecutable() ? 'X' : '-',
            (void*)info.GetRegionBase(),
            (void*)info.GetRegionEnd());
    }

    printf("Dumping instructions from PC=0x%.16llx\n", *debugger.get_pc());

    auto target = debugger.get_target();
    for (auto i = 0; i < 128; i++) {
        auto ins = *debugger.instruction_get();
        std::string comment = ins.GetComment(target);
        if (!comment.empty()) {
            comment = "; " + comment;
        }

        printf("0x%.16llx: %-8s %-40s %s\n",
            ins.GetAddress().GetLoadAddress(target),
            ins.GetMnemonic(target),
            ins.GetOperands(target),
            comment.c_str());

        if (ins.DoesBranch()) {
            puts("----------------------------------------------------------------------");
        }

        debugger.step_instruction();
    }

    std::string memory_map = "(void *) mmap(nullptr, 4096, 0x1, 0x1000 | 0x0001, 0, 0)";
    if (auto memory = debugger.evaluate_expression<void*>(memory_map)) {
        printf("Mapped memory at %p\n", *memory);
    }

    auto ret = debugger.evaluate_expression<unsigned>("(unsigned) 1+1");
    if (ret) {
        printf("Test: %u\n", *ret);
    }

    ret = debugger.evaluate_expression<unsigned>("(unsigned) getpid()");
    if (ret) {
        printf("Test: %u\n", *ret);
    }

    std::string library_path = "/usr/local/lib/libunicorn.dylib";
    if (!debugger.library_load(library_path)) {
        printf("Could not load library\n");
        return -1;
    }

    printf("Loaded library\n");

    if (!debugger.library_unload(library_path)) {
        printf("Could not unload library\n");
        return -1;
    }

    printf("Unloaded library\n");

    debugger.registers_set({
        { "rax", "0x44444444" },
        { "rbx", "0x88888888" }
    });

    if (auto reg_value = debugger.register_get("rax")) {
        printf("Register value: name=%s value=%s\n", reg_value->GetName(), reg_value->GetValue());
    }

    if (auto reg_value = debugger.register_get("rbx")) {
        printf("Register value: name=%s value=%s\n", reg_value->GetName(), reg_value->GetValue());
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <string>
#include <errno.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#ifdef DARWIN
# include <sys/param.h>
# include <sys/sysctl.h>
#endif
#include <sys/time.h>
#include <sys/stat.h>
#include <limits.h>
#include <sstream>
#include <stdlib.h>
#include <libgen.h>
#ifdef LINUX
# include <sched.h>
# ifdef HAS_LIBNUMA
#  include <numaif.h>
# endif
#endif

#include "tools.h"
#include "failure.h"
#include "log.h"

using std::string;

/* purpose: formats ISO 8601 timestamp into given buffer (simplified)
 * paramtr: seconds (IN): time stamp
 *          buffer (OUT): where to put the results
 *          size (IN): capacity of buffer
 * returns: pointer to start of buffer for convenience.
 */
char * isodate( time_t seconds, char* buffer, size_t size ) {
    struct tm zulu = *gmtime(&seconds);
    struct tm local = *localtime(&seconds);
    zulu.tm_isdst = local.tm_isdst;
    {
        time_t distance = (seconds - mktime(&zulu)) / 60;
        int hours = distance / 60;
        int minutes = distance < 0 ? -distance % 60 : distance % 60;
        size_t len = strftime( buffer, size, "%Y-%m-%dT%H:%M:%S", &local );
        snprintf( buffer+len, size-len, "%+03d:%02d", hours, minutes );
    }
    return buffer;
}

/* purpose: formats ISO 8601 timestamp into given buffer (simplified)
 * paramtr: seconds_wf (IN): time stamp with fractional seconds (millis)
 *          buffer (OUT): where to put the results
 *          size (IN): capacity of buffer
 * returns: pointer to start of buffer for convenience.
 */
char * iso2date( double seconds_wf, char* buffer, size_t size ) {
    char millis[8];
    double integral, fractional = modf(seconds_wf,&integral);
    time_t seconds = (time_t) integral;
    struct tm zulu = *gmtime(&seconds);
    struct tm local = *localtime(&seconds);
    zulu.tm_isdst = local.tm_isdst;
    snprintf( millis, sizeof(millis), "%.3f", fractional );
    {
        time_t distance = (seconds - mktime(&zulu)) / 60;
        int hours = distance / 60;
        int minutes = distance < 0 ? -distance % 60 : distance % 60;
        size_t len = strftime( buffer, size, "%Y-%m-%dT%H:%M:%S", &local );
        snprintf( buffer+len, size-len, "%s%+03d:%02d", millis+1, hours, minutes );
    }
    return buffer;
}

/* Get the local host name */
void get_host_name(std::string &hostname) {
    char name[HOST_NAME_MAX];
    if (gethostname(name, HOST_NAME_MAX) < 0) {
        myfailures("Unable to get host name");
    }
    hostname = name;
}

/* Get the current time as the number of seconds since the epoch */
double current_time() {
    struct timeval now;
    gettimeofday(&now, NULL);
    double ts = now.tv_sec + (now.tv_usec/1000000.0);
    return ts;
}

/* Get the total amount of physical memory in bytes */
unsigned long get_host_memory() {
    unsigned long memory;
#ifdef DARWIN
    size_t size = sizeof(memory);
    if (sysctlbyname("hw.memsize", &memory, &size, NULL, 0) < 0) {
        myfailures("Unable to get host physical memory size");
    }
#else
    long pages = sysconf(_SC_PHYS_PAGES);
    if (pages < 0) {
        myfailures("Unable to get number of host physical memory pages");
    }
    long pagesize = sysconf(_SC_PAGE_SIZE);
    if (pagesize < 0) {
        myfailures("Unable to get physical page size");
    }
    memory = pages * pagesize;
#endif
    if (memory == 0) {
        myfailure("Invalid memory size: %lu bytes", memory);
    }
    return memory;
}

struct cpuinfo get_host_cpuinfo() {
    struct cpuinfo c;
    c.cpus = 0;
    c.cores = 0;
    c.sockets = 0;
#ifdef __MACH__
    size_t size = sizeof(unsigned int);
    if (sysctlbyname("hw.logicalcpu", &c.cpus, &size, NULL, 0) < 0) {
        myfailures("Unable to get number of CPUs (logical CPUs)");
    }
    if (sysctlbyname("hw.physicalcpu", &c.cores, &size, NULL, 0) < 0) {
        myfailures("Unable to get number of cores (physical CPUs)");
    }
    if (sysctlbyname("hw.packages", &c.sockets, &size, NULL, 0) < 0) {
        myfailures("Unable to get number of CPU sockets");
    }
#else
    // FIXME We need to read this from /proc/cpuinfo on LINUX
    c.cpus = 4;
    c.cores = 2;
    c.sockets = 1;
#endif
    if (c.cpus == 0 || c.cores == 0 || c.sockets == 0) {
        myfailure("Invalid cpuinfo: %u %u %u", c.cpus, c.cores, c.sockets);
    }
    return c;
}

int mkdirs(const char *path) {
    if (path == NULL || strlen(path) == 0) {
        return 0;
    }

    // No need to create cwd
    if (path[0] == '.' && path[1] == '\0') {
        return 0;
    }

    if (strlen(path) > PATH_MAX) {
        errno = ENAMETOOLONG;
        return -1;
    }

    char mypath[PATH_MAX];
    char *p = mypath;

    if (path[0] == '.' && path[1] == '.') {
        if (getcwd(mypath, PATH_MAX) == NULL) {
            return -1;
        }

        char *parent = strrchr(mypath, '/');
        if (parent) *parent = '\0';

        int off = strlen(mypath);
        strcpy(mypath+off, path+2);

        // In this case we don't need to go back to the root
        p = mypath + off;
    } else if (path[0] == '.' && path[1] == '/') {
        strcpy(mypath, path+2);
    } else {
        strcpy(mypath, path);
    }

    while (*p == '/') p++;

    int created = 0;
    struct stat st;
    while ((p = strchr(p, '/'))) {
        *p = '\0';

        if (stat(mypath, &st)) {
            if (errno == ENOENT) {
                if (mkdir(mypath, 0777)) {
                    return -1;
                }
                created++;
            } else {
                return -1;
            }
        } else {
            // If it exists, make sure it is a dir
            if (S_ISDIR(st.st_mode) == 0) {
                errno = ENOTDIR;
                return -1;
            }
        }

        *p = '/';
        while (*p == '/') p++;
    }

    // Last element of path
    if (stat(mypath, &st)) {
        if (errno == ENOENT) {
            if (mkdir(mypath, 0777)) {
                return -1;
            }
            created++;
        } else {
            return -1;
        }
    } else {
        if (S_ISDIR(st.st_mode) == 0) {
            errno = ENOTDIR;
            return -1;
        }
    }

    return created;
}

bool is_executable(const string &file) {
    // Invalid path
    if (file.size() == 0) {
        return false;
    }

    struct stat st;
    if (stat(file.c_str(), &st) == 0) {
        if (S_ISREG(st.st_mode)) {
            if ((st.st_uid == geteuid() && (S_IXUSR & st.st_mode) == S_IXUSR) ||
                (st.st_gid == getegid() && (S_IXGRP & st.st_mode) == S_IXGRP) ||
                ((S_IXOTH & st.st_mode) == S_IXOTH)) {
                // It is a regular file and we can execute it
                return true;
            }
        }
    }

    // In all other cases, the file is not executable
    return false;
}

int read_file(const string &file, char *buf, size_t size) {
    // Invalid path
    if (file.size() == 0) {
        errno = ENOENT;
        return -1;
    }

    FILE *f = fopen(file.c_str(), "r");
    if (f == NULL) {
        return -1;
    }

    size_t read = fread(buf, 1, size, f);

    if (fclose(f)) {
        return -1;
    }

    return read;
}

string pathfind(const string &file) {
    if (file.size() == 0) {
        return file;
    }

    // files that have a / should be returned as-is
    if (file.find('/') != string::npos) {
        return file;
    }

    // normally we wouldn't allow this
    if (is_executable(file)) {
        return file;
    }

    string path;
    char *env = getenv("PATH");
    if (env == NULL) {
#ifdef _PATH_DEFPATH
        path = _PATH_DEFPATH;
#else
        return file;
#endif
    } else {
        /* yes, there is a PATH variable */
        path = env;
    }

    string element;
    std::istringstream split(path);
    while(std::getline(split, element, ':')) {
        if (element.size() == 0) {
            continue;
        }
        string myfile = element + "/" + file;
        if (is_executable(myfile)) {
            return myfile;
        }
    }

    return file;
}

/* Return the directory part of a path */
string dirname(const string &path) {
    char *temp = strdup(path.c_str());
    string result = ::dirname(temp);
    free(temp);
    return result;
}

/* Return the last part of a path */
string filename(const string &path) {
    char *temp = strdup(path.c_str());
    string result = ::basename(temp);
    free(temp);
    return result;
}

int clear_cpu_affinity() {
#ifdef LINUX
    struct cpuinfo c = get_host_cpuinfo();
    cpu_set_t *cpuset = CPU_ALLOC(c.cpus);
    if (cpuset == NULL) {
        return -1;
    }
    size_t cpusetsize = CPU_ALLOC_SIZE(c.cpus);
    CPU_ZERO_S(cpusetsize, cpuset);

    for (unsigned i=0; i<c.cpus; i++) {
        CPU_SET_S(i, cpusetsize, cpuset);
    }

    int rc = sched_setaffinity(0, cpusetsize, cpuset);
    CPU_FREE(cpuset);
    if (rc < 0) {
        return -1;
    }
#endif
    return 0;
}

int clear_memory_affinity() {
#ifdef HAS_LIBNUMA
    int rc = set_mempolicy(MPOL_DEFAULT, NULL, 0);
    if (rc < 0) {
        return -1;
    }
#endif
    return 0;
}
<commit_msg>PM-953: Read cpu topology from /proc/cpuinfo on linux<commit_after>#include <string>
#include <fstream>
#include <errno.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#ifdef DARWIN
# include <sys/param.h>
# include <sys/sysctl.h>
#endif
#include <sys/time.h>
#include <sys/stat.h>
#include <limits.h>
#include <sstream>
#include <stdlib.h>
#include <libgen.h>
#ifdef LINUX
# include <sched.h>
# ifdef HAS_LIBNUMA
#  include <numaif.h>
# endif
#endif

#include "tools.h"
#include "failure.h"
#include "log.h"

using std::string;

/* purpose: formats ISO 8601 timestamp into given buffer (simplified)
 * paramtr: seconds (IN): time stamp
 *          buffer (OUT): where to put the results
 *          size (IN): capacity of buffer
 * returns: pointer to start of buffer for convenience.
 */
char * isodate( time_t seconds, char* buffer, size_t size ) {
    struct tm zulu = *gmtime(&seconds);
    struct tm local = *localtime(&seconds);
    zulu.tm_isdst = local.tm_isdst;
    {
        time_t distance = (seconds - mktime(&zulu)) / 60;
        int hours = distance / 60;
        int minutes = distance < 0 ? -distance % 60 : distance % 60;
        size_t len = strftime( buffer, size, "%Y-%m-%dT%H:%M:%S", &local );
        snprintf( buffer+len, size-len, "%+03d:%02d", hours, minutes );
    }
    return buffer;
}

/* purpose: formats ISO 8601 timestamp into given buffer (simplified)
 * paramtr: seconds_wf (IN): time stamp with fractional seconds (millis)
 *          buffer (OUT): where to put the results
 *          size (IN): capacity of buffer
 * returns: pointer to start of buffer for convenience.
 */
char * iso2date( double seconds_wf, char* buffer, size_t size ) {
    char millis[8];
    double integral, fractional = modf(seconds_wf,&integral);
    time_t seconds = (time_t) integral;
    struct tm zulu = *gmtime(&seconds);
    struct tm local = *localtime(&seconds);
    zulu.tm_isdst = local.tm_isdst;
    snprintf( millis, sizeof(millis), "%.3f", fractional );
    {
        time_t distance = (seconds - mktime(&zulu)) / 60;
        int hours = distance / 60;
        int minutes = distance < 0 ? -distance % 60 : distance % 60;
        size_t len = strftime( buffer, size, "%Y-%m-%dT%H:%M:%S", &local );
        snprintf( buffer+len, size-len, "%s%+03d:%02d", millis+1, hours, minutes );
    }
    return buffer;
}

/* Get the local host name */
void get_host_name(std::string &hostname) {
    char name[HOST_NAME_MAX];
    if (gethostname(name, HOST_NAME_MAX) < 0) {
        myfailures("Unable to get host name");
    }
    hostname = name;
}

/* Get the current time as the number of seconds since the epoch */
double current_time() {
    struct timeval now;
    gettimeofday(&now, NULL);
    double ts = now.tv_sec + (now.tv_usec/1000000.0);
    return ts;
}

/* Get the total amount of physical memory in bytes */
unsigned long get_host_memory() {
    unsigned long memory;
#ifdef DARWIN
    size_t size = sizeof(memory);
    if (sysctlbyname("hw.memsize", &memory, &size, NULL, 0) < 0) {
        myfailures("Unable to get host physical memory size");
    }
#else
    long pages = sysconf(_SC_PHYS_PAGES);
    if (pages < 0) {
        myfailures("Unable to get number of host physical memory pages");
    }
    long pagesize = sysconf(_SC_PAGE_SIZE);
    if (pagesize < 0) {
        myfailures("Unable to get physical page size");
    }
    memory = pages * pagesize;
#endif
    if (memory == 0) {
        myfailure("Invalid memory size: %lu bytes", memory);
    }
    return memory;
}

struct cpuinfo get_host_cpuinfo() {
    struct cpuinfo c;
    c.cpus = 0;
    c.cores = 0;
    c.sockets = 0;
#ifdef __MACH__
    size_t size = sizeof(unsigned int);
    if (sysctlbyname("hw.logicalcpu", &c.cpus, &size, NULL, 0) < 0) {
        myfailures("Unable to get number of CPUs (logical CPUs)");
    }
    if (sysctlbyname("hw.physicalcpu", &c.cores, &size, NULL, 0) < 0) {
        myfailures("Unable to get number of cores (physical CPUs)");
    }
    if (sysctlbyname("hw.packages", &c.sockets, &size, NULL, 0) < 0) {
        myfailures("Unable to get number of CPU sockets");
    }
#else
    std::ifstream infile;
    infile.open("/proc/cpuinfo");
    if (!infile.good()) {
        myfailures("Error opening /proc/cpuinfo");
    }

    int last_physical_id = -1;
    int new_socket = 0;
    string rec;
    while (getline(infile, rec)) {
        if (rec.find("processor\t:", 0, 11) == 0) {
            // Each time we encounter a processor field, we increment the
            // number of cpus/threads
            c.cpus += 1;
        } else if (rec.find("physical id\t:", 0, 13) == 0) {
            // Each time we encounter a new physical id, we increment the
            // number of sockets
            int new_physical_id;
            if (sscanf(rec.c_str(), "physical id\t: %u", &new_physical_id) != 1) {
                myfailures("Error reading 'physical id' field from /proc/cpuinfo");
            }
            if (new_physical_id != last_physical_id) {
                c.sockets += 1;
                last_physical_id = new_physical_id;
                new_socket = 1;
            }
        } else if (rec.find("cpu cores\t:", 0, 11) == 0) {
            // Each time we encounter a new socket, we count the number of
            // cores it has
            if (new_socket) {
                unsigned int cores;
                if (sscanf(rec.c_str(), "cpu cores\t: %u", &cores) != 1) {
                    myfailures("Error reading 'cpu cores' field from /proc/cpuinfo");
                }
                c.cores += cores;
                new_socket = 0;
            }
        }
    }

    if (infile.bad() || !infile.eof()) {
        myfailures("Error reading /proc/cpuinfo");
    }

    infile.close();
#endif
    if (c.cpus == 0 || c.cores == 0 || c.sockets == 0 || c.cores > c.cpus || c.sockets > c.cores) {
        myfailure("Invalid cpuinfo: %u %u %u", c.cpus, c.cores, c.sockets);
    }
    return c;
}

int mkdirs(const char *path) {
    if (path == NULL || strlen(path) == 0) {
        return 0;
    }

    // No need to create cwd
    if (path[0] == '.' && path[1] == '\0') {
        return 0;
    }

    if (strlen(path) > PATH_MAX) {
        errno = ENAMETOOLONG;
        return -1;
    }

    char mypath[PATH_MAX];
    char *p = mypath;

    if (path[0] == '.' && path[1] == '.') {
        if (getcwd(mypath, PATH_MAX) == NULL) {
            return -1;
        }

        char *parent = strrchr(mypath, '/');
        if (parent) *parent = '\0';

        int off = strlen(mypath);
        strcpy(mypath+off, path+2);

        // In this case we don't need to go back to the root
        p = mypath + off;
    } else if (path[0] == '.' && path[1] == '/') {
        strcpy(mypath, path+2);
    } else {
        strcpy(mypath, path);
    }

    while (*p == '/') p++;

    int created = 0;
    struct stat st;
    while ((p = strchr(p, '/'))) {
        *p = '\0';

        if (stat(mypath, &st)) {
            if (errno == ENOENT) {
                if (mkdir(mypath, 0777)) {
                    return -1;
                }
                created++;
            } else {
                return -1;
            }
        } else {
            // If it exists, make sure it is a dir
            if (S_ISDIR(st.st_mode) == 0) {
                errno = ENOTDIR;
                return -1;
            }
        }

        *p = '/';
        while (*p == '/') p++;
    }

    // Last element of path
    if (stat(mypath, &st)) {
        if (errno == ENOENT) {
            if (mkdir(mypath, 0777)) {
                return -1;
            }
            created++;
        } else {
            return -1;
        }
    } else {
        if (S_ISDIR(st.st_mode) == 0) {
            errno = ENOTDIR;
            return -1;
        }
    }

    return created;
}

bool is_executable(const string &file) {
    // Invalid path
    if (file.size() == 0) {
        return false;
    }

    struct stat st;
    if (stat(file.c_str(), &st) == 0) {
        if (S_ISREG(st.st_mode)) {
            if ((st.st_uid == geteuid() && (S_IXUSR & st.st_mode) == S_IXUSR) ||
                (st.st_gid == getegid() && (S_IXGRP & st.st_mode) == S_IXGRP) ||
                ((S_IXOTH & st.st_mode) == S_IXOTH)) {
                // It is a regular file and we can execute it
                return true;
            }
        }
    }

    // In all other cases, the file is not executable
    return false;
}

int read_file(const string &file, char *buf, size_t size) {
    // Invalid path
    if (file.size() == 0) {
        errno = ENOENT;
        return -1;
    }

    FILE *f = fopen(file.c_str(), "r");
    if (f == NULL) {
        return -1;
    }

    size_t read = fread(buf, 1, size, f);

    if (fclose(f)) {
        return -1;
    }

    return read;
}

string pathfind(const string &file) {
    if (file.size() == 0) {
        return file;
    }

    // files that have a / should be returned as-is
    if (file.find('/') != string::npos) {
        return file;
    }

    // normally we wouldn't allow this
    if (is_executable(file)) {
        return file;
    }

    string path;
    char *env = getenv("PATH");
    if (env == NULL) {
#ifdef _PATH_DEFPATH
        path = _PATH_DEFPATH;
#else
        return file;
#endif
    } else {
        /* yes, there is a PATH variable */
        path = env;
    }

    string element;
    std::istringstream split(path);
    while(std::getline(split, element, ':')) {
        if (element.size() == 0) {
            continue;
        }
        string myfile = element + "/" + file;
        if (is_executable(myfile)) {
            return myfile;
        }
    }

    return file;
}

/* Return the directory part of a path */
string dirname(const string &path) {
    char *temp = strdup(path.c_str());
    string result = ::dirname(temp);
    free(temp);
    return result;
}

/* Return the last part of a path */
string filename(const string &path) {
    char *temp = strdup(path.c_str());
    string result = ::basename(temp);
    free(temp);
    return result;
}

int clear_cpu_affinity() {
#ifdef LINUX
    struct cpuinfo c = get_host_cpuinfo();
    cpu_set_t *cpuset = CPU_ALLOC(c.cpus);
    if (cpuset == NULL) {
        return -1;
    }
    size_t cpusetsize = CPU_ALLOC_SIZE(c.cpus);
    CPU_ZERO_S(cpusetsize, cpuset);

    for (unsigned i=0; i<c.cpus; i++) {
        CPU_SET_S(i, cpusetsize, cpuset);
    }

    int rc = sched_setaffinity(0, cpusetsize, cpuset);
    CPU_FREE(cpuset);
    if (rc < 0) {
        return -1;
    }
#endif
    return 0;
}

int clear_memory_affinity() {
#ifdef HAS_LIBNUMA
    int rc = set_mempolicy(MPOL_DEFAULT, NULL, 0);
    if (rc < 0) {
        return -1;
    }
#endif
    return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "src/trace_processor/types/task_state.h"

#include <stdint.h>
#include <algorithm>

#include "perfetto/base/logging.h"
#include "perfetto/ext/base/string_writer.h"

namespace perfetto {
namespace trace_processor {
namespace ftrace_utils {

TaskState::TaskState(uint16_t raw_state) {
  if (raw_state > kMaxState) {
    state_ = 0;
  } else {
    state_ = raw_state | kValid;
  }
}

TaskState::TaskState(const char* state_str) {
  bool invalid_char = false;
  bool is_runnable = false;
  for (size_t i = 0; state_str[i] != '\0'; i++) {
    char c = state_str[i];
    if (is_kernel_preempt()) {
      // No other character should be encountered after '+'.
      invalid_char = true;
      break;
    } else if (c == '+') {
      state_ |= kMaxState;
      continue;
    }

    if (is_runnable) {
      // We should not encounter any character apart from '+' if runnable.
      invalid_char = true;
      break;
    }

    if (c == 'R') {
      if (state_ != 0) {
        // We should not encounter R if we already have set other atoms.
        invalid_char = true;
        break;
      } else {
        is_runnable = true;
        continue;
      }
    }

    if (c == 'S')
      state_ |= Atom::kInterruptibleSleep;
    else if (c == 'D')
      state_ |= Atom::kUninterruptibleSleep;
    else if (c == 'T')
      state_ |= Atom::kStopped;
    else if (c == 't')
      state_ |= Atom::kTraced;
    else if (c == 'X')
      state_ |= Atom::kExitDead;
    else if (c == 'Z')
      state_ |= Atom::kExitZombie;
    else if (c == 'x')
      state_ |= Atom::kTaskDead;
    else if (c == 'K')
      state_ |= Atom::kWakeKill;
    else if (c == 'W')
      state_ |= Atom::kWaking;
    else if (c == 'P')
      state_ |= Atom::kParked;
    else if (c == 'N')
      state_ |= Atom::kNoLoad;
    else if (c == '|')
      continue;
    else {
      invalid_char = true;
      break;
    }
  }

  bool no_state = !is_runnable && state_ == 0;
  if (invalid_char || no_state || state_ > kMaxState) {
    state_ = 0;
  } else {
    state_ |= kValid;
  }
}

TaskState::TaskStateStr TaskState::ToString(char separator) const {
  PERFETTO_CHECK(is_valid());

  char buffer[32];
  size_t pos = 0;

  // This mapping is given by the file
  // https://android.googlesource.com/kernel/msm.git/+/android-msm-wahoo-4.4-pie-qpr1/include/trace/events/sched.h#155
  if (is_runnable()) {
    buffer[pos++] = 'R';
  } else {
    if (state_ & Atom::kInterruptibleSleep)
      buffer[pos++] = 'S';
    if (state_ & Atom::kUninterruptibleSleep) {
      if (separator && pos != 0)
        buffer[pos++] = separator;
      buffer[pos++] = 'D';  // D for (D)isk sleep
    }
    if (state_ & Atom::kStopped) {
      if (separator && pos != 0)
        buffer[pos++] = separator;
      buffer[pos++] = 'T';
    }
    if (state_ & Atom::kTraced) {
      if (separator && pos != 0)
        buffer[pos++] = separator;
      buffer[pos++] = 't';
    }
    if (state_ & Atom::kExitDead) {
      if (separator && pos != 0)
        buffer[pos++] = separator;
      buffer[pos++] = 'X';
    }
    if (state_ & Atom::kExitZombie) {
      if (separator && pos != 0)
        buffer[pos++] = separator;
      buffer[pos++] = 'Z';
    }
    if (state_ & Atom::kTaskDead) {
      if (separator && pos != 0)
        buffer[pos++] = separator;
      buffer[pos++] = 'x';
    }
    if (state_ & Atom::kWakeKill) {
      if (separator && pos != 0)
        buffer[pos++] = separator;
      buffer[pos++] = 'K';
    }
    if (state_ & Atom::kWaking) {
      if (separator && pos != 0)
        buffer[pos++] = separator;
      buffer[pos++] = 'W';
    }
    if (state_ & Atom::kParked) {
      if (separator && pos != 0)
        buffer[pos++] = separator;
      buffer[pos++] = 'P';
    }
    if (state_ & Atom::kNoLoad) {
      if (separator && pos != 0)
        buffer[pos++] = separator;
      buffer[pos++] = 'N';
    }
  }

  if (is_kernel_preempt())
    buffer[pos++] = '+';

  TaskStateStr output{};
  memcpy(output.data(), buffer, std::min(pos, output.size() - 1));
  return output;
}

}  // namespace ftrace_utils
}  // namespace trace_processor
}  // namespace perfetto
<commit_msg>Allow invalid task state for conversion<commit_after>/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "src/trace_processor/types/task_state.h"

#include <stdint.h>
#include <algorithm>

#include "perfetto/base/logging.h"
#include "perfetto/ext/base/string_writer.h"

namespace perfetto {
namespace trace_processor {
namespace ftrace_utils {

TaskState::TaskState(uint16_t raw_state) {
  if (raw_state > kMaxState) {
    state_ = 0;
  } else {
    state_ = raw_state | kValid;
  }
}

TaskState::TaskState(const char* state_str) {
  bool invalid_char = false;
  bool is_runnable = false;
  for (size_t i = 0; state_str[i] != '\0'; i++) {
    char c = state_str[i];
    if (is_kernel_preempt()) {
      // No other character should be encountered after '+'.
      invalid_char = true;
      break;
    } else if (c == '+') {
      state_ |= kMaxState;
      continue;
    }

    if (is_runnable) {
      // We should not encounter any character apart from '+' if runnable.
      invalid_char = true;
      break;
    }

    if (c == 'R') {
      if (state_ != 0) {
        // We should not encounter R if we already have set other atoms.
        invalid_char = true;
        break;
      } else {
        is_runnable = true;
        continue;
      }
    }

    if (c == 'S')
      state_ |= Atom::kInterruptibleSleep;
    else if (c == 'D')
      state_ |= Atom::kUninterruptibleSleep;
    else if (c == 'T')
      state_ |= Atom::kStopped;
    else if (c == 't')
      state_ |= Atom::kTraced;
    else if (c == 'X')
      state_ |= Atom::kExitDead;
    else if (c == 'Z')
      state_ |= Atom::kExitZombie;
    else if (c == 'x')
      state_ |= Atom::kTaskDead;
    else if (c == 'K')
      state_ |= Atom::kWakeKill;
    else if (c == 'W')
      state_ |= Atom::kWaking;
    else if (c == 'P')
      state_ |= Atom::kParked;
    else if (c == 'N')
      state_ |= Atom::kNoLoad;
    else if (c == '|')
      continue;
    else {
      invalid_char = true;
      break;
    }
  }

  bool no_state = !is_runnable && state_ == 0;
  if (invalid_char || no_state || state_ > kMaxState) {
    state_ = 0;
  } else {
    state_ |= kValid;
  }
}

TaskState::TaskStateStr TaskState::ToString(char separator) const {
  if (!is_valid()) {
    return TaskStateStr{"?"};
  }

  char buffer[32];
  size_t pos = 0;

  // This mapping is given by the file
  // https://android.googlesource.com/kernel/msm.git/+/android-msm-wahoo-4.4-pie-qpr1/include/trace/events/sched.h#155
  if (is_runnable()) {
    buffer[pos++] = 'R';
  } else {
    if (state_ & Atom::kInterruptibleSleep)
      buffer[pos++] = 'S';
    if (state_ & Atom::kUninterruptibleSleep) {
      if (separator && pos != 0)
        buffer[pos++] = separator;
      buffer[pos++] = 'D';  // D for (D)isk sleep
    }
    if (state_ & Atom::kStopped) {
      if (separator && pos != 0)
        buffer[pos++] = separator;
      buffer[pos++] = 'T';
    }
    if (state_ & Atom::kTraced) {
      if (separator && pos != 0)
        buffer[pos++] = separator;
      buffer[pos++] = 't';
    }
    if (state_ & Atom::kExitDead) {
      if (separator && pos != 0)
        buffer[pos++] = separator;
      buffer[pos++] = 'X';
    }
    if (state_ & Atom::kExitZombie) {
      if (separator && pos != 0)
        buffer[pos++] = separator;
      buffer[pos++] = 'Z';
    }
    if (state_ & Atom::kTaskDead) {
      if (separator && pos != 0)
        buffer[pos++] = separator;
      buffer[pos++] = 'x';
    }
    if (state_ & Atom::kWakeKill) {
      if (separator && pos != 0)
        buffer[pos++] = separator;
      buffer[pos++] = 'K';
    }
    if (state_ & Atom::kWaking) {
      if (separator && pos != 0)
        buffer[pos++] = separator;
      buffer[pos++] = 'W';
    }
    if (state_ & Atom::kParked) {
      if (separator && pos != 0)
        buffer[pos++] = separator;
      buffer[pos++] = 'P';
    }
    if (state_ & Atom::kNoLoad) {
      if (separator && pos != 0)
        buffer[pos++] = separator;
      buffer[pos++] = 'N';
    }
  }

  if (is_kernel_preempt())
    buffer[pos++] = '+';

  TaskStateStr output{};
  memcpy(output.data(), buffer, std::min(pos, output.size() - 1));
  return output;
}

}  // namespace ftrace_utils
}  // namespace trace_processor
}  // namespace perfetto
<|endoftext|>


<commit_before>#include <stdio.h>
#include <vector>
#include <cmath>

#include "ChSystemParallel.h"
#include "ChLcpSystemDescriptorParallel.h"

#include "utils/input_output.h"
#include "utils/generators.h"

using namespace chrono;

using std::cout;
using std::endl;

// =======================================================================
enum ProblemType {
	SETTLING,
	DROPPING
};

ProblemType problem = SETTLING;

// =======================================================================
// Global problem definitions

int threads = 8;

// Simulation parameters
double gravity = 9.81;
double time_step = 0.0001;
double time_settling_min = 1;
double time_settling_max = 5;
double time_dropping = 1;

int max_iteration = 20;

// Output
const char* data_folder = "../CRATER";
const char* checkpoint_file = "../CRATER/settled.dat";
double out_fps = 30;

// Parameters for the granular material
int        Id_g = 1;
double     r_g = 1e-3 / 2;
double     rho_g = 2500;
double     vol_g = (4.0/3) * PI * r_g * r_g * r_g;
double     mass_g = rho_g * vol_g;
ChVector<> inertia_g = 0.4 * mass_g * r_g * r_g * ChVector<>(1,1,1);

float      Y_g = 1e8;
float      mu_g = 0.3;
float      alpha_g = 0.1;

// Parameters for the falling ball
int        Id_b = 0;
double     R_b = 2.54e-2 / 2;
double     rho_b = 2000;
double     vol_b = (4.0/3) * PI * R_b * R_b * R_b;
double     mass_b = rho_b * vol_b;
ChVector<> inertia_b = 0.4 * mass_b * R_b * R_b * ChVector<>(1,1,1);

float      Y_b = 1e8;
float      mu_b = 0.3;
float      alpha_b = 0.1;

// Parameters for the containing bin
int        binId = -200;
double     hDimX = 4.5e-2;          // length in x direction
double     hDimY = 4.5e-2;          // depth in y direction
double     hDimZ = 7.5e-2;          // height in z direction
double     hThickness = 0.5e-2;     // wall thickness

float      Y_c = 2e6;
float      mu_c = 0.3;
float      alpha_c = 0.6;

// Number of layers and height of one layer for generator domain
int        numLayers = 4;
double     layerHeight = 1e-2;

// Drop height (above surface of settled granular material)
double h = 10e-2;

// =======================================================================

void AddWall(ChSharedBodyDEMPtr&  body,
             const ChVector<>&    loc,
             const ChVector<>&    dim)
{
	// Append to collision geometry
	body->GetCollisionModel()->AddBox(dim.x, dim.y, dim.z, loc);

	// Append to assets
	ChSharedPtr<ChBoxShape> box_shape = ChSharedPtr<ChAsset>(new ChBoxShape);
	box_shape->SetColor(ChColor(1, 0, 0));
	box_shape->Pos = loc;
	box_shape->Rot = ChQuaternion<>(1, 0, 0, 0);
	box_shape->GetBoxGeometry().Size = dim;

	body->GetAssets().push_back(box_shape);
}

int CreateObjects(ChSystemParallel* system)
{
	// Create a material for the granular material
	ChSharedPtr<ChMaterialSurfaceDEM> mat_g;
	mat_g = ChSharedPtr<ChMaterialSurfaceDEM>(new ChMaterialSurfaceDEM);
	mat_g->SetYoungModulus(Y_g);
	mat_g->SetFriction(mu_g);
	mat_g->SetDissipationFactor(alpha_g);

	// Create a material for the container
	ChSharedPtr<ChMaterialSurfaceDEM> mat_c;
	mat_c = ChSharedPtr<ChMaterialSurfaceDEM>(new ChMaterialSurfaceDEM);
	mat_c->SetYoungModulus(Y_c);
	mat_c->SetFriction(mu_c);
	mat_c->SetDissipationFactor(alpha_c);

	// Create a mixture entirely made out of spheres
	utils::Generator gen(system);

	utils::MixtureIngredientPtr& m1 = gen.AddMixtureIngredient(utils::SPHERE, 1.0);
	m1->setDefaultMaterialDEM(mat_g);
	m1->setDefaultDensity(rho_g);
	m1->setDefaultSize(r_g);

	gen.setBodyIdentifier(Id_g);

	double r = 1.01 * r_g;

	for (int i = 0; i < numLayers; i++) {
		double center = r + layerHeight / 2 + i * (r + layerHeight);
		gen.createObjectsBox(utils::POISSON_DISK,
		                     2 * r,
		                     ChVector<>(0, 0, center),
		                     ChVector<>(hDimX - r, hDimY - r, layerHeight/2));
		cout << "Layer " << i << "total bodies: " << gen.getTotalNumBodies() << endl;
	}

	// Create the containing bin
	ChSharedBodyDEMPtr bin(new ChBodyDEM(new ChCollisionModelParallel));

	bin->SetMaterialSurfaceDEM(mat_c);

	bin->SetIdentifier(binId);
	bin->SetMass(1);
	bin->SetPos(ChVector<>(0, 0, 0));
	bin->SetRot(ChQuaternion<>(1, 0, 0, 0));
	bin->SetCollide(true);
	bin->SetBodyFixed(true);

	bin->GetCollisionModel()->ClearModel();
	AddWall(bin, ChVector<>(0, 0, -hThickness), ChVector<>(hDimX, hDimY, hThickness));
	AddWall(bin, ChVector<>(-hDimX-hThickness, 0, hDimZ), ChVector<>(hThickness, hDimY, hDimZ));
	AddWall(bin, ChVector<>( hDimX+hThickness, 0, hDimZ), ChVector<>(hThickness, hDimY, hDimZ));
	AddWall(bin, ChVector<>(0, -hDimY-hThickness, hDimZ), ChVector<>(hDimX, hThickness, hDimZ));
	AddWall(bin, ChVector<>(0,  hDimY+hThickness, hDimZ), ChVector<>(hDimX, hThickness, hDimZ));
	bin->GetCollisionModel()->BuildModel();

	system->AddBody(bin);

	return gen.getTotalNumBodies();
}

// =======================================================================
// Create the falling ball such that its bottom point is at the specified
// height and its downward initial velocity has the specified magnitude.

void CreateFallingBall(ChSystemParallel* system, double z, double vz)
{
	// Create a material for the falling ball
	ChSharedPtr<ChMaterialSurfaceDEM> mat_b;
	mat_b = ChSharedPtr<ChMaterialSurfaceDEM>(new ChMaterialSurfaceDEM);
	mat_b->SetYoungModulus(1e8f);
	mat_b->SetFriction(0.4f);
	mat_b->SetDissipationFactor(0.1f);

	// Create the falling ball, but do not add it to the system
	ChSharedBodyDEMPtr ball(new ChBodyDEM(new ChCollisionModelParallel));

	ball->SetMaterialSurfaceDEM(mat_b);

	ball->SetIdentifier(Id_b);
	ball->SetMass(mass_b);
	ball->SetInertiaXX(inertia_b);
	ball->SetPos(ChVector<>(0, 0, z + R_b));
	ball->SetRot(ChQuaternion<>(1, 0, 0, 0));
	ball->SetPos_dt(ChVector<>(0, 0, -vz));
	ball->SetCollide(true);
	ball->SetBodyFixed(false);

	ball->GetCollisionModel()->ClearModel();
	ball->GetCollisionModel()->AddSphere(R_b);
	ball->GetCollisionModel()->BuildModel();

	ChSharedPtr<ChSphereShape> ball_shape = ChSharedPtr<ChAsset>(new ChSphereShape);
	ball_shape->SetColor(ChColor(0, 0, 1));
	ball_shape->GetSphereGeometry().rad = R_b;
	ball_shape->Pos = ChVector<>(0, 0, 0);
	ball_shape->Rot = ChQuaternion<>(1, 0, 0, 0);
	ball->GetAssets().push_back(ball_shape);

	system->AddBody(ball);
}

// ========================================================================
// These utility functions find the height of the highest or lowest sphere
// in the granular mix, respectively.  We only look at bodies whith stricty
// positive identifiers.

double FindHighest(ChSystem* sys)
{
	double highest = 0;
	for (int i = 0; i < sys->Get_bodylist()->size(); ++i) {
		ChBody* body = (ChBody*) sys->Get_bodylist()->at(i);
		if (body->GetIdentifier() > 0 && body->GetPos().z > highest)
			highest = body->GetPos().z;
	}
	return highest;
}

double FindLowest(ChSystem* sys)
{
	double lowest = 1000;
	for (int i = 0; i < sys->Get_bodylist()->size(); ++i) {
		ChBody* body = (ChBody*) sys->Get_bodylist()->at(i);
		if (body->GetIdentifier() > 0 && body->GetPos().z < lowest)
			lowest = body->GetPos().z;
	}
	return lowest;
}

// ========================================================================
// This utility function returns true if all bodies in the granular mix
// have a linear velocity whose magnitude is below the specified value.

bool CheckSettled(ChSystem* sys, double threshold)
{
	double t2 = threshold * threshold;
	for (int i = 0; i < sys->Get_bodylist()->size(); ++i) {
		ChBody* body = (ChBody*) sys->Get_bodylist()->at(i);
		if (body->GetIdentifier() > 0) {
			double vel2 = body->GetPos_dt().Length2();
			if (vel2 > t2)
				return false;
		}
	}

	return true;
}

// ========================================================================
int main(int argc, char* argv[])
{

	// Create system
	ChSystemParallelDEM* msystem = new ChSystemParallelDEM();

	// Set number of threads.
	int max_threads = msystem->GetParallelThreadNumber();
	if (threads > max_threads)
		threads = max_threads;
	msystem->SetParallelThreadNumber(threads);
	omp_set_num_threads(threads);

	// Set gravitational acceleration
	msystem->Set_G_acc(ChVector<>(0, 0, -gravity));

	// Edit system settings
	msystem->SetMaxiter(max_iteration);
	msystem->SetIterLCPmaxItersSpeed(max_iteration);
	msystem->SetTol(1e-3);
	msystem->SetTolSpeeds(1e-3);
	msystem->SetStep(time_step);

	((ChLcpSolverParallelDEM*) msystem->GetLcpSolverSpeed())->SetMaxIteration(max_iteration);
	((ChLcpSolverParallelDEM*) msystem->GetLcpSolverSpeed())->SetTolerance(0);
	((ChLcpSolverParallelDEM*) msystem->GetLcpSolverSpeed())->SetContactRecoverySpeed(1);

	((ChCollisionSystemParallel*) msystem->GetCollisionSystem())->setBinsPerAxis(I3(10, 10, 10));
	((ChCollisionSystemParallel*) msystem->GetCollisionSystem())->setBodyPerBin(100, 50);

	((ChCollisionSystemParallel*) msystem->GetCollisionSystem())->ChangeNarrowphase(new ChCNarrowphaseR);

	// Depending on problem type:
	// - Select end simulation times
	// - Create granular material and container
	// - Create falling ball
	double time_end;

	if (problem == SETTLING) {
		time_end = time_settling_max;

		// Create containing bin and the granular material at randomized initial positions
		CreateObjects(msystem);
	} else {
		time_end = time_dropping;

		// Create the granular material bodies and the container from the checkpoint file.
		utils::ReadCheckpoint(msystem, checkpoint_file);

		// Create the falling ball just above the granular material with a velocity
		// given by free fall from the specified height and starting at rest.
		double z = FindHighest(msystem);
		double vz = std::sqrt(2 * gravity * h);
		CreateFallingBall(msystem, z, vz);
	}

	// Number of steps
	int num_steps = std::ceil(time_end / time_step);
	int out_steps = std::ceil((1 / time_step) / out_fps);

	// Zero velocity level for settling check (fraction of a grain radius per second)
	double zero_v = 0.1 * r_g;

	// Perform the simulation
	double time = 0;
	int sim_frame = 0;
	int out_frame = 0;
	int next_out_frame = 0;
	double exec_time = 0;

	while (time < time_end) {
		if (sim_frame == next_out_frame) {
			char filename[100];
			sprintf(filename, "%s/POVRAY/data_%03d.dat", data_folder, out_frame);
			utils::WriteShapesPovray(msystem, filename);

			cout << " --------------------------------- " << out_frame << "  " << time << "  " <<  endl;
			cout << "                                   " << FindLowest(msystem) << endl;
			cout << "                                   " << exec_time << endl;

			out_frame++;
			next_out_frame += out_steps;
		}

		if (problem == SETTLING && time > time_settling_min && CheckSettled(msystem, zero_v)) {
			cout << "Granular material settled...  time = " << time << endl;
			break;
		}

		msystem->DoStepDynamics(time_step);

		time += time_step;
		sim_frame++;
		exec_time += msystem->mtimer_step();
	}

	// Create a checkpoint from the last state
	if (problem == SETTLING)
		utils::WriteCheckpoint(msystem, checkpoint_file);

	// Final stats
	cout << "==================================" << endl;
	cout << "Number of bodies: " << msystem->Get_bodylist()->size() << endl;
	cout << "Lowest position: " << FindLowest(msystem) << endl;
	cout << "Simulation time: " << exec_time << endl;
	cout << "Number of threads: " << threads << endl;

	return 0;
}

<commit_msg>Fix bug in calculating layer offsets.<commit_after>#include <stdio.h>
#include <vector>
#include <cmath>

#include "ChSystemParallel.h"
#include "ChLcpSystemDescriptorParallel.h"

#include "utils/input_output.h"
#include "utils/generators.h"

using namespace chrono;

using std::cout;
using std::endl;

// =======================================================================
enum ProblemType {
	SETTLING,
	DROPPING
};

ProblemType problem = SETTLING;

// =======================================================================
// Global problem definitions

int threads = 8;

// Simulation parameters
double gravity = 9.81;
double time_step = 0.0001;
double time_settling_min = 1;
double time_settling_max = 5;
double time_dropping = 1;

int max_iteration = 20;

// Output
const char* data_folder = "../CRATER";
const char* checkpoint_file = "../CRATER/settled.dat";
double out_fps = 30;

// Parameters for the granular material
int        Id_g = 1;
double     r_g = 1e-3 / 2;
double     rho_g = 2500;
double     vol_g = (4.0/3) * PI * r_g * r_g * r_g;
double     mass_g = rho_g * vol_g;
ChVector<> inertia_g = 0.4 * mass_g * r_g * r_g * ChVector<>(1,1,1);

float      Y_g = 1e8;
float      mu_g = 0.3;
float      alpha_g = 0.1;

// Parameters for the falling ball
int        Id_b = 0;
double     R_b = 2.54e-2 / 2;
double     rho_b = 2000;
double     vol_b = (4.0/3) * PI * R_b * R_b * R_b;
double     mass_b = rho_b * vol_b;
ChVector<> inertia_b = 0.4 * mass_b * R_b * R_b * ChVector<>(1,1,1);

float      Y_b = 1e8;
float      mu_b = 0.3;
float      alpha_b = 0.1;

// Parameters for the containing bin
int        binId = -200;
double     hDimX = 4e-2;            // length in x direction
double     hDimY = 4e-2;            // depth in y direction
double     hDimZ = 7.5e-2;          // height in z direction
double     hThickness = 0.5e-2;     // wall thickness

float      Y_c = 2e6;
float      mu_c = 0.3;
float      alpha_c = 0.6;

// Number of layers and height of one layer for generator domain
int        numLayers = 4;
double     layerHeight = 1e-2;

// Drop height (above surface of settled granular material)
double h = 10e-2;

// =======================================================================

void AddWall(ChSharedBodyDEMPtr&  body,
             const ChVector<>&    loc,
             const ChVector<>&    dim)
{
	// Append to collision geometry
	body->GetCollisionModel()->AddBox(dim.x, dim.y, dim.z, loc);

	// Append to assets
	ChSharedPtr<ChBoxShape> box_shape = ChSharedPtr<ChAsset>(new ChBoxShape);
	box_shape->SetColor(ChColor(1, 0, 0));
	box_shape->Pos = loc;
	box_shape->Rot = ChQuaternion<>(1, 0, 0, 0);
	box_shape->GetBoxGeometry().Size = dim;

	body->GetAssets().push_back(box_shape);
}

int CreateObjects(ChSystemParallel* system)
{
	// Create a material for the granular material
	ChSharedPtr<ChMaterialSurfaceDEM> mat_g;
	mat_g = ChSharedPtr<ChMaterialSurfaceDEM>(new ChMaterialSurfaceDEM);
	mat_g->SetYoungModulus(Y_g);
	mat_g->SetFriction(mu_g);
	mat_g->SetDissipationFactor(alpha_g);

	// Create a material for the container
	ChSharedPtr<ChMaterialSurfaceDEM> mat_c;
	mat_c = ChSharedPtr<ChMaterialSurfaceDEM>(new ChMaterialSurfaceDEM);
	mat_c->SetYoungModulus(Y_c);
	mat_c->SetFriction(mu_c);
	mat_c->SetDissipationFactor(alpha_c);

	// Create a mixture entirely made out of spheres
	utils::Generator gen(system);

	utils::MixtureIngredientPtr& m1 = gen.AddMixtureIngredient(utils::SPHERE, 1.0);
	m1->setDefaultMaterialDEM(mat_g);
	m1->setDefaultDensity(rho_g);
	m1->setDefaultSize(r_g);

	gen.setBodyIdentifier(Id_g);

	double r = 1.01 * r_g;

	for (int i = 0; i < numLayers; i++) {
		double center = r + layerHeight / 2 + i * (2 * r + layerHeight);
		gen.createObjectsBox(utils::POISSON_DISK,
		                     2 * r,
		                     ChVector<>(0, 0, center),
		                     ChVector<>(hDimX - r, hDimY - r, layerHeight/2));
		cout << "Layer " << i << "total bodies: " << gen.getTotalNumBodies() << endl;
	}

	// Create the containing bin
	ChSharedBodyDEMPtr bin(new ChBodyDEM(new ChCollisionModelParallel));

	bin->SetMaterialSurfaceDEM(mat_c);

	bin->SetIdentifier(binId);
	bin->SetMass(1);
	bin->SetPos(ChVector<>(0, 0, 0));
	bin->SetRot(ChQuaternion<>(1, 0, 0, 0));
	bin->SetCollide(true);
	bin->SetBodyFixed(true);

	bin->GetCollisionModel()->ClearModel();
	AddWall(bin, ChVector<>(0, 0, -hThickness), ChVector<>(hDimX, hDimY, hThickness));
	AddWall(bin, ChVector<>(-hDimX-hThickness, 0, hDimZ), ChVector<>(hThickness, hDimY, hDimZ));
	AddWall(bin, ChVector<>( hDimX+hThickness, 0, hDimZ), ChVector<>(hThickness, hDimY, hDimZ));
	AddWall(bin, ChVector<>(0, -hDimY-hThickness, hDimZ), ChVector<>(hDimX, hThickness, hDimZ));
	AddWall(bin, ChVector<>(0,  hDimY+hThickness, hDimZ), ChVector<>(hDimX, hThickness, hDimZ));
	bin->GetCollisionModel()->BuildModel();

	system->AddBody(bin);

	return gen.getTotalNumBodies();
}

// =======================================================================
// Create the falling ball such that its bottom point is at the specified
// height and its downward initial velocity has the specified magnitude.

void CreateFallingBall(ChSystemParallel* system, double z, double vz)
{
	// Create a material for the falling ball
	ChSharedPtr<ChMaterialSurfaceDEM> mat_b;
	mat_b = ChSharedPtr<ChMaterialSurfaceDEM>(new ChMaterialSurfaceDEM);
	mat_b->SetYoungModulus(1e8f);
	mat_b->SetFriction(0.4f);
	mat_b->SetDissipationFactor(0.1f);

	// Create the falling ball, but do not add it to the system
	ChSharedBodyDEMPtr ball(new ChBodyDEM(new ChCollisionModelParallel));

	ball->SetMaterialSurfaceDEM(mat_b);

	ball->SetIdentifier(Id_b);
	ball->SetMass(mass_b);
	ball->SetInertiaXX(inertia_b);
	ball->SetPos(ChVector<>(0, 0, z + R_b));
	ball->SetRot(ChQuaternion<>(1, 0, 0, 0));
	ball->SetPos_dt(ChVector<>(0, 0, -vz));
	ball->SetCollide(true);
	ball->SetBodyFixed(false);

	ball->GetCollisionModel()->ClearModel();
	ball->GetCollisionModel()->AddSphere(R_b);
	ball->GetCollisionModel()->BuildModel();

	ChSharedPtr<ChSphereShape> ball_shape = ChSharedPtr<ChAsset>(new ChSphereShape);
	ball_shape->SetColor(ChColor(0, 0, 1));
	ball_shape->GetSphereGeometry().rad = R_b;
	ball_shape->Pos = ChVector<>(0, 0, 0);
	ball_shape->Rot = ChQuaternion<>(1, 0, 0, 0);
	ball->GetAssets().push_back(ball_shape);

	system->AddBody(ball);
}

// ========================================================================
// These utility functions find the height of the highest or lowest sphere
// in the granular mix, respectively.  We only look at bodies whith stricty
// positive identifiers.

double FindHighest(ChSystem* sys)
{
	double highest = 0;
	for (int i = 0; i < sys->Get_bodylist()->size(); ++i) {
		ChBody* body = (ChBody*) sys->Get_bodylist()->at(i);
		if (body->GetIdentifier() > 0 && body->GetPos().z > highest)
			highest = body->GetPos().z;
	}
	return highest;
}

double FindLowest(ChSystem* sys)
{
	double lowest = 1000;
	for (int i = 0; i < sys->Get_bodylist()->size(); ++i) {
		ChBody* body = (ChBody*) sys->Get_bodylist()->at(i);
		if (body->GetIdentifier() > 0 && body->GetPos().z < lowest)
			lowest = body->GetPos().z;
	}
	return lowest;
}

// ========================================================================
// This utility function returns true if all bodies in the granular mix
// have a linear velocity whose magnitude is below the specified value.

bool CheckSettled(ChSystem* sys, double threshold)
{
	double t2 = threshold * threshold;
	for (int i = 0; i < sys->Get_bodylist()->size(); ++i) {
		ChBody* body = (ChBody*) sys->Get_bodylist()->at(i);
		if (body->GetIdentifier() > 0) {
			double vel2 = body->GetPos_dt().Length2();
			if (vel2 > t2)
				return false;
		}
	}

	return true;
}

// ========================================================================
int main(int argc, char* argv[])
{

	// Create system
	ChSystemParallelDEM* msystem = new ChSystemParallelDEM();

	// Set number of threads.
	int max_threads = msystem->GetParallelThreadNumber();
	if (threads > max_threads)
		threads = max_threads;
	msystem->SetParallelThreadNumber(threads);
	omp_set_num_threads(threads);

	// Set gravitational acceleration
	msystem->Set_G_acc(ChVector<>(0, 0, -gravity));

	// Edit system settings
	msystem->SetMaxiter(max_iteration);
	msystem->SetIterLCPmaxItersSpeed(max_iteration);
	msystem->SetTol(1e-3);
	msystem->SetTolSpeeds(1e-3);
	msystem->SetStep(time_step);

	((ChLcpSolverParallelDEM*) msystem->GetLcpSolverSpeed())->SetMaxIteration(max_iteration);
	((ChLcpSolverParallelDEM*) msystem->GetLcpSolverSpeed())->SetTolerance(0);
	((ChLcpSolverParallelDEM*) msystem->GetLcpSolverSpeed())->SetContactRecoverySpeed(1);

	((ChCollisionSystemParallel*) msystem->GetCollisionSystem())->setBinsPerAxis(I3(10, 10, 10));
	((ChCollisionSystemParallel*) msystem->GetCollisionSystem())->setBodyPerBin(100, 50);

	((ChCollisionSystemParallel*) msystem->GetCollisionSystem())->ChangeNarrowphase(new ChCNarrowphaseR);

	// Depending on problem type:
	// - Select end simulation times
	// - Create granular material and container
	// - Create falling ball
	double time_end;

	if (problem == SETTLING) {
		time_end = time_settling_max;

		// Create containing bin and the granular material at randomized initial positions
		CreateObjects(msystem);
	} else {
		time_end = time_dropping;

		// Create the granular material bodies and the container from the checkpoint file.
		utils::ReadCheckpoint(msystem, checkpoint_file);

		// Create the falling ball just above the granular material with a velocity
		// given by free fall from the specified height and starting at rest.
		double z = FindHighest(msystem);
		double vz = std::sqrt(2 * gravity * h);
		CreateFallingBall(msystem, z, vz);
	}

	// Number of steps
	int num_steps = std::ceil(time_end / time_step);
	int out_steps = std::ceil((1 / time_step) / out_fps);

	// Zero velocity level for settling check (fraction of a grain radius per second)
	double zero_v = 0.1 * r_g;

	// Perform the simulation
	double time = 0;
	int sim_frame = 0;
	int out_frame = 0;
	int next_out_frame = 0;
	double exec_time = 0;

	while (time < time_end) {
		if (sim_frame == next_out_frame) {
			char filename[100];
			sprintf(filename, "%s/POVRAY/data_%03d.dat", data_folder, out_frame);
			utils::WriteShapesPovray(msystem, filename);

			cout << " --------------------------------- " << out_frame << "  " << time << "  " <<  endl;
			cout << "                                   " << FindLowest(msystem) << endl;
			cout << "                                   " << exec_time << endl;

			out_frame++;
			next_out_frame += out_steps;
		}

		if (problem == SETTLING && time > time_settling_min && CheckSettled(msystem, zero_v)) {
			cout << "Granular material settled...  time = " << time << endl;
			break;
		}

		msystem->DoStepDynamics(time_step);

		time += time_step;
		sim_frame++;
		exec_time += msystem->mtimer_step();
	}

	// Create a checkpoint from the last state
	if (problem == SETTLING)
		utils::WriteCheckpoint(msystem, checkpoint_file);

	// Final stats
	cout << "==================================" << endl;
	cout << "Number of bodies: " << msystem->Get_bodylist()->size() << endl;
	cout << "Lowest position: " << FindLowest(msystem) << endl;
	cout << "Simulation time: " << exec_time << endl;
	cout << "Number of threads: " << threads << endl;

	return 0;
}

<|endoftext|>


<commit_before>#include <vector>

#include <opengm/functions/explicit_function.hxx>
#include <opengm/unittests/test.hxx>
#include <opengm/graphicalmodel/graphicalmodel.hxx>
#include <opengm/operations/adder.hxx>
#include <opengm/operations/minimizer.hxx>
#include <opengm/inference/external/trws.hxx>
#include <opengm/inference/lpgurobi.hxx>
#include <opengm/utilities/metaprogramming.hxx>

#include <opengm/functions/learnable/lpotts.hxx>
#include <opengm/functions/learnable/sum_of_experts.hxx>
#include <opengm/learning/struct-max-margin.hxx>
#include <opengm/learning/loss/hammingloss.hxx>
//#include <opengm/learning/dataset/testdataset.hxx>
//#include <opengm/learning/dataset/testdataset2.hxx>
#include <opengm/learning/dataset/testdatasets.hxx>

//*************************************
typedef double ValueType;
typedef size_t IndexType;
typedef size_t LabelType;
typedef opengm::meta::TypeListGenerator<opengm::ExplicitFunction<ValueType,IndexType,LabelType>, opengm::functions::learnable::LPotts<ValueType,IndexType,LabelType>, opengm::functions::learnable::SumOfExperts<ValueType,IndexType,LabelType> >::type FunctionListType;
typedef opengm::GraphicalModel<ValueType,opengm::Adder, FunctionListType, opengm::DiscreteSpace<IndexType,LabelType> > GM;
typedef opengm::learning::HammingLoss     LOSS;
typedef opengm::LPGurobi<GM,opengm::Minimizer> INF;
typedef opengm::datasets::TestDataset1<GM,LOSS> DS1;
typedef opengm::datasets::TestDataset2<GM,LOSS> DS2;
typedef opengm::datasets::TestDatasetSimple<GM,LOSS> DSS;

//*************************************

int main() {
   std::cout << " Includes are fine :-) " << std::endl;

   {
	  DSS dataset(1);
	  std::cout << "Dataset includes " << dataset.getNumberOfModels() << " instances and has " << dataset.getNumberOfWeights() << " parameters."<<std::endl;

	  opengm::learning::StructMaxMargin<DSS,LOSS>::Parameter para;
	  opengm::learning::StructMaxMargin<DSS,LOSS> learner(dataset,para);

	  INF::Parameter infPara;
	  infPara.integerConstraint_ = true;
	  learner.learn<INF>(infPara);
   }

   {
	  DS1 dataset(1);
	  std::cout << "Dataset includes " << dataset.getNumberOfModels() << " instances and has " << dataset.getNumberOfWeights() << " parameters."<<std::endl;

	  opengm::learning::StructMaxMargin<DS1,LOSS>::Parameter para;
	  opengm::learning::StructMaxMargin<DS1,LOSS> learner(dataset,para);

	  INF::Parameter infPara;
	  infPara.integerConstraint_ = true;
	  learner.learn<INF>(infPara);

   }

   //{
	  //DS2 dataset(1);
	  //std::cout << "Dataset includes " << dataset.getNumberOfModels() << " instances and has " << dataset.getNumberOfWeights() << " parameters."<<std::endl;

	  //opengm::learning::StructMaxMargin<DS2,LOSS>::Parameter para;
	  //opengm::learning::StructMaxMargin<DS2,LOSS> learner(dataset,para);

	  //INF::Parameter infPara;
	  //infPara.integerConstraint_ = true;
	  //learner.learn<INF>(infPara);
   //}

}

<commit_msg>re-enabled all testdatasets in test_learning<commit_after>#include <vector>

#include <opengm/functions/explicit_function.hxx>
#include <opengm/unittests/test.hxx>
#include <opengm/graphicalmodel/graphicalmodel.hxx>
#include <opengm/operations/adder.hxx>
#include <opengm/operations/minimizer.hxx>
#include <opengm/inference/external/trws.hxx>
#include <opengm/inference/lpgurobi.hxx>
#include <opengm/utilities/metaprogramming.hxx>

#include <opengm/functions/learnable/lpotts.hxx>
#include <opengm/functions/learnable/sum_of_experts.hxx>
#include <opengm/learning/struct-max-margin.hxx>
#include <opengm/learning/loss/hammingloss.hxx>
//#include <opengm/learning/dataset/testdataset.hxx>
//#include <opengm/learning/dataset/testdataset2.hxx>
#include <opengm/learning/dataset/testdatasets.hxx>

//*************************************
typedef double ValueType;
typedef size_t IndexType;
typedef size_t LabelType;
typedef opengm::meta::TypeListGenerator<opengm::ExplicitFunction<ValueType,IndexType,LabelType>, opengm::functions::learnable::LPotts<ValueType,IndexType,LabelType>, opengm::functions::learnable::SumOfExperts<ValueType,IndexType,LabelType> >::type FunctionListType;
typedef opengm::GraphicalModel<ValueType,opengm::Adder, FunctionListType, opengm::DiscreteSpace<IndexType,LabelType> > GM;
typedef opengm::learning::HammingLoss     LOSS;
typedef opengm::LPGurobi<GM,opengm::Minimizer> INF;
typedef opengm::datasets::TestDataset1<GM,LOSS> DS1;
typedef opengm::datasets::TestDataset2<GM,LOSS> DS2;
typedef opengm::datasets::TestDatasetSimple<GM,LOSS> DSS;

//*************************************

int main() {
   std::cout << " Includes are fine :-) " << std::endl;

   {
	  DSS dataset(1);
	  std::cout << "Dataset includes " << dataset.getNumberOfModels() << " instances and has " << dataset.getNumberOfWeights() << " parameters."<<std::endl;

	  opengm::learning::StructMaxMargin<DSS,LOSS>::Parameter para;
	  opengm::learning::StructMaxMargin<DSS,LOSS> learner(dataset,para);

	  INF::Parameter infPara;
	  infPara.integerConstraint_ = true;
	  learner.learn<INF>(infPara);
   }

   {
	  DS1 dataset(1);
	  std::cout << "Dataset includes " << dataset.getNumberOfModels() << " instances and has " << dataset.getNumberOfWeights() << " parameters."<<std::endl;

	  opengm::learning::StructMaxMargin<DS1,LOSS>::Parameter para;
	  opengm::learning::StructMaxMargin<DS1,LOSS> learner(dataset,para);

	  INF::Parameter infPara;
	  infPara.integerConstraint_ = true;
	  learner.learn<INF>(infPara);

   }

   {
	  DS2 dataset(1);
	  std::cout << "Dataset includes " << dataset.getNumberOfModels() << " instances and has " << dataset.getNumberOfWeights() << " parameters."<<std::endl;

	  opengm::learning::StructMaxMargin<DS2,LOSS>::Parameter para;
	  opengm::learning::StructMaxMargin<DS2,LOSS> learner(dataset,para);

	  INF::Parameter infPara;
	  infPara.integerConstraint_ = true;
	  learner.learn<INF>(infPara);
   }

}

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of meegotouch-controlpanelapplets.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "wallpaperwidget.h"
#include "wallpaperlist.h"

#include <MApplicationPage>
#include <MLayout>
#include <MLinearLayoutPolicy>
#include <MContainer>
#include <QTimer>
#include <MContentItem>
#include <MAction>
#include <QGraphicsLinearLayout>
#include <QDebug>
#include <QtTracker/Tracker>
#include <MLabel>

//#define DEBUG
#define WARNING
#include "../debug.h"

static const int MaxColumns = 2;

static const char *oviCommand = "webwidgetrunner /usr/share/webwidgets/applications/d34177b1c241ea44cb132005b63ee6527c9f6040-wrt-widget.desktop -widgetparameter graphics &";

WallpaperWidget::WallpaperWidget (
        WallpaperBusinessLogic *wallpaperBusinessLogic,
        QGraphicsWidget        *parent) :
    DcpWidget (parent),
    m_WallpaperBusinessLogic (wallpaperBusinessLogic)
{
    /*
     * Unfortunatelly the content has to be created late, otherwise the list
     * only shows one row.
     * FIXME: I'm n ot sure how late should this be done, I thing we should use
     * the void MApplicationPage::createContent(), but I don't know how to do
     * that.
     */
    //createContent ();
    QTimer::singleShot(100, this, SLOT(createContent()));
}

WallpaperWidget::~WallpaperWidget ()
{
}

void
WallpaperWidget::createContent ()
{
    MLayout              *layout;
    MLinearLayoutPolicy  *mainLayout;

    /*
     * Creating a layout that holds the rows of the internal widgets.
     */
    layout = new MLayout (this);
    mainLayout = new MLinearLayoutPolicy (layout, Qt::Vertical);
    mainLayout->setContentsMargins (0., 0., 0., 0.);
    mainLayout->setSpacing (0.);
    setLayout (layout);

    /*
     * Adding the header/title
     */
    addHeaderContainer (mainLayout);

    /*
     * The list of the available images.
     */
    m_ImageList = new WallpaperList (m_WallpaperBusinessLogic, this);
    m_ImageList->setObjectName("WallpaperImageList");
    connect (m_ImageList, SIGNAL(imageActivated(WallpaperDescriptor *)),
            this, SLOT(slotImageActivated(WallpaperDescriptor *)));

    m_ImageList->setDataSourceType (WallpaperList::DataSourceLocal);

    /*
     * Adding all widgets into the layout.
     */
    mainLayout->addItem (m_ImageList);
    mainLayout->setStretchFactor (m_ImageList, 1);

    connect (m_WallpaperBusinessLogic, SIGNAL(imageEditRequested()),
            this, SLOT(slotImageActivated()));
}

void
WallpaperWidget::addHeaderContainer (
        MLinearLayoutPolicy *mainLayout)
{
    MContainer            *container;
    QGraphicsLinearLayout *layout;

    Q_ASSERT (mainLayout);

    SYS_DEBUG ("***********************************************************");
    /*
     * Creating a lcontainer and a layout.
     */
    container = new MContainer (this);
    container->setStyleName ("CommonXLargeHeaderPanelInverted");
    container->setHeaderVisible (false);
    container->setContentsMargins (0., 0., 0., 0.);
    //container->setSpacing (0.);

    layout = new QGraphicsLinearLayout (Qt::Horizontal);
    layout->setContentsMargins (0., 0., 0., 0.);
    layout->setSpacing (0.);
    container->centralWidget()->setLayout (layout);

    /*
     * The label that we use as title.
     */
    //% "Wallpaper"
    m_TitleLabel = new MLabel (qtTrId("qtn_wall_wallpaper"));
    m_TitleLabel->setStyleName ("CommonXLargeHeaderInverted");
    layout->addItem (m_TitleLabel);
    layout->setAlignment (m_TitleLabel, Qt::AlignLeft);

    /*
     * Adding the whole row to the main container.
     */
    mainLayout->addItem (container);
    mainLayout->setStretchFactor (container, 0);
}

void
WallpaperWidget::retranslateUi ()
{
    if (m_TitleLabel)
        //% "Wallpaper"
        m_TitleLabel->setText (qtTrId("qtn_wall_wallpaper"));
}

/*
 * This slot is called when the user activates an image in the list. The
 * WallpaperList has a signal for that.
 */
void
WallpaperWidget::slotImageActivated (
        WallpaperDescriptor *desc)
{
    SYS_DEBUG ("*** desc = %s", SYS_STR(desc->basename()));
    m_WallpaperBusinessLogic->startEdit (desc);
}

/*
 * When this slot is activated the image has to be already loaded, so that the
 * editor widget can be shown without delay.
 */
void
WallpaperWidget::slotImageActivated ()
{
    SYS_DEBUG ("");

    emit changeWidget (1);
}

void
WallpaperWidget::oviActivated ()
{
    SYS_DEBUG ("Executing %s", oviCommand);
    system (oviCommand);
}

void
WallpaperWidget::polishEvent ()
{
    QGraphicsWidget  *parent;
    MApplicationPage *page = 0;
    MAction          *action;

    /*
     * We need to find the MApplicationPage among our parents.
     */
    parent = parentWidget();
    while (parent) {
        page = qobject_cast <MApplicationPage *>(parent);
        if (page)
            break;
        parent = parent->parentWidget();
    }

    if (!page)
        return;

    /**************************************************************************
     * Hiding the home button.
     */
    page->setComponentsDisplayMode (
            MApplicationPage::HomeButton,
            MApplicationPageModel::Hide);

    /*
     * Adding the gallery action.
     */
    #ifdef HAVE_CONTENT_MANAGER
    action = new MAction("icon-m-content-gallery", "", this);
    action->setLocation(MAction::ToolBarLocation);
    page->addAction(action);
    connect(action, SIGNAL(triggered()), this, SLOT(galleryActivated()));
    #endif

    /*
     * Adding the ovi action.
     */
    action = new MAction("icon-m-common-ovi", "", this);
    action->setLocation(MAction::ToolBarLocation);
    page->addAction(action);
    connect(action, SIGNAL(triggered()), this, SLOT(oviActivated()));
}

#ifdef HAVE_CONTENT_MANAGER
/*!
 * Slot that is activated when the user clicked on the gallery item, the widget
 * that activates the ContentManager page. We support this only when the
 * ContentManager library is available.
 */
void
WallpaperWidget::galleryActivated ()
{
    /*
     * Please note that the m_ImageBrowser is a QPointer object that will reset
     * itself to NULL when the widget is destroyed. It will also initialize
     * itself to NULL when it is created.
     */
    if (!m_ImageBrowser) {
        m_ImageBrowser = new ContentItemsPage (this);
        m_ImageBrowser->setContentTypes (
          QStringList() <<
            "http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#Image");

        m_ImageBrowser->setObjectName (
                "SelectSingleContentItemPage_imageBrowser");
        m_ImageBrowser->setStyleName ("CommonApplicationPageInverted");
        m_ImageBrowser->setCommonLayoutSuffix ("Inverted");

        connect (m_ImageBrowser, SIGNAL (backButtonClicked ()),
                 m_ImageBrowser, SLOT (dismiss ()));
        connect (m_ImageBrowser, SIGNAL (itemClicked (const QString &)),
                 SLOT (galleryImageSelected (const QString &)));
    }

    m_ImageBrowser->appear (MSceneWindow::DestroyWhenDismissed);
}
#endif

#ifdef HAVE_CONTENT_MANAGER
/*!
 * Slot that activated when the user picks an image from the content manager
 * page. We only need this slot when the ContentManager library is activated.
 */
void
WallpaperWidget::galleryImageSelected (
        const QString &uri)
{
    m_WallpaperBusinessLogic->addImageFromGallery (uri);
    SYS_WARNING ("m_ImageBrowser->unselectItem (%s);", SYS_STR(uri));
    m_ImageBrowser->unselectItem (uri);
}
#endif

<commit_msg>Fixes: wallpaperwidget crash (happened only in ut_wallpaperwidget, so not serious)<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of meegotouch-controlpanelapplets.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "wallpaperwidget.h"
#include "wallpaperlist.h"

#include <MApplicationPage>
#include <MLayout>
#include <MLinearLayoutPolicy>
#include <MContainer>
#include <QTimer>
#include <MContentItem>
#include <MAction>
#include <QGraphicsLinearLayout>
#include <QDebug>
#include <QtTracker/Tracker>
#include <MLabel>

//#define DEBUG
#define WARNING
#include "../debug.h"

static const int MaxColumns = 2;

static const char *oviCommand = "webwidgetrunner /usr/share/webwidgets/applications/d34177b1c241ea44cb132005b63ee6527c9f6040-wrt-widget.desktop -widgetparameter graphics &";

WallpaperWidget::WallpaperWidget (
        WallpaperBusinessLogic *wallpaperBusinessLogic,
        QGraphicsWidget        *parent) :
    DcpWidget (parent),
    m_WallpaperBusinessLogic (wallpaperBusinessLogic)
{
    /*
     * Unfortunatelly the content has to be created late, otherwise the list
     * only shows one row.
     * FIXME: I'm n ot sure how late should this be done, I thing we should use
     * the void MApplicationPage::createContent(), but I don't know how to do
     * that.
     */
    //createContent ();
    QTimer::singleShot(100, this, SLOT(createContent()));
}

WallpaperWidget::~WallpaperWidget ()
{
}

void
WallpaperWidget::createContent ()
{
    MLayout              *layout;
    MLinearLayoutPolicy  *mainLayout;

    /*
     * Creating a layout that holds the rows of the internal widgets.
     */
    layout = new MLayout (this);
    mainLayout = new MLinearLayoutPolicy (layout, Qt::Vertical);
    mainLayout->setContentsMargins (0., 0., 0., 0.);
    mainLayout->setSpacing (0.);
    setLayout (layout);

    /*
     * Adding the header/title
     */
    addHeaderContainer (mainLayout);

    /*
     * The list of the available images.
     */
    m_ImageList = new WallpaperList (m_WallpaperBusinessLogic, this);
    m_ImageList->setObjectName("WallpaperImageList");
    connect (m_ImageList, SIGNAL(imageActivated(WallpaperDescriptor *)),
            this, SLOT(slotImageActivated(WallpaperDescriptor *)));

    m_ImageList->setDataSourceType (WallpaperList::DataSourceLocal);

    /*
     * Adding all widgets into the layout.
     */
    mainLayout->addItem (m_ImageList);
    mainLayout->setStretchFactor (m_ImageList, 1);

    connect (m_WallpaperBusinessLogic, SIGNAL(imageEditRequested()),
            this, SLOT(slotImageActivated()));
}

void
WallpaperWidget::addHeaderContainer (
        MLinearLayoutPolicy *mainLayout)
{
    MContainer            *container;
    QGraphicsLinearLayout *layout;

    Q_ASSERT (mainLayout);

    SYS_DEBUG ("***********************************************************");
    /*
     * Creating a lcontainer and a layout.
     */
    container = new MContainer (this);
    container->setStyleName ("CommonXLargeHeaderPanelInverted");
    container->setHeaderVisible (false);
    container->setContentsMargins (0., 0., 0., 0.);
    //container->setSpacing (0.);

    layout = new QGraphicsLinearLayout (Qt::Horizontal);
    layout->setContentsMargins (0., 0., 0., 0.);
    layout->setSpacing (0.);
    container->centralWidget()->setLayout (layout);

    /*
     * The label that we use as title.
     */
    //% "Wallpaper"
    m_TitleLabel = new MLabel (qtTrId("qtn_wall_wallpaper"));
    m_TitleLabel->setStyleName ("CommonXLargeHeaderInverted");
    layout->addItem (m_TitleLabel);
    layout->setAlignment (m_TitleLabel, Qt::AlignLeft);

    /*
     * Adding the whole row to the main container.
     */
    mainLayout->addItem (container);
    mainLayout->setStretchFactor (container, 0);
}

void
WallpaperWidget::retranslateUi ()
{
    if (m_TitleLabel)
        //% "Wallpaper"
        m_TitleLabel->setText (qtTrId("qtn_wall_wallpaper"));
}

/*
 * This slot is called when the user activates an image in the list. The
 * WallpaperList has a signal for that.
 */
void
WallpaperWidget::slotImageActivated (
        WallpaperDescriptor *desc)
{
    SYS_DEBUG ("*** desc = %s", SYS_STR(desc->basename()));
    m_WallpaperBusinessLogic->startEdit (desc);
}

/*
 * When this slot is activated the image has to be already loaded, so that the
 * editor widget can be shown without delay.
 */
void
WallpaperWidget::slotImageActivated ()
{
    SYS_DEBUG ("");

    emit changeWidget (1);
}

void
WallpaperWidget::oviActivated ()
{
    SYS_DEBUG ("Executing %s", oviCommand);
    system (oviCommand);
}

void
WallpaperWidget::polishEvent ()
{
    QGraphicsWidget  *parent;
    MApplicationPage *page = 0;
    MAction          *action;

    /*
     * We need to find the MApplicationPage among our parents.
     */
    parent = parentWidget();
    while (parent) {
        page = qobject_cast <MApplicationPage *>(parent);
        if (page)
            break;
        parent = parent->parentWidget();
    }

    if (!page)
        return;

    /**************************************************************************
     * Hiding the home button.
     */
    page->setComponentsDisplayMode (
            MApplicationPage::HomeButton,
            MApplicationPageModel::Hide);

    /*
     * Adding the gallery action.
     */
    #ifdef HAVE_CONTENT_MANAGER
    action = new MAction("icon-m-content-gallery", "", this);
    action->setLocation(MAction::ToolBarLocation);
    page->addAction(action);
    connect(action, SIGNAL(triggered()), this, SLOT(galleryActivated()));
    #endif

    /*
     * Adding the ovi action.
     */
    action = new MAction("icon-m-common-ovi", "", this);
    action->setLocation(MAction::ToolBarLocation);
    page->addAction(action);
    connect(action, SIGNAL(triggered()), this, SLOT(oviActivated()));
}

#ifdef HAVE_CONTENT_MANAGER
/*!
 * Slot that is activated when the user clicked on the gallery item, the widget
 * that activates the ContentManager page. We support this only when the
 * ContentManager library is available.
 */
void
WallpaperWidget::galleryActivated ()
{
    /*
     * Please note that the m_ImageBrowser is a QPointer object that will reset
     * itself to NULL when the widget is destroyed. It will also initialize
     * itself to NULL when it is created.
     */
    if (!m_ImageBrowser) {
        m_ImageBrowser = new ContentItemsPage (this);
        m_ImageBrowser->setContentTypes (
          QStringList() <<
            "http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#Image");

        m_ImageBrowser->setObjectName (
                "SelectSingleContentItemPage_imageBrowser");
        m_ImageBrowser->setStyleName ("CommonApplicationPageInverted");
        m_ImageBrowser->setCommonLayoutSuffix ("Inverted");

        connect (m_ImageBrowser, SIGNAL (backButtonClicked ()),
                 m_ImageBrowser, SLOT (dismiss ()));
        connect (m_ImageBrowser, SIGNAL (itemClicked (const QString &)),
                 SLOT (galleryImageSelected (const QString &)));
    }

    m_ImageBrowser->appear (MSceneWindow::DestroyWhenDismissed);
}
#endif

#ifdef HAVE_CONTENT_MANAGER
/*!
 * Slot that activated when the user picks an image from the content manager
 * page. We only need this slot when the ContentManager library is activated.
 */
void
WallpaperWidget::galleryImageSelected (
        const QString &uri)
{
    m_WallpaperBusinessLogic->addImageFromGallery (uri);
    SYS_WARNING ("m_ImageBrowser->unselectItem (%s);", SYS_STR(uri));

    if (m_ImageBrowser)
        m_ImageBrowser->unselectItem (uri);
}
#endif

<|endoftext|>