<commit_before>/******************************************************************************
 *                       ____    _    _____                                   *
 *                      / ___|  / \  |  ___|    C++                           *
 *                     | |     / _ \ | |_       Actor                         *
 *                     | |___ / ___ \|  _|      Framework                     *
 *                      \____/_/   \_|_|                                      *
 *                                                                            *
 * Copyright 2011-2018 Dominik Charousset                                     *
 *                                                                            *
 * Distributed under the terms and conditions of the BSD 3-Clause License or  *
 * (at your option) under the terms and conditions of the Boost Software      *
 * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE.       *
 *                                                                            *
 * If you did not receive a copy of the license files, see                    *
 * http://opensource.org/licenses/BSD-3-Clause and                            *
 * http://www.boost.org/LICENSE_1_0.txt.                                      *
 ******************************************************************************/

#pragma once

#include "caf/config.hpp"
#include "caf/detail/parser/add_ascii.hpp"
#include "caf/detail/parser/chars.hpp"
#include "caf/detail/parser/read_ipv6_address.hpp"
#include "caf/detail/scope_guard.hpp"
#include "caf/pec.hpp"
#include "caf/uri.hpp"

CAF_PUSH_UNUSED_LABEL_WARNING

#include "caf/detail/parser/fsm.hpp"

namespace caf {
namespace detail {
namespace parser {

//   foo://example.com:8042/over/there?name=ferret#nose
//   \_/   \______________/\_________/ \_________/ \__/
//    |           |            |            |        |
// scheme     authority       path        query   fragment
//    |   _____________________|__
//   / \ /                        \.
//   urn:example:animal:ferret:nose

// Unlike our other parsers, the URI parsers only check for validity and
// generate ranges for the subcomponents. URIs can't have linebreaks, so we can
// safely keep track of the position by looking at the column.

template <class State>
void read_uri_percent_encoded(State& ps, std::string& str) {
  uint8_t char_code = 0;
  auto g = make_scope_guard([&] {
    if (ps.code <= pec::trailing_character)
      str += static_cast<char>(char_code);
  });
  // clang-format off
  start();
  state(init) {
    transition(read_nibble, hexadecimal_chars, add_ascii<16>(char_code, ch))
  }
  state(read_nibble) {
    transition(done, hexadecimal_chars, add_ascii<16>(char_code, ch))
  }
  term_state(done) {
    // nop
  }
  fin();
  // clang-format on
}

inline bool uri_unprotected_char(char c) {
  // Consider valid characters not explicitly stated as reserved as unreserved.
  return isprint(c) && !in_whitelist(":/?#[]@!$&'()*+,;=", c);
}

// clang-format off
#define read_next_char(next_state, dest)                                       \
  transition(next_state, uri_unprotected_char, dest += ch)                     \
  fsm_transition(read_uri_percent_encoded(ps, dest), next_state, '%')
// clang-format on

template <class State, class Consumer>
void read_uri_query(State& ps, Consumer&& consumer) {
  // Local variables.
  uri::query_map result;
  std::string key;
  std::string value;
  // Utility functions.
  auto take_str = [&](std::string& str) {
    using std::swap;
    std::string res;
    swap(str, res);
    return res;
  };
  auto push = [&] { result.emplace(take_str(key), take_str(value)); };
  // Call consumer on exit.
  auto g = make_scope_guard([&] {
    if (ps.code <= pec::trailing_character)
      consumer.query(std::move(result));
  });
  // clang-format off
  start();
  // Query may be empty.
  term_state(init) {
    read_next_char(read_key, key)
  }
  state(read_key) {
    read_next_char(read_key, key)
    transition(read_value, '=')
  }
  term_state(read_value, push()) {
    read_next_char(read_value, value)
    transition(init, '&', push())
  }
  fin();
  // clang-format on
}

template <class State, class Consumer>
void read_uri(State& ps, Consumer&& consumer) {
  // Local variables.
  std::string str;
  uint16_t port = 0;
  // Replaces `str` with a default constructed string to make sure we're never
  // operating on a moved-from string object.
  auto take_str = [&] {
    using std::swap;
    std::string res;
    swap(str, res);
    return res;
  };
  // Allowed character sets.
  auto path_char = [](char c) {
    return uri_unprotected_char(c) || c == '/' || c == ':';
  };
  // Utility setters for avoiding code duplication.
  auto set_path = [&] { consumer.path(take_str()); };
  auto set_host = [&] { consumer.host(take_str()); };
  auto set_userinfo = [&] { consumer.userinfo(take_str()); };
  // Consumer for reading IPv6 addresses.
  struct {
    Consumer& f;
    void value(ipv6_address addr) {
      f.host(addr);
    }
  } ip_consumer{consumer};
  // clang-format off
  start();
  state(init) {
    epsilon(read_scheme)
  }
  state(read_scheme) {
    read_next_char(read_scheme, str)
    transition(have_scheme, ':', consumer.scheme(take_str()))
  }
  state(have_scheme) {
    transition(disambiguate_path, '/')
    read_next_char(read_path, str)
    fsm_transition(read_uri_percent_encoded(ps, str), read_path, '%')
  }
  // This state is terminal, because "file:/" is a valid URI.
  term_state(disambiguate_path, consumer.path("/")) {
    transition(start_authority, '/')
    epsilon(read_path, any_char, str += '/')
  }
  state(start_authority) {
    // A third '/' skips the authority, e.g., "file:///".
    transition(read_path, '/', str += '/')
    read_next_char(read_authority, str)
    fsm_transition(read_ipv6_address(ps, ip_consumer), await_end_of_ipv6, '[')
  }
  state(await_end_of_ipv6) {
    transition(end_of_ipv6_host, ']')
  }
  term_state(end_of_ipv6_host) {
    transition(start_port, ':')
    epsilon(end_of_authority)
  }
  term_state(end_of_host) {
    transition(start_port, ':', set_host())
    epsilon(end_of_authority, "/?#", set_host())
  }
  term_state(read_authority, set_host()) {
    read_next_char(read_authority, str)
    transition(start_host, '@', set_userinfo())
    transition(start_port, ':', set_host())
    epsilon(end_of_authority, "/?#", set_host())
  }
  state(start_host) {
    read_next_char(read_host, str)
    fsm_transition(read_ipv6_address(ps, ip_consumer), await_end_of_ipv6, '[')
  }
  term_state(read_host, set_host()) {
    read_next_char(read_host, str)
    transition(start_port, ':', set_host())
    epsilon(end_of_authority, "/?#", set_host())
  }
  state(start_port) {
    transition(read_port, decimal_chars, add_ascii<10>(port, ch))
  }
  term_state(read_port, consumer.port(port)) {
    transition(read_port, decimal_chars, add_ascii<10>(port, ch),
               pec::integer_overflow)
    epsilon(end_of_authority, "/?#", consumer.port(port))
  }
  term_state(end_of_authority) {
    transition(read_path, '/')
    transition(start_query, '?')
    transition(read_fragment, '#')
  }
  term_state(read_path, set_path()) {
    transition(read_path, path_char, str += ch)
    fsm_transition(read_uri_percent_encoded(ps, str), read_path, '%')
    transition(start_query, '?', set_path())
    transition(read_fragment, '#', set_path())
  }
  term_state(start_query) {
    fsm_epsilon(read_uri_query(ps, consumer), end_of_query)
  }
  unstable_state(end_of_query) {
    transition(read_fragment, '#')
    epsilon(done)
  }
  term_state(read_fragment, consumer.fragment(take_str())) {
    read_next_char(read_fragment, str)
  }
  term_state(done) {
    // nop
  }
  fin();
  // clang-format on
}

} // namespace parser
} // namespace detail
} // namespace caf

#include "caf/detail/parser/fsm_undef.hpp"

CAF_POP_WARNINGS
<commit_msg>Consider < and > as reserved characters in URIs<commit_after>/******************************************************************************
 *                       ____    _    _____                                   *
 *                      / ___|  / \  |  ___|    C++                           *
 *                     | |     / _ \ | |_       Actor                         *
 *                     | |___ / ___ \|  _|      Framework                     *
 *                      \____/_/   \_|_|                                      *
 *                                                                            *
 * Copyright 2011-2018 Dominik Charousset                                     *
 *                                                                            *
 * Distributed under the terms and conditions of the BSD 3-Clause License or  *
 * (at your option) under the terms and conditions of the Boost Software      *
 * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE.       *
 *                                                                            *
 * If you did not receive a copy of the license files, see                    *
 * http://opensource.org/licenses/BSD-3-Clause and                            *
 * http://www.boost.org/LICENSE_1_0.txt.                                      *
 ******************************************************************************/

#pragma once

#include "caf/config.hpp"
#include "caf/detail/parser/add_ascii.hpp"
#include "caf/detail/parser/chars.hpp"
#include "caf/detail/parser/read_ipv6_address.hpp"
#include "caf/detail/scope_guard.hpp"
#include "caf/pec.hpp"
#include "caf/uri.hpp"

CAF_PUSH_UNUSED_LABEL_WARNING

#include "caf/detail/parser/fsm.hpp"

namespace caf {
namespace detail {
namespace parser {

//   foo://example.com:8042/over/there?name=ferret#nose
//   \_/   \______________/\_________/ \_________/ \__/
//    |           |            |            |        |
// scheme     authority       path        query   fragment
//    |   _____________________|__
//   / \ /                        \.
//   urn:example:animal:ferret:nose

// Unlike our other parsers, the URI parsers only check for validity and
// generate ranges for the subcomponents. URIs can't have linebreaks, so we can
// safely keep track of the position by looking at the column.

template <class State>
void read_uri_percent_encoded(State& ps, std::string& str) {
  uint8_t char_code = 0;
  auto g = make_scope_guard([&] {
    if (ps.code <= pec::trailing_character)
      str += static_cast<char>(char_code);
  });
  // clang-format off
  start();
  state(init) {
    transition(read_nibble, hexadecimal_chars, add_ascii<16>(char_code, ch))
  }
  state(read_nibble) {
    transition(done, hexadecimal_chars, add_ascii<16>(char_code, ch))
  }
  term_state(done) {
    // nop
  }
  fin();
  // clang-format on
}

inline bool uri_unprotected_char(char c) {
  // Consider valid characters not explicitly stated as reserved as unreserved.
  return isprint(c) && !in_whitelist(":/?#[]@!$&'()*+,;=<>", c);
}

// clang-format off
#define read_next_char(next_state, dest)                                       \
  transition(next_state, uri_unprotected_char, dest += ch)                     \
  fsm_transition(read_uri_percent_encoded(ps, dest), next_state, '%')
// clang-format on

template <class State, class Consumer>
void read_uri_query(State& ps, Consumer&& consumer) {
  // Local variables.
  uri::query_map result;
  std::string key;
  std::string value;
  // Utility functions.
  auto take_str = [&](std::string& str) {
    using std::swap;
    std::string res;
    swap(str, res);
    return res;
  };
  auto push = [&] { result.emplace(take_str(key), take_str(value)); };
  // Call consumer on exit.
  auto g = make_scope_guard([&] {
    if (ps.code <= pec::trailing_character)
      consumer.query(std::move(result));
  });
  // clang-format off
  start();
  // Query may be empty.
  term_state(init) {
    read_next_char(read_key, key)
  }
  state(read_key) {
    read_next_char(read_key, key)
    transition(read_value, '=')
  }
  term_state(read_value, push()) {
    read_next_char(read_value, value)
    transition(init, '&', push())
  }
  fin();
  // clang-format on
}

template <class State, class Consumer>
void read_uri(State& ps, Consumer&& consumer) {
  // Local variables.
  std::string str;
  uint16_t port = 0;
  // Replaces `str` with a default constructed string to make sure we're never
  // operating on a moved-from string object.
  auto take_str = [&] {
    using std::swap;
    std::string res;
    swap(str, res);
    return res;
  };
  // Allowed character sets.
  auto path_char = [](char c) {
    return uri_unprotected_char(c) || c == '/' || c == ':';
  };
  // Utility setters for avoiding code duplication.
  auto set_path = [&] { consumer.path(take_str()); };
  auto set_host = [&] { consumer.host(take_str()); };
  auto set_userinfo = [&] { consumer.userinfo(take_str()); };
  // Consumer for reading IPv6 addresses.
  struct {
    Consumer& f;
    void value(ipv6_address addr) {
      f.host(addr);
    }
  } ip_consumer{consumer};
  // clang-format off
  start();
  state(init) {
    epsilon(read_scheme)
  }
  state(read_scheme) {
    read_next_char(read_scheme, str)
    transition(have_scheme, ':', consumer.scheme(take_str()))
  }
  state(have_scheme) {
    transition(disambiguate_path, '/')
    read_next_char(read_path, str)
    fsm_transition(read_uri_percent_encoded(ps, str), read_path, '%')
  }
  // This state is terminal, because "file:/" is a valid URI.
  term_state(disambiguate_path, consumer.path("/")) {
    transition(start_authority, '/')
    epsilon(read_path, any_char, str += '/')
  }
  state(start_authority) {
    // A third '/' skips the authority, e.g., "file:///".
    transition(read_path, '/', str += '/')
    read_next_char(read_authority, str)
    fsm_transition(read_ipv6_address(ps, ip_consumer), await_end_of_ipv6, '[')
  }
  state(await_end_of_ipv6) {
    transition(end_of_ipv6_host, ']')
  }
  term_state(end_of_ipv6_host) {
    transition(start_port, ':')
    epsilon(end_of_authority)
  }
  term_state(end_of_host) {
    transition(start_port, ':', set_host())
    epsilon(end_of_authority, "/?#", set_host())
  }
  term_state(read_authority, set_host()) {
    read_next_char(read_authority, str)
    transition(start_host, '@', set_userinfo())
    transition(start_port, ':', set_host())
    epsilon(end_of_authority, "/?#", set_host())
  }
  state(start_host) {
    read_next_char(read_host, str)
    fsm_transition(read_ipv6_address(ps, ip_consumer), await_end_of_ipv6, '[')
  }
  term_state(read_host, set_host()) {
    read_next_char(read_host, str)
    transition(start_port, ':', set_host())
    epsilon(end_of_authority, "/?#", set_host())
  }
  state(start_port) {
    transition(read_port, decimal_chars, add_ascii<10>(port, ch))
  }
  term_state(read_port, consumer.port(port)) {
    transition(read_port, decimal_chars, add_ascii<10>(port, ch),
               pec::integer_overflow)
    epsilon(end_of_authority, "/?#", consumer.port(port))
  }
  term_state(end_of_authority) {
    transition(read_path, '/')
    transition(start_query, '?')
    transition(read_fragment, '#')
  }
  term_state(read_path, set_path()) {
    transition(read_path, path_char, str += ch)
    fsm_transition(read_uri_percent_encoded(ps, str), read_path, '%')
    transition(start_query, '?', set_path())
    transition(read_fragment, '#', set_path())
  }
  term_state(start_query) {
    fsm_epsilon(read_uri_query(ps, consumer), end_of_query)
  }
  unstable_state(end_of_query) {
    transition(read_fragment, '#')
    epsilon(done)
  }
  term_state(read_fragment, consumer.fragment(take_str())) {
    read_next_char(read_fragment, str)
  }
  term_state(done) {
    // nop
  }
  fin();
  // clang-format on
}

} // namespace parser
} // namespace detail
} // namespace caf

#include "caf/detail/parser/fsm_undef.hpp"

CAF_POP_WARNINGS
<|endoftext|>


<commit_before>#include "lib/marisa/trie.h"
#include "emscripten.h"

#include "js-marisa.h"
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <iostream>
#include <memory.h>
#include <stdarg.h>
#include <stdio.h>
#include <sys/stat.h>

using namespace std;

long EMSCRIPTEN_KEEPALIVE push_trie(int length, int* int_trie_bytes) {

    EM_ASM(
        FS.mkdir('/IDBFS');
        FS.mount(IDBFS, {}, '/IDBFS');
    );

    FILE *fp;
    fp = fopen("/IDBFS/demo.record_trie", "w");
    char* bytes = (char *) int_trie_bytes;
    size_t wrote_bytes = fwrite(bytes, 1, length, fp);
    fclose(fp);
    printf("Wrote out %d bytes in c/emscripten land.\n", wrote_bytes);

    marisa::RecordTrie* _rtrie = new marisa::RecordTrie();
    printf("Setting format\n");
    _rtrie->setFormat(">iii");
    printf("Tring to MMAP\n");
    _rtrie->mmap("/IDBFS/demo.record_trie");
    cout << "MMAP'd the demo.record_trie\n";

    cout << (long) _rtrie << " C++ pointer location\n";
    return (long) _rtrie;
}

// This is the main entry point where we pass in a pointer to the
// record trie and a string delimited by | characters
// The return value is written into the result char*.
// If no valid result exists, then we write a null into the first byte
// of the result
char* EMSCRIPTEN_KEEPALIVE trie_lookup(long rtrie_handle, const char* bssid_list) {

    static char resultBuf[2000] = {0};

    marisa::RecordTrie* _rtrie = (marisa::RecordTrie*) rtrie_handle;
    printf("Read: [%s]\n", bssid_list);

    printf("Calling trie_lookup\n");
    vector<marisa::Record> results;

    std::string bssids  = std::string(bssid_list);
    std::string delimiter = "|";

    size_t pos = 0;
    std::string token;
    while ((pos = bssids.find(delimiter)) != std::string::npos) {
        token = bssids.substr(0, pos);
        printf("(ignored) Looking up result for : [%s]\n", token.c_str());
        _rtrie->getRecord(&results, token.c_str());
        printf("[%s] results object length: %d\n", token.c_str(), results.size());
        for(vector<marisa::Record>::const_iterator i = results.begin(); i != results.end(); i++) {
            marisa::Record rec = *i;
            int* int_tuple = rec.getIntTuple();

            for (int i=0; i < 100; i++) {
                printf("index[%d]=%d\n", i, int_tuple[i]);
                if (int_tuple[i] == -1) {
                    break;
                }

                sprintf(resultBuf+strlen(resultBuf), ", %d", int_tuple[i]);
            }
            sprintf(resultBuf+strlen(resultBuf), ")\n");
        }
        bssids.erase(0, pos + delimiter.length());
    }

    printf("Returning [%s]\n", resultBuf);
    return resultBuf;
}

<commit_msg>dropped noisey logs<commit_after>#include "lib/marisa/trie.h"
#include "emscripten.h"

#include "js-marisa.h"
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <iostream>
#include <memory.h>
#include <stdarg.h>
#include <stdio.h>
#include <sys/stat.h>

using namespace std;

long EMSCRIPTEN_KEEPALIVE push_trie(int length, int* int_trie_bytes) {

    EM_ASM(
        FS.mkdir('/IDBFS');
        FS.mount(IDBFS, {}, '/IDBFS');
    );

    FILE *fp;
    fp = fopen("/IDBFS/demo.record_trie", "w");
    char* bytes = (char *) int_trie_bytes;
    size_t wrote_bytes = fwrite(bytes, 1, length, fp);
    fclose(fp);
    printf("Wrote out %d bytes in c/emscripten land.\n", wrote_bytes);

    marisa::RecordTrie* _rtrie = new marisa::RecordTrie();
    printf("Setting format\n");
    _rtrie->setFormat(">iii");
    printf("Tring to MMAP\n");
    _rtrie->mmap("/IDBFS/demo.record_trie");
    cout << "MMAP'd the demo.record_trie\n";

    cout << (long) _rtrie << " C++ pointer location\n";
    return (long) _rtrie;
}

// This is the main entry point where we pass in a pointer to the
// record trie and a string delimited by | characters
// The return value is written into the result char*.
// If no valid result exists, then we write a null into the first byte
// of the result
char* EMSCRIPTEN_KEEPALIVE trie_lookup(long rtrie_handle, const char* bssid_list) {

    static char resultBuf[10000] = {0};

    marisa::RecordTrie* _rtrie = (marisa::RecordTrie*) rtrie_handle;
    printf("Read: [%s]\n", bssid_list);

    printf("Calling trie_lookup\n");
    vector<marisa::Record> results;

    std::string bssids  = std::string(bssid_list);
    std::string delimiter = "|";

    size_t pos = 0;
    std::string token;
    while ((pos = bssids.find(delimiter)) != std::string::npos) {
        token = bssids.substr(0, pos);
        printf("(ignored) Looking up result for : [%s]\n", token.c_str());
        _rtrie->getRecord(&results, token.c_str());
        printf("[%s] results object length: %d\n", token.c_str(), results.size());
        for(vector<marisa::Record>::const_iterator i = results.begin(); i != results.end(); i++) {
            marisa::Record rec = *i;
            int* int_tuple = rec.getIntTuple();

            for (int i=0; i < 100; i++) {
                if (int_tuple[i] == -1) {
                    break;
                }

                if (strlen(resultBuf) == 0) {
                    sprintf(resultBuf+strlen(resultBuf), "%d", int_tuple[i]);
                }
                else {
                    sprintf(resultBuf+strlen(resultBuf), "|%d", int_tuple[i]);
                }
            }
        }
        bssids.erase(0, pos + delimiter.length());
    }

    printf("Returning [%s]\n", resultBuf);
    return resultBuf;
}

<|endoftext|>


<commit_before>#include <cstdio>
#include <cstdlib>

#include <LibUtilities/Memory/NekMemoryManager.hpp>
#include <LibUtilities/BasicUtils/SessionReader.h>
#include <LibUtilities/Communication/Comm.h>
#include <MultiRegions/ContField2D.h>
#include <SpatialDomains/MeshGraph2D.h>

using namespace Nektar;

//#define TIMING
#ifdef TIMING
#include <time.h>
#define Timing(s) \
 fprintf(stdout,"%s Took %g seconds\n",s,(clock()-st)/cps); \
 st = clock();
#else
#define Timing(s) \
 /* Nothing */
#endif

int NoCaseStringCompare(const string & s1, const string& s2);

int main(int argc, char *argv[])
{
    LibUtilities::SessionReaderSharedPtr vSession
            = LibUtilities::SessionReader::CreateInstance(argc, argv);

    MultiRegions::ContField2DSharedPtr Exp,Fce;
    int     i, nq,  coordim;
    Array<OneD,NekDouble>  fce;
    Array<OneD,NekDouble>  xc0,xc1,xc2;
    StdRegions::ConstFactorMap factors;
    StdRegions::VarCoeffMap varcoeffs;
    FlagList flags;
    NekDouble    cps = (double)CLOCKS_PER_SEC;
    NekDouble    st;

    if( (argc != 2) && (argc != 3) && (argc != 4))
    {
        fprintf(stderr,"Usage: Helmholtz2D meshfile [SysSolnType]   or   \n");
        exit(1);
    }

    try
    {
        //----------------------------------------------
        // Read in mesh from input file
        SpatialDomains::MeshGraphSharedPtr graph2D = MemoryManager<SpatialDomains::MeshGraph2D>::AllocateSharedPtr(vSession);
        //----------------------------------------------

        //----------------------------------------------
        // Print summary of solution details
        flags.set(eUseGlobal, true);
        factors[StdRegions::eFactorLambda] = vSession->GetParameter("Lambda");
        const SpatialDomains::ExpansionMap &expansions = graph2D->GetExpansions();
        LibUtilities::BasisKey bkey0 = expansions.begin()->second->m_basisKeyVector[0];
        cout << "Solving 2D Helmholtz: " << endl;
        cout << "         Communication: " << vSession->GetComm()->GetType() << endl;
        cout << "         Solver type  : " << vSession->GetSolverInfo("GlobalSysSoln") << endl;
        cout << "         Lambda       : " << factors[StdRegions::eFactorLambda] << endl;
        cout << "         No. modes    : " << bkey0.GetNumModes() << endl;
        cout << endl;
        //----------------------------------------------

        //----------------------------------------------
        // Define Expansion
        Exp = MemoryManager<MultiRegions::ContField2D>::
            AllocateSharedPtr(vSession,graph2D,vSession->GetVariable(0));
        //----------------------------------------------

        Timing("Read files and define exp ..");

        //----------------------------------------------
        // Set up coordinates of mesh for Forcing function evaluation
        coordim = Exp->GetCoordim(0);
        nq      = Exp->GetTotPoints();

        xc0 = Array<OneD,NekDouble>(nq,0.0);
        xc1 = Array<OneD,NekDouble>(nq,0.0);
        xc2 = Array<OneD,NekDouble>(nq,0.0);

        switch(coordim)
        {
        case 2:
            Exp->GetCoords(xc0,xc1);
            break;
        case 3:
            Exp->GetCoords(xc0,xc1,xc2);
            break;
        default:
            ASSERTL0(false,"Coordim not valid");
            break;
        }
        //----------------------------------------------

        //----------------------------------------------
        // Set up variable coefficients if defined
        if (vSession->DefinesFunction("d00"))
        {
            Array<OneD, NekDouble> d00(nq,0.0);
            LibUtilities::EquationSharedPtr d00func = vSession->GetFunction("d00",0);
            d00func->Evaluate(xc0, xc1, xc2, d00);
            varcoeffs[StdRegions::eVarCoeffD00] = d00;
        }
        if (vSession->DefinesFunction("d11"))
        {
            Array<OneD, NekDouble> d11(nq,0.0);
            LibUtilities::EquationSharedPtr d11func = vSession->GetFunction("d11",0);
            d11func->Evaluate(xc0, xc1, xc2, d11);
            varcoeffs[StdRegions::eVarCoeffD11] = d11;
        }
        //----------------------------------------------

        //----------------------------------------------
        // Define forcing function for first variable defined in file
        fce = Array<OneD,NekDouble>(nq);
        LibUtilities::EquationSharedPtr ffunc = vSession->GetFunction("Forcing",0);
        ffunc->Evaluate(xc0, xc1, xc2, fce);

        //----------------------------------------------

        //----------------------------------------------
        // Setup expansion containing the  forcing function
        Fce = MemoryManager<MultiRegions::ContField2D>::AllocateSharedPtr(*Exp);
        Fce->SetPhys(fce);
        //----------------------------------------------
        Timing("Define forcing ..");

        //----------------------------------------------
        //Helmholtz solution taking physical forcing after setting
        //initial condition to zero
        Vmath::Zero(Exp->GetNcoeffs(),Exp->UpdateCoeffs(),1);
        Exp->HelmSolve(Fce->GetPhys(), Exp->UpdateCoeffs(), flags, factors, varcoeffs);
        //----------------------------------------------
        Timing("Helmholtz Solve ..");

#ifdef TIMING
        for(i = 0; i < 1000; ++i)
        {
            Exp->HelmSolve(Fce->GetPhys(), Exp->UpdateCoeffs(), flags, factors, varcoeffs);
        }

        Timing("1000 Helmholtz Solves:... ");
#endif

        //----------------------------------------------
        // Backward Transform Solution to get solved values
        Exp->BwdTrans(Exp->GetCoeffs(), Exp->UpdatePhys(), MultiRegions::eGlobal);
        //----------------------------------------------

        //-----------------------------------------------
        // Write solution to file
        string   out(vSession->GetSessionName() + ".fld");
        if (vSession->GetComm()->GetSize() > 1)
        {
            out += "." + boost::lexical_cast<string>(vSession->GetComm()->GetRank());
        }
        std::vector<SpatialDomains::FieldDefinitionsSharedPtr> FieldDef
                                                    = Exp->GetFieldDefinitions();
        std::vector<std::vector<NekDouble> > FieldData(FieldDef.size());

        Exp->GlobalToLocal(Exp->GetCoeffs(),Exp->UpdateCoeffs());
        for(i = 0; i < FieldDef.size(); ++i)
        {
            FieldDef[i]->m_fields.push_back("u");
            Exp->AppendFieldData(FieldDef[i], FieldData[i]);
        }
        graph2D->Write(out, FieldDef, FieldData);
        //-----------------------------------------------

        //----------------------------------------------
        // See if there is an exact solution, if so
        // evaluate and plot errors
        LibUtilities::EquationSharedPtr ex_sol = vSession->GetFunction("ExactSolution",0);

        if(ex_sol)
        {
            //----------------------------------------------
            // evaluate exact solution
            ex_sol->Evaluate(xc0, xc1, xc2, fce);

            Fce->SetPhys(fce);
            Fce->SetPhysState(true);
            //--------------------------------------------

            //--------------------------------------------
            // Calculate errors
            NekDouble vLinfError = Exp->Linf(Fce->GetPhys());
            NekDouble vL2Error   = Exp->L2(Fce->GetPhys());
            NekDouble vH1Error   = Exp->H1(Fce->GetPhys());
            if (vSession->GetComm()->GetRank() == 0)
            {
                cout << "L infinity error: " << vLinfError << endl;
                cout << "L 2 error:        " << vL2Error << endl;
                cout << "H 1 error:        " << vH1Error << endl;
            }
            //--------------------------------------------

        }
        //----------------------------------------------
    }
    catch (const std::runtime_error&)
    {
        cout << "Caught an error" << endl;
        return 1;
    }

    vSession->Finalise();

    return 0;
}

/**
 * Performs a case-insensitive string comparison (from web).
 * @param   s1          First string to compare.
 * @param   s2          Second string to compare.
 * @returns             0 if the strings match.
 */
int NoCaseStringCompare(const string & s1, const string& s2)
{
    string::const_iterator it1=s1.begin();
    string::const_iterator it2=s2.begin();

    //stop when either string's end has been reached
    while ( (it1!=s1.end()) && (it2!=s2.end()) )
    {
        if(::toupper(*it1) != ::toupper(*it2)) //letters differ?
        {
            // return -1 to indicate smaller than, 1 otherwise
            return (::toupper(*it1)  < ::toupper(*it2)) ? -1 : 1;
        }

        //proceed to the next character in each string
        ++it1;
        ++it2;
    }

    size_t size1=s1.size();
    size_t size2=s2.size();// cache lengths

    //return -1,0 or 1 according to strings' lengths
    if (size1==size2)
    {
        return 0;
    }

    return (size1 < size2) ? -1 : 1;
}

<commit_msg>Measuring 20 Helmholves in 2D<commit_after>#include <cstdio>
#include <cstdlib>

#include <LibUtilities/Memory/NekMemoryManager.hpp>
#include <LibUtilities/BasicUtils/SessionReader.h>
#include <LibUtilities/Communication/Comm.h>
#include <MultiRegions/ContField2D.h>
#include <SpatialDomains/MeshGraph2D.h>

using namespace Nektar;

#define TIMING
#ifdef TIMING
#include <time.h>
#define Timing(s) \
 fprintf(stdout,"%s Took %g seconds\n",s,(clock()-st)/cps); \
 st = clock();
#else
#define Timing(s) \
 /* Nothing */
#endif

int NoCaseStringCompare(const string & s1, const string& s2);

int main(int argc, char *argv[])
{
    LibUtilities::SessionReaderSharedPtr vSession
            = LibUtilities::SessionReader::CreateInstance(argc, argv);

    MultiRegions::ContField2DSharedPtr Exp,Fce;
    int     i, nq,  coordim;
    Array<OneD,NekDouble>  fce;
    Array<OneD,NekDouble>  xc0,xc1,xc2;
    StdRegions::ConstFactorMap factors;
    StdRegions::VarCoeffMap varcoeffs;
    FlagList flags;
    NekDouble    cps = (double)CLOCKS_PER_SEC;
    NekDouble    st;

    if( (argc != 2) && (argc != 3) && (argc != 4))
    {
        fprintf(stderr,"Usage: Helmholtz2D meshfile [SysSolnType]   or   \n");
        exit(1);
    }

    try
    {
        //----------------------------------------------
        // Read in mesh from input file
        SpatialDomains::MeshGraphSharedPtr graph2D = MemoryManager<SpatialDomains::MeshGraph2D>::AllocateSharedPtr(vSession);
        //----------------------------------------------

        //----------------------------------------------
        // Print summary of solution details
        flags.set(eUseGlobal, true);
        factors[StdRegions::eFactorLambda] = vSession->GetParameter("Lambda");
        const SpatialDomains::ExpansionMap &expansions = graph2D->GetExpansions();
        LibUtilities::BasisKey bkey0 = expansions.begin()->second->m_basisKeyVector[0];
        cout << "Solving 2D Helmholtz: " << endl;
        cout << "         Communication: " << vSession->GetComm()->GetType() << endl;
        cout << "         Solver type  : " << vSession->GetSolverInfo("GlobalSysSoln") << endl;
        cout << "         Lambda       : " << factors[StdRegions::eFactorLambda] << endl;
        cout << "         No. modes    : " << bkey0.GetNumModes() << endl;
        cout << endl;
        //----------------------------------------------

        //----------------------------------------------
        // Define Expansion
        Exp = MemoryManager<MultiRegions::ContField2D>::
            AllocateSharedPtr(vSession,graph2D,vSession->GetVariable(0));
        //----------------------------------------------

        Timing("Read files and define exp ..");

        //----------------------------------------------
        // Set up coordinates of mesh for Forcing function evaluation
        coordim = Exp->GetCoordim(0);
        nq      = Exp->GetTotPoints();

        xc0 = Array<OneD,NekDouble>(nq,0.0);
        xc1 = Array<OneD,NekDouble>(nq,0.0);
        xc2 = Array<OneD,NekDouble>(nq,0.0);

        switch(coordim)
        {
        case 2:
            Exp->GetCoords(xc0,xc1);
            break;
        case 3:
            Exp->GetCoords(xc0,xc1,xc2);
            break;
        default:
            ASSERTL0(false,"Coordim not valid");
            break;
        }
        //----------------------------------------------

        //----------------------------------------------
        // Set up variable coefficients if defined
        if (vSession->DefinesFunction("d00"))
        {
            Array<OneD, NekDouble> d00(nq,0.0);
            LibUtilities::EquationSharedPtr d00func = vSession->GetFunction("d00",0);
            d00func->Evaluate(xc0, xc1, xc2, d00);
            varcoeffs[StdRegions::eVarCoeffD00] = d00;
        }
        if (vSession->DefinesFunction("d11"))
        {
            Array<OneD, NekDouble> d11(nq,0.0);
            LibUtilities::EquationSharedPtr d11func = vSession->GetFunction("d11",0);
            d11func->Evaluate(xc0, xc1, xc2, d11);
            varcoeffs[StdRegions::eVarCoeffD11] = d11;
        }
        //----------------------------------------------

        //----------------------------------------------
        // Define forcing function for first variable defined in file
        fce = Array<OneD,NekDouble>(nq);
        LibUtilities::EquationSharedPtr ffunc = vSession->GetFunction("Forcing",0);
        ffunc->Evaluate(xc0, xc1, xc2, fce);

        //----------------------------------------------

        //----------------------------------------------
        // Setup expansion containing the  forcing function
        Fce = MemoryManager<MultiRegions::ContField2D>::AllocateSharedPtr(*Exp);
        Fce->SetPhys(fce);
        //----------------------------------------------
        Timing("Define forcing ..");

        //----------------------------------------------
        //Helmholtz solution taking physical forcing after setting
        //initial condition to zero
        Vmath::Zero(Exp->GetNcoeffs(),Exp->UpdateCoeffs(),1);
        Exp->HelmSolve(Fce->GetPhys(), Exp->UpdateCoeffs(), flags, factors, varcoeffs);
        //----------------------------------------------
        Timing("Helmholtz Solve ..");

#ifdef TIMING
        for(i = 0; i < 20; ++i)
        {
            Exp->HelmSolve(Fce->GetPhys(), Exp->UpdateCoeffs(), flags, factors, varcoeffs);
        }

        Timing("1000 Helmholtz Solves:... ");
#endif

        //----------------------------------------------
        // Backward Transform Solution to get solved values
        Exp->BwdTrans(Exp->GetCoeffs(), Exp->UpdatePhys(), MultiRegions::eGlobal);
        //----------------------------------------------

        //-----------------------------------------------
        // Write solution to file
        string   out(vSession->GetSessionName() + ".fld");
        if (vSession->GetComm()->GetSize() > 1)
        {
            out += "." + boost::lexical_cast<string>(vSession->GetComm()->GetRank());
        }
        std::vector<SpatialDomains::FieldDefinitionsSharedPtr> FieldDef
                                                    = Exp->GetFieldDefinitions();
        std::vector<std::vector<NekDouble> > FieldData(FieldDef.size());

        Exp->GlobalToLocal(Exp->GetCoeffs(),Exp->UpdateCoeffs());
        for(i = 0; i < FieldDef.size(); ++i)
        {
            FieldDef[i]->m_fields.push_back("u");
            Exp->AppendFieldData(FieldDef[i], FieldData[i]);
        }
        graph2D->Write(out, FieldDef, FieldData);
        //-----------------------------------------------

        //----------------------------------------------
        // See if there is an exact solution, if so
        // evaluate and plot errors
        LibUtilities::EquationSharedPtr ex_sol = vSession->GetFunction("ExactSolution",0);

        if(ex_sol)
        {
            //----------------------------------------------
            // evaluate exact solution
            ex_sol->Evaluate(xc0, xc1, xc2, fce);

            Fce->SetPhys(fce);
            Fce->SetPhysState(true);
            //--------------------------------------------

            //--------------------------------------------
            // Calculate errors
            NekDouble vLinfError = Exp->Linf(Fce->GetPhys());
            NekDouble vL2Error   = Exp->L2(Fce->GetPhys());
            NekDouble vH1Error   = Exp->H1(Fce->GetPhys());
            if (vSession->GetComm()->GetRank() == 0)
            {
                cout << "L infinity error: " << vLinfError << endl;
                cout << "L 2 error:        " << vL2Error << endl;
                cout << "H 1 error:        " << vH1Error << endl;
            }
            //--------------------------------------------

        }
        //----------------------------------------------
    }
    catch (const std::runtime_error&)
    {
        cout << "Caught an error" << endl;
        return 1;
    }

    vSession->Finalise();

    return 0;
}

/**
 * Performs a case-insensitive string comparison (from web).
 * @param   s1          First string to compare.
 * @param   s2          Second string to compare.
 * @returns             0 if the strings match.
 */
int NoCaseStringCompare(const string & s1, const string& s2)
{
    string::const_iterator it1=s1.begin();
    string::const_iterator it2=s2.begin();

    //stop when either string's end has been reached
    while ( (it1!=s1.end()) && (it2!=s2.end()) )
    {
        if(::toupper(*it1) != ::toupper(*it2)) //letters differ?
        {
            // return -1 to indicate smaller than, 1 otherwise
            return (::toupper(*it1)  < ::toupper(*it2)) ? -1 : 1;
        }

        //proceed to the next character in each string
        ++it1;
        ++it2;
    }

    size_t size1=s1.size();
    size_t size2=s2.size();// cache lengths

    //return -1,0 or 1 according to strings' lengths
    if (size1==size2)
    {
        return 0;
    }

    return (size1 < size2) ? -1 : 1;
}

<|endoftext|>


<commit_before>#include "StaticImageRenderer.h"
#include "CommandLineArguments.h"

#include <iostream>
#include <fstream>
#include <string>
#include <thread>
#include <chrono>
#include <atomic>

PH_CLI_NAMESPACE_BEGIN

StaticImageRenderer::StaticImageRenderer(const CommandLineArguments& args) :
	m_engineId(0),
	m_sceneFilePath(args.getSceneFilePath()),
	m_imageFilePath(args.getImageFilePath()),
	m_numRenderThreads(args.getNumRenderThreads()),
	m_performPostProcessing(args.performPostPorcess())
{
	phCreateEngine(&m_engineId, static_cast<PHuint32>(m_numRenderThreads));
}

void StaticImageRenderer::render() const
{
	if(!loadCommandsFromSceneFile())
	{
		return;
	}

	phUpdate(m_engineId);

	std::thread renderThread([=]()
	{
		phRender(m_engineId);
	});

	std::atomic<bool> isRenderingCompleted = false;
	std::thread queryThread([&]()
	{
		/*PHuint32 x, y, w, h;
		int regionStatus = phAsyncPollUpdatedFilmRegion(engineId, &x, &y, &w, &h);
		if(regionStatus != PH_FILM_REGION_STATUS_INVALID)
		{
			std::cout << "xywh: " << x << ", " << y << ", " << w << ", " << h << std::endl;
		}*/

		using namespace std::chrono_literals;

		PHfloat32 currentProgress = 0, samplesPerSecond = 0;
		PHfloat32 lastProgress = 0;
		while(!isRenderingCompleted)
		{
			phAsyncGetRendererStatistics(m_engineId, &currentProgress, &samplesPerSecond);

			if((currentProgress - lastProgress) > 1.0f)
			{
				lastProgress = currentProgress;
				std::cout << "progress: " << currentProgress << " % | "
				          << "samples/sec: " << samplesPerSecond << std::endl;
			}

			std::this_thread::sleep_for(2s);
		}
	});

	renderThread.join();
	isRenderingCompleted = true;

	PHuint32 filmWpx, filmHpx;
	phGetFilmDimension(m_engineId, &filmWpx, &filmHpx);

	PHuint64 frameId;
	phCreateFrame(&frameId, filmWpx, filmHpx);
	if(m_performPostProcessing)
	{
		phDevelopFilm(m_engineId, frameId);
	}
	else
	{
		phDevelopFilmRaw(m_engineId, frameId);
	}
	phSaveFrame(frameId, m_imageFilePath.c_str());

	std::cout << "render completed, image saved to <" << m_imageFilePath << ">" << std::endl;
}

bool StaticImageRenderer::loadCommandsFromSceneFile() const
{
	std::ifstream sceneFile;
	sceneFile.open(m_sceneFilePath, std::ios::in);
	if(!sceneFile.is_open())
	{
		std::cerr << "warning: scene file <" << m_sceneFilePath << "> opening failed" << std::endl;
		return false;
	}
	else
	{
		std::string lineCommand;
		while(sceneFile.good())
		{
			std::getline(sceneFile, lineCommand);
			lineCommand += '\n';
			phEnterCommand(m_engineId, lineCommand.c_str());
		}
		phEnterCommand(m_engineId, "->");
	}
}

PH_CLI_NAMESPACE_END<commit_msg>[bugfix] join query thread<commit_after>#include "StaticImageRenderer.h"
#include "CommandLineArguments.h"

#include <iostream>
#include <fstream>
#include <string>
#include <thread>
#include <chrono>
#include <atomic>

PH_CLI_NAMESPACE_BEGIN

StaticImageRenderer::StaticImageRenderer(const CommandLineArguments& args) :
	m_engineId(0),
	m_sceneFilePath(args.getSceneFilePath()),
	m_imageFilePath(args.getImageFilePath()),
	m_numRenderThreads(args.getNumRenderThreads()),
	m_performPostProcessing(args.performPostPorcess())
{
	phCreateEngine(&m_engineId, static_cast<PHuint32>(m_numRenderThreads));
}

void StaticImageRenderer::render() const
{
	if(!loadCommandsFromSceneFile())
	{
		return;
	}

	phUpdate(m_engineId);

	std::thread renderThread([=]()
	{
		phRender(m_engineId);
	});

	std::atomic<bool> isRenderingCompleted = false;
	std::thread queryThread([&]()
	{
		/*PHuint32 x, y, w, h;
		int regionStatus = phAsyncPollUpdatedFilmRegion(engineId, &x, &y, &w, &h);
		if(regionStatus != PH_FILM_REGION_STATUS_INVALID)
		{
			std::cout << "xywh: " << x << ", " << y << ", " << w << ", " << h << std::endl;
		}*/

		using namespace std::chrono_literals;

		PHfloat32 currentProgress = 0, samplesPerSecond = 0;
		PHfloat32 lastProgress = 0;
		while(!isRenderingCompleted)
		{
			phAsyncGetRendererStatistics(m_engineId, &currentProgress, &samplesPerSecond);

			if((currentProgress - lastProgress) > 1.0f)
			{
				lastProgress = currentProgress;
				std::cout << "progress: " << currentProgress << " % | "
				          << "samples/sec: " << samplesPerSecond << std::endl;
			}

			std::this_thread::sleep_for(2s);
		}
	});

	renderThread.join();
	isRenderingCompleted = true;

	PHuint32 filmWpx, filmHpx;
	phGetFilmDimension(m_engineId, &filmWpx, &filmHpx);

	PHuint64 frameId;
	phCreateFrame(&frameId, filmWpx, filmHpx);
	if(m_performPostProcessing)
	{
		phDevelopFilm(m_engineId, frameId);
	}
	else
	{
		phDevelopFilmRaw(m_engineId, frameId);
	}
	phSaveFrame(frameId, m_imageFilePath.c_str());

	std::cout << "render completed, image saved to <" << m_imageFilePath << ">" << std::endl;

	queryThread.join();
}

bool StaticImageRenderer::loadCommandsFromSceneFile() const
{
	std::ifstream sceneFile;
	sceneFile.open(m_sceneFilePath, std::ios::in);
	if(!sceneFile.is_open())
	{
		std::cerr << "warning: scene file <" << m_sceneFilePath << "> opening failed" << std::endl;
		return false;
	}
	else
	{
		std::string lineCommand;
		while(sceneFile.good())
		{
			std::getline(sceneFile, lineCommand);
			lineCommand += '\n';
			phEnterCommand(m_engineId, lineCommand.c_str());
		}
		phEnterCommand(m_engineId, "->");
	}
}

PH_CLI_NAMESPACE_END<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used 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.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtCore/QtCore>
#include <QtTest/QtTest>

class tst_Headers: public QObject
{
    Q_OBJECT
public:
    tst_Headers();

private slots:
    void initTestCase();

    void licenseCheck_data() { allHeadersData(); }
    void licenseCheck();

    void privateSlots_data() { allHeadersData(); }
    void privateSlots();

    void macros_data() { allHeadersData(); }
    void macros();

private:
    void allHeadersData();
    QStringList headers;
    const QRegExp copyrightPattern;
    const QRegExp licensePattern;
    const QRegExp moduleTest;
};

tst_Headers::tst_Headers() :
    copyrightPattern("\\*\\* Copyright \\(C\\) 20[0-9][0-9] Nokia Corporation and/or its subsidiary\\(-ies\\)."),
    licensePattern("\\*\\* \\$QT_BEGIN_LICENSE:(LGPL|BSD|3RDPARTY)\\$"),
    moduleTest(QLatin1String("\\*\\* This file is part of the .+ of the Qt Toolkit."))
{
}

QStringList getHeaders(const QString &path)
{
    QStringList headers;

    QDir dir(path);
    QStringList dirs = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);

    foreach (QString subdir, dirs)
        headers += getHeaders(path + "/" + subdir);

    QStringList entries = dir.entryList(QStringList("*.h"), QDir::Files);
    QRegExp reg("^(?!ui_)");
    entries = entries.filter(reg);
    foreach (QString entry, entries)
        headers += path + "/" + entry;

    return headers;
}

void tst_Headers::initTestCase()
{
    QString qtSrcDir = QString::fromLocal8Bit(qgetenv("QTSRCDIR").isEmpty()
            ? qgetenv("QTDIR") : qgetenv("QTSRCDIR"));
    headers = getHeaders(qtSrcDir + "/src");

#ifndef Q_OS_WINCE
    // Windows CE does not have any headers on the test device
    QVERIFY2(!headers.isEmpty(), "No headers were found, something is wrong with the auto test setup.");
#endif

    QVERIFY(copyrightPattern.isValid());
    QVERIFY(licensePattern.isValid());
}

void tst_Headers::allHeadersData()
{
    QTest::addColumn<QString>("header");

    if (headers.isEmpty())
        QSKIP("can't find any headers in your $QTDIR/src", SkipAll);

    foreach (QString hdr, headers) {
        if (hdr.contains("/3rdparty/") || hdr.endsWith("/qclass_lib_map.h"))
            continue;

        QTest::newRow(qPrintable(hdr)) << hdr;
    }
}

void tst_Headers::licenseCheck()
{
    QFETCH(QString, header);

    if (header.endsWith("/qgifhandler.h") || header.endsWith("/qconfig.h"))
        return;

    QFile f(header);
    QVERIFY(f.open(QIODevice::ReadOnly));
    QByteArray data = f.readAll();
    QStringList content = QString::fromLocal8Bit(data.replace('\r',"")).split("\n");

    QVERIFY(licensePattern.exactMatch(content.at(7)) ||
            licensePattern.exactMatch(content.at(4)));
    QString licenseType = licensePattern.cap(1);

    int i = 0;

    QCOMPARE(content.at(i++), QString("/****************************************************************************"));
    if (licenseType != "3RDPARTY") {
        QCOMPARE(content.at(i++), QString("**"));
        QVERIFY(copyrightPattern.exactMatch(content.at(i++)));
        QCOMPARE(content.at(i++), QString("** Contact: Qt Software Information (qt-info@nokia.com)"));
    }
    QCOMPARE(content.at(i++), QString("**"));
    QVERIFY(moduleTest.exactMatch(content.at(i++)));
    QCOMPARE(content.at(i++), QString("**"));
}

void tst_Headers::privateSlots()
{
    QFETCH(QString, header);

    if (header.endsWith("/qobjectdefs.h"))
        return;

    QFile f(header);
    QVERIFY(f.open(QIODevice::ReadOnly));

    QStringList content = QString::fromLocal8Bit(f.readAll()).split("\n");
    foreach (QString line, content) {
        if (line.contains("Q_PRIVATE_SLOT("))
            QVERIFY(line.contains("_q_"));
    }
}

void tst_Headers::macros()
{
    QFETCH(QString, header);

    if (header.endsWith("_p.h") || header.endsWith("_pch.h")
        || header.contains("global/qconfig-") || header.endsWith("/qconfig.h")
        || header.contains("/src/tools/") || header.contains("/src/plugins/")
        || header.endsWith("/qiconset.h") || header.endsWith("/qfeatures.h")
        || header.endsWith("qt_windows.h"))
        return;

    QFile f(header);
    QVERIFY(f.open(QIODevice::ReadOnly));

    QByteArray data = f.readAll();
    QStringList content = QString::fromLocal8Bit(data.replace('\r', "")).split("\n");

    int beginHeader = content.indexOf("QT_BEGIN_HEADER");
    int endHeader = content.lastIndexOf("QT_END_HEADER");

    QVERIFY(beginHeader >= 0);
    QVERIFY(endHeader >= 0);
    QVERIFY(beginHeader < endHeader);

    QVERIFY(content.indexOf(QRegExp("\\bslots\\s*:")) == -1);
    QVERIFY(content.indexOf(QRegExp("\\bsignals\\s*:")) == -1);

    if (header.contains("/sql/drivers/") || header.contains("/arch/qatomic")
        || header.endsWith("qglobal.h")
        || header.endsWith("qwindowdefs_win.h"))
        return;

    int qtmodule = content.indexOf(QRegExp("^QT_MODULE\\(.*\\)$"));
    QVERIFY(qtmodule != -1);
    QVERIFY(qtmodule > beginHeader);
    QVERIFY(qtmodule < endHeader);

    int beginNamespace = content.indexOf("QT_BEGIN_NAMESPACE");
    int endNamespace = content.lastIndexOf("QT_END_NAMESPACE");
    QVERIFY(beginNamespace != -1);
    QVERIFY(endNamespace != -1);
    QVERIFY(beginHeader < beginNamespace);
    QVERIFY(beginNamespace < endNamespace);
    QVERIFY(endNamespace < endHeader);
}

QTEST_MAIN(tst_Headers)
#include "tst_headers.moc"
<commit_msg>Autotest: fix detection of generated files and strip the first line<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used 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.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtCore/QtCore>
#include <QtTest/QtTest>

class tst_Headers: public QObject
{
    Q_OBJECT
public:
    tst_Headers();

private slots:
    void initTestCase();

    void licenseCheck_data() { allHeadersData(); }
    void licenseCheck();

    void privateSlots_data() { allHeadersData(); }
    void privateSlots();

    void macros_data() { allHeadersData(); }
    void macros();

private:
    void allHeadersData();
    QStringList headers;
    const QRegExp copyrightPattern;
    const QRegExp licensePattern;
    const QRegExp moduleTest;
};

tst_Headers::tst_Headers() :
    copyrightPattern("\\*\\* Copyright \\(C\\) 20[0-9][0-9] Nokia Corporation and/or its subsidiary\\(-ies\\)."),
    licensePattern("\\*\\* \\$QT_BEGIN_LICENSE:(LGPL|BSD|3RDPARTY)\\$"),
    moduleTest(QLatin1String("\\*\\* This file is part of the .+ of the Qt Toolkit."))
{
}

QStringList getHeaders(const QString &path)
{
    QStringList headers;

    QDir dir(path);
    QStringList dirs = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);

    foreach (QString subdir, dirs)
        headers += getHeaders(path + "/" + subdir);

    QStringList entries = dir.entryList(QStringList("*.h"), QDir::Files);
    QRegExp reg("^(?!ui_)");
    entries = entries.filter(reg);
    foreach (QString entry, entries)
        headers += path + "/" + entry;

    return headers;
}

void tst_Headers::initTestCase()
{
    QString qtSrcDir = QString::fromLocal8Bit(qgetenv("QTSRCDIR").isEmpty()
            ? qgetenv("QTDIR") : qgetenv("QTSRCDIR"));
    headers = getHeaders(qtSrcDir + "/src");

#ifndef Q_OS_WINCE
    // Windows CE does not have any headers on the test device
    QVERIFY2(!headers.isEmpty(), "No headers were found, something is wrong with the auto test setup.");
#endif

    QVERIFY(copyrightPattern.isValid());
    QVERIFY(licensePattern.isValid());
}

void tst_Headers::allHeadersData()
{
    QTest::addColumn<QString>("header");

    if (headers.isEmpty())
        QSKIP("can't find any headers in your $QTDIR/src", SkipAll);

    foreach (QString hdr, headers) {
        if (hdr.contains("/3rdparty/") || hdr.endsWith("/qclass_lib_map.h"))
            continue;

        QTest::newRow(qPrintable(hdr)) << hdr;
    }
}

void tst_Headers::licenseCheck()
{
    QFETCH(QString, header);

    if (header.endsWith("/qgifhandler.h") || header.endsWith("/qconfig.h"))
        return;

    QFile f(header);
    QVERIFY(f.open(QIODevice::ReadOnly));
    QByteArray data = f.readAll();
    QStringList content = QString::fromLocal8Bit(data.replace('\r',"")).split("\n");

    if (content.first().contains("generated"))
        content.takeFirst();

    QVERIFY(licensePattern.exactMatch(content.at(7)) ||
            licensePattern.exactMatch(content.at(4)));
    QString licenseType = licensePattern.cap(1);

    int i = 0;

    QCOMPARE(content.at(i++), QString("/****************************************************************************"));
    if (licenseType != "3RDPARTY") {
        QCOMPARE(content.at(i++), QString("**"));
        QVERIFY(copyrightPattern.exactMatch(content.at(i++)));
        QCOMPARE(content.at(i++), QString("** Contact: Qt Software Information (qt-info@nokia.com)"));
    }
    QCOMPARE(content.at(i++), QString("**"));
    QVERIFY(moduleTest.exactMatch(content.at(i++)));
    QCOMPARE(content.at(i++), QString("**"));
}

void tst_Headers::privateSlots()
{
    QFETCH(QString, header);

    if (header.endsWith("/qobjectdefs.h"))
        return;

    QFile f(header);
    QVERIFY(f.open(QIODevice::ReadOnly));

    QStringList content = QString::fromLocal8Bit(f.readAll()).split("\n");
    foreach (QString line, content) {
        if (line.contains("Q_PRIVATE_SLOT("))
            QVERIFY(line.contains("_q_"));
    }
}

void tst_Headers::macros()
{
    QFETCH(QString, header);

    if (header.endsWith("_p.h") || header.endsWith("_pch.h")
        || header.contains("global/qconfig-") || header.endsWith("/qconfig.h")
        || header.contains("/src/tools/") || header.contains("/src/plugins/")
        || header.endsWith("/qiconset.h") || header.endsWith("/qfeatures.h")
        || header.endsWith("qt_windows.h"))
        return;

    QFile f(header);
    QVERIFY(f.open(QIODevice::ReadOnly));

    QByteArray data = f.readAll();
    QStringList content = QString::fromLocal8Bit(data.replace('\r', "")).split("\n");

    int beginHeader = content.indexOf("QT_BEGIN_HEADER");
    int endHeader = content.lastIndexOf("QT_END_HEADER");

    QVERIFY(beginHeader >= 0);
    QVERIFY(endHeader >= 0);
    QVERIFY(beginHeader < endHeader);

    QVERIFY(content.indexOf(QRegExp("\\bslots\\s*:")) == -1);
    QVERIFY(content.indexOf(QRegExp("\\bsignals\\s*:")) == -1);

    if (header.contains("/sql/drivers/") || header.contains("/arch/qatomic")
        || header.endsWith("qglobal.h")
        || header.endsWith("qwindowdefs_win.h"))
        return;

    int qtmodule = content.indexOf(QRegExp("^QT_MODULE\\(.*\\)$"));
    QVERIFY(qtmodule != -1);
    QVERIFY(qtmodule > beginHeader);
    QVERIFY(qtmodule < endHeader);

    int beginNamespace = content.indexOf("QT_BEGIN_NAMESPACE");
    int endNamespace = content.lastIndexOf("QT_END_NAMESPACE");
    QVERIFY(beginNamespace != -1);
    QVERIFY(endNamespace != -1);
    QVERIFY(beginHeader < beginNamespace);
    QVERIFY(beginNamespace < endNamespace);
    QVERIFY(endNamespace < endHeader);
}

QTEST_MAIN(tst_Headers)
#include "tst_headers.moc"
<|endoftext|>


<commit_before>// Ignore unused parameter warnings coming from cppunit headers
#include <libmesh/ignore_warnings.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <libmesh/restore_warnings.h>

#include <libmesh/equation_systems.h>
#include <libmesh/mesh.h>
#include <libmesh/mesh_generation.h>
#include <libmesh/numeric_vector.h>
#include <libmesh/dof_map.h>
#include <libmesh/elem.h>
#include <libmesh/default_coupling.h>

#include "test_comm.h"

// THE CPPUNIT_TEST_SUITE_END macro expands to code that involves
// std::auto_ptr, which in turn produces -Wdeprecated-declarations
// warnings.  These can be ignored in GCC as long as we wrap the
// offending code in appropriate pragmas.  We can't get away with a
// single ignore_warnings.h inclusion at the beginning of this file,
// since the libmesh headers pull in a restore_warnings.h at some
// point.  We also don't bother restoring warnings at the end of this
// file since it's not a header.
#include <libmesh/ignore_warnings.h>

using namespace libMesh;

Number cubic_default_coupling_test (const Point& p,
                                    const Parameters&,
                                    const std::string&,
                                    const std::string&)
{
  const Real & x = p(0);
  const Real & y = p(1);
  const Real & z = p(2);

  return x*(1-x)*(1-x) + x*x*(1-y) + x*(1-y)*(1-z) + y*(1-y)*z + z*(1-z)*(1-z);
}

class DefaultCouplingTest : public CppUnit::TestCase {
public:
  CPPUNIT_TEST_SUITE( DefaultCouplingTest );

  CPPUNIT_TEST( testCouplingOnEdge3 );
  CPPUNIT_TEST( testCouplingOnQuad9 );
  CPPUNIT_TEST( testCouplingOnTri6 );
  CPPUNIT_TEST( testCouplingOnHex27 );

  CPPUNIT_TEST_SUITE_END();

private:

public:
  void setUp()
  {}

  void tearDown()
  {}

  void testCoupling(const ElemType elem_type)
  {
    Mesh mesh(*TestCommWorld);

    EquationSystems es(mesh);
    System &sys = es.add_system<System> ("SimpleSystem");
    sys.add_variable("u", THIRD, HIERARCHIC);
    sys.get_dof_map().default_algebraic_ghosting().set_n_levels(3);

    const unsigned int n_elem_per_side = 5;
    const std::unique_ptr<Elem> test_elem = Elem::build(elem_type);
    const unsigned int ymax = test_elem->dim() > 1;
    const unsigned int zmax = test_elem->dim() > 2;
    const unsigned int ny = ymax * n_elem_per_side;
    const unsigned int nz = zmax * n_elem_per_side;

    MeshTools::Generation::build_cube (mesh,
                                       n_elem_per_side,
                                       ny,
                                       nz,
                                       0., 1.,
                                       0., ymax,
                                       0., zmax,
                                       elem_type);

    es.init();
    sys.project_solution(cubic_default_coupling_test, nullptr, es.parameters);

    for (const auto & elem : mesh.active_local_element_ptr_range())
      for (unsigned int s1=0; s1 != elem->n_neighbors(); ++s1)
        {
          const Elem * n1 = elem->neighbor_ptr(s1);
          if (!n1)
            continue;

          // Let's speed up this test by only checking the ghosted
          // elements which are most likely to break.
          if (n1->processor_id() == mesh.processor_id())
            continue;

          for (unsigned int s2=0; s2 != elem->n_neighbors(); ++s2)
            {
              const Elem * n2 = elem->neighbor_ptr(s2);
              if (!n2 ||
                  n2->processor_id() == mesh.processor_id())
                continue;

              for (unsigned int s3=0; s3 != elem->n_neighbors(); ++s3)
                {
                  const Elem * n3 = elem->neighbor_ptr(s3);
                  if (!n3 ||
                      n3->processor_id() == mesh.processor_id())
                    continue;

                  Point p = n3->centroid();

                  CPPUNIT_ASSERT_DOUBLES_EQUAL(libmesh_real(sys.point_value(0,p,n3)),
                                               libmesh_real(cubic_default_coupling_test(p,es.parameters,"","")),
                                               TOLERANCE*TOLERANCE);
                }
            }
        }
  }

  void testCouplingOnEdge3() { testCoupling(EDGE3); }
  void testCouplingOnQuad9() { testCoupling(QUAD9); }
  void testCouplingOnTri6()  { testCoupling(TRI6); }
  void testCouplingOnHex27() { testCoupling(HEX27); }

};

CPPUNIT_TEST_SUITE_REGISTRATION( DefaultCouplingTest );
<commit_msg>Test is_evaluable, evaluable_* iterators<commit_after>// Ignore unused parameter warnings coming from cppunit headers
#include <libmesh/ignore_warnings.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <libmesh/restore_warnings.h>

#include <libmesh/equation_systems.h>
#include <libmesh/mesh.h>
#include <libmesh/mesh_generation.h>
#include <libmesh/numeric_vector.h>
#include <libmesh/dof_map.h>
#include <libmesh/elem.h>
#include <libmesh/default_coupling.h>

#include "test_comm.h"

// THE CPPUNIT_TEST_SUITE_END macro expands to code that involves
// std::auto_ptr, which in turn produces -Wdeprecated-declarations
// warnings.  These can be ignored in GCC as long as we wrap the
// offending code in appropriate pragmas.  We can't get away with a
// single ignore_warnings.h inclusion at the beginning of this file,
// since the libmesh headers pull in a restore_warnings.h at some
// point.  We also don't bother restoring warnings at the end of this
// file since it's not a header.
#include <libmesh/ignore_warnings.h>

using namespace libMesh;

Number cubic_default_coupling_test (const Point& p,
                                    const Parameters&,
                                    const std::string&,
                                    const std::string&)
{
  const Real & x = p(0);
  const Real & y = p(1);
  const Real & z = p(2);

  return x*(1-x)*(1-x) + x*x*(1-y) + x*(1-y)*(1-z) + y*(1-y)*z + z*(1-z)*(1-z);
}

class DefaultCouplingTest : public CppUnit::TestCase {
public:
  CPPUNIT_TEST_SUITE( DefaultCouplingTest );

  CPPUNIT_TEST( testCouplingOnEdge3 );
  CPPUNIT_TEST( testCouplingOnQuad9 );
  CPPUNIT_TEST( testCouplingOnTri6 );
  CPPUNIT_TEST( testCouplingOnHex27 );

  CPPUNIT_TEST_SUITE_END();

private:

public:
  void setUp()
  {}

  void tearDown()
  {}

  void testCoupling(const ElemType elem_type)
  {
    Mesh mesh(*TestCommWorld);

    EquationSystems es(mesh);
    System &sys = es.add_system<System> ("SimpleSystem");
    sys.add_variable("u", THIRD, HIERARCHIC);
    sys.get_dof_map().default_algebraic_ghosting().set_n_levels(3);

    const unsigned int n_elem_per_side = 5;
    const std::unique_ptr<Elem> test_elem = Elem::build(elem_type);
    const unsigned int ymax = test_elem->dim() > 1;
    const unsigned int zmax = test_elem->dim() > 2;
    const unsigned int ny = ymax * n_elem_per_side;
    const unsigned int nz = zmax * n_elem_per_side;

    MeshTools::Generation::build_cube (mesh,
                                       n_elem_per_side,
                                       ny,
                                       nz,
                                       0., 1.,
                                       0., ymax,
                                       0., zmax,
                                       elem_type);

    es.init();
    sys.project_solution(cubic_default_coupling_test, nullptr, es.parameters);

    std::set<dof_id_type> evaluable_elements;

    for (const auto & elem : mesh.active_local_element_ptr_range())
      {
        CPPUNIT_ASSERT(sys.get_dof_map().is_evaluable(*elem));
        evaluable_elements.insert(elem->id());

        for (unsigned int s1=0; s1 != elem->n_neighbors(); ++s1)
          {
            const Elem * n1 = elem->neighbor_ptr(s1);
            // Let's speed up this test by only checking the ghosted
            // elements which are most likely to break.
            if (!n1 ||
                n1->processor_id() == mesh.processor_id())
              continue;

            if (!evaluable_elements.count(n1->id()))
              {
                CPPUNIT_ASSERT(sys.get_dof_map().is_evaluable(*n1));
                evaluable_elements.insert(n1->id());
              }

            for (unsigned int s2=0; s2 != elem->n_neighbors(); ++s2)
              {
                const Elem * n2 = n1->neighbor_ptr(s2);
                if (!n2 ||
                    n2->processor_id() == mesh.processor_id())
                  continue;

                if (!evaluable_elements.count(n2->id()))
                  {
                    CPPUNIT_ASSERT(sys.get_dof_map().is_evaluable(*n2));
                    evaluable_elements.insert(n2->id());
                  }

                for (unsigned int s3=0; s3 != elem->n_neighbors(); ++s3)
                  {
                    const Elem * n3 = n2->neighbor_ptr(s3);
                    if (!n3 ||
                        n3->processor_id() == mesh.processor_id() ||
                        evaluable_elements.count(n3->id()))
                      continue;

                    CPPUNIT_ASSERT(sys.get_dof_map().is_evaluable(*n3));
                    evaluable_elements.insert(n3->id());

                    Point p = n3->centroid();

                    CPPUNIT_ASSERT_DOUBLES_EQUAL(libmesh_real(sys.point_value(0,p,n3)),
                                                 libmesh_real(cubic_default_coupling_test(p,es.parameters,"","")),
                                                 TOLERANCE*TOLERANCE);
                  }
              }
          }
      }

    const std::size_t n_evaluable =
      std::distance(mesh.evaluable_elements_begin(sys.get_dof_map()),
                    mesh.evaluable_elements_end(sys.get_dof_map()));

    CPPUNIT_ASSERT_EQUAL(evaluable_elements.size(), n_evaluable);
  }

  void testCouplingOnEdge3() { testCoupling(EDGE3); }
  void testCouplingOnQuad9() { testCoupling(QUAD9); }
  void testCouplingOnTri6()  { testCoupling(TRI6); }
  void testCouplingOnHex27() { testCoupling(HEX27); }

};

CPPUNIT_TEST_SUITE_REGISTRATION( DefaultCouplingTest );
<|endoftext|>


<commit_before>/*
 * particle_filter.cpp
 *
 *  Created on: Dec 12, 2016
 *      Author: Tiffany Huang
 */

#include <random>
#include <algorithm>
#include <iostream>
#include <numeric>
#include <assert.h>

#include "particle_filter.h"
#include "helper_functions.h"

#include "math.h"

using namespace std;

//constants: might be good to include them in particle_filter.h so that they could be tuned outside the class
//(in main.cpp for ex)
const int N = 1000;
const double EPSILON = 1E-5;

//helper functions
double coef(double x, double ux, double std_x) {
    return pow(x-ux,2)/(2*pow(std_x,2));
}

double gauss(double x, double y, double ux, double uy, double std_x, double std_y) {
    double c = 1/(2*M_PI*std_x*std_y);

    double val = coef(x, ux, std_x) + coef(y, uy, std_y);

    return c * exp(-val);
}
//end helper functions

void ParticleFilter::init(double x, double y, double theta, double std[]) {
    default_random_engine gen;

    //Create normal distributions for each dimension
    normal_distribution<double> dist_x(x, std[0]);
    normal_distribution<double> dist_y(y, std[1]);
    normal_distribution<double> dist_psi(theta, std[2]);

    num_particles = N;

    for (int i = 0; i < num_particles; i++) {
        Particle p;
        p.id = i;
        p.x = dist_x(gen);
        p.y = dist_y(gen);
        p.theta = dist_psi(gen);

        p.weight = 1;

        particles.push_back(p);
        weights.push_back(1);
    }

    is_initialized = true;
}

void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) {
    default_random_engine gen;

    for (int i = 0; i < num_particles; i++) {
        Particle part = particles[i];
        double xf, yf, thetaf;

        //prediction
        if (fabs(yaw_rate) < EPSILON) { //yawrate ~ 0
            xf = part.x + velocity*delta_t*cos(part.theta);
            yf = part.y + velocity*delta_t*sin(part.theta);
            thetaf = part.theta;
        } else {
            xf = part.x + (velocity/yaw_rate) * (sin(part.theta + yaw_rate*delta_t) - sin(part.theta));
            yf = part.y + (velocity/yaw_rate) * (cos(part.theta) - cos(part.theta + yaw_rate*delta_t));
            thetaf = part.theta + yaw_rate*delta_t;
        }

        //Create normal distributions for each dimension
        normal_distribution<double> dist_x(xf, std_pos[0]);
        normal_distribution<double> dist_y(yf, std_pos[1]);
        normal_distribution<double> dist_psi(thetaf, std_pos[2]);

        //add noise
        xf = dist_x(gen);
        yf = dist_y(gen);
        thetaf = dist_psi(gen);

        particles[i].x = xf;
        particles[i].y = yf;
        particles[i].theta = thetaf;

    }
}

void ParticleFilter::dataAssociation(std::vector<LandmarkObs> predicted, std::vector<LandmarkObs>& observations) {

    for (int i = 0; i < observations.size(); i++) {
        int min_idx = -1;
        double min_dist = MAXFLOAT;

        LandmarkObs obs = observations[i];
        for (int j = 0; j < predicted.size(); j++) {
            LandmarkObs pred = predicted[j];

            double d = dist(obs.x, obs.y, pred.x, pred.y);
            if (d < min_dist) {
                min_dist = d;
                min_idx = j;
            }
        }

        assert(min_idx > -1);

        observations[i].id = predicted[min_idx].id;
    }

}

void ParticleFilter::updateWeights(double sensor_range, double std_landmark[],
		std::vector<LandmarkObs> observations, Map map_landmarks) {

	// NOTE: The observations are given in the VEHICLE'S coordinate system. Your particles are located
	//   according to the MAP'S coordinate system. You will need to transform between the two systems.
	//   Keep in mind that this transformation requires both rotation AND translation (but no scaling).
	//   The following is a good resource for the theory:
	//   https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm
	//   and the following is a good resource for the actual equation to implement (look at equation
	//   3.33. Note that you'll need to switch the minus sign in that equation to a plus to account
	//   for the fact that the map's y-axis actually points downwards.)
	//   http://planning.cs.uiuc.edu/node99.html
    double sum_weights = 0.0;
    std::vector<double> new_weights;

    for (int i = 0; i < num_particles; i++) {
        // Transform observations from vehicle's coordinate system into the map's one
        Particle part = particles[i];
        std::vector<LandmarkObs> observations_map;

        for (int j = 0; j < observations.size(); j++) {
            double obs_x = observations[j].x;
            double obs_y = observations[j].y;

            double ang = -part.theta;

            double x = obs_x*cos(ang) + obs_y*sin(ang) + part.x;
            double y = -obs_x*sin(ang) + obs_y*cos(ang) + part.y;

            LandmarkObs landObs;
            landObs.x = x;
            landObs.y = y;

            observations_map.push_back(landObs);
        }

        //filter landmarks within sensor range from the particle
        std::vector<LandmarkObs> predicted;
        for (int k = 0; k < map_landmarks.landmark_list.size(); k++) {
            Map::single_landmark_s landmark = map_landmarks.landmark_list[k];

            double d = dist(part.x, part.y, landmark.x_f, landmark.y_f);

            if (d <= sensor_range) {
                LandmarkObs obs;
                obs.x = landmark.x_f;
                obs.y = landmark.y_f;
                obs.id = landmark.id_i;
                predicted.push_back(obs);
            }
        }

        //find which observation corresponds to which landmark
        dataAssociation(predicted, observations_map);

        double p = 1.0; //asumes at least one observation

        assert(observations_map.size() > 0); //if the particle contains no landamarks nearby, what to do?
        //it might mean the initialization was way off the map, or that the vehicle is eventually lost (run away from the
        // marked territory)

        for (int l = 0; l < observations_map.size(); l++) {
            LandmarkObs lobs = observations_map[l];
            Map::single_landmark_s associated_landmark = map_landmarks.landmark_list[lobs.id-1];
            assert (associated_landmark.id_i == lobs.id);

            double val = gauss(lobs.x, lobs.y, associated_landmark.x_f, associated_landmark.y_f, std_landmark[0], std_landmark[1]);

            p *= val;
        }

        new_weights.push_back(p);
        sum_weights += p;
    }

    for (int i = 0; i < num_particles; i++) {
        new_weights[i] /= sum_weights;
    }

    weights = new_weights;

}

void ParticleFilter::resample() {
    default_random_engine gen;
    discrete_distribution<> dd(weights.begin(), weights.end());

    std::vector<Particle> new_particles;
    for (int i = 0; i < num_particles; i++) {
        Particle p;
        int idx = dd(gen);
        p.x = particles[idx].x;
        p.y = particles[idx].y;
        p.theta = particles[idx].theta;
        p.id = i;

        new_particles.push_back(p);
    }

    particles = new_particles;

}

void ParticleFilter::write(std::string filename) {
	// You don't need to modify this file.
	std::ofstream dataFile;
	dataFile.open(filename, std::ios::app);
	for (int i = 0; i < num_particles; ++i) {
		dataFile << particles[i].x << " " << particles[i].y << " " << particles[i].theta << "\n";
	}
	dataFile.close();
}
<commit_msg>remove MAXFLOAT reference for finding minimum<commit_after>/*
 * particle_filter.cpp
 *
 *  Created on: Dec 12, 2016
 *      Author: Tiffany Huang
 */

#include <random>
#include <algorithm>
#include <iostream>
#include <numeric>
#include <assert.h>

#include "particle_filter.h"
#include "helper_functions.h"

#include "math.h"

using namespace std;

//constants: might be good to include them in particle_filter.h so that they could be tuned outside the class
//(in main.cpp for ex)
const int N = 1000;
const double EPSILON = 1E-5;

//helper functions
double coef(double x, double ux, double std_x) {
    return pow(x-ux,2)/(2*pow(std_x,2));
}

double gauss(double x, double y, double ux, double uy, double std_x, double std_y) {
    double c = 1/(2*M_PI*std_x*std_y);

    double val = coef(x, ux, std_x) + coef(y, uy, std_y);

    return c * exp(-val);
}
//end helper functions

void ParticleFilter::init(double x, double y, double theta, double std[]) {
    default_random_engine gen;

    //Create normal distributions for each dimension
    normal_distribution<double> dist_x(x, std[0]);
    normal_distribution<double> dist_y(y, std[1]);
    normal_distribution<double> dist_psi(theta, std[2]);

    num_particles = N;

    for (int i = 0; i < num_particles; i++) {
        Particle p;
        p.id = i;
        p.x = dist_x(gen);
        p.y = dist_y(gen);
        p.theta = dist_psi(gen);

        p.weight = 1;

        particles.push_back(p);
        weights.push_back(1);
    }

    is_initialized = true;
}

void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) {
    default_random_engine gen;

    for (int i = 0; i < num_particles; i++) {
        Particle part = particles[i];
        double xf, yf, thetaf;

        //prediction
        if (fabs(yaw_rate) < EPSILON) { //yawrate ~ 0
            xf = part.x + velocity*delta_t*cos(part.theta);
            yf = part.y + velocity*delta_t*sin(part.theta);
            thetaf = part.theta;
        } else {
            xf = part.x + (velocity/yaw_rate) * (sin(part.theta + yaw_rate*delta_t) - sin(part.theta));
            yf = part.y + (velocity/yaw_rate) * (cos(part.theta) - cos(part.theta + yaw_rate*delta_t));
            thetaf = part.theta + yaw_rate*delta_t;
        }

        //Create normal distributions for each dimension
        normal_distribution<double> dist_x(xf, std_pos[0]);
        normal_distribution<double> dist_y(yf, std_pos[1]);
        normal_distribution<double> dist_psi(thetaf, std_pos[2]);

        //add noise
        xf = dist_x(gen);
        yf = dist_y(gen);
        thetaf = dist_psi(gen);

        particles[i].x = xf;
        particles[i].y = yf;
        particles[i].theta = thetaf;

    }
}

void ParticleFilter::dataAssociation(std::vector<LandmarkObs> predicted, std::vector<LandmarkObs>& observations) {

    for (int i = 0; i < observations.size(); i++) {
        int min_idx = -1;
        double min_dist = 0;

        LandmarkObs obs = observations[i];
        for (int j = 0; j < predicted.size(); j++) {
            LandmarkObs pred = predicted[j];

            double d = dist(obs.x, obs.y, pred.x, pred.y);
            if (min_idx < 0 || d < min_dist) {
                min_dist = d;
                min_idx = j;
            }
        }

        assert(min_idx > -1);

        observations[i].id = predicted[min_idx].id;
    }

}

void ParticleFilter::updateWeights(double sensor_range, double std_landmark[],
		std::vector<LandmarkObs> observations, Map map_landmarks) {

	// NOTE: The observations are given in the VEHICLE'S coordinate system. Your particles are located
	//   according to the MAP'S coordinate system. You will need to transform between the two systems.
	//   Keep in mind that this transformation requires both rotation AND translation (but no scaling).
	//   The following is a good resource for the theory:
	//   https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm
	//   and the following is a good resource for the actual equation to implement (look at equation
	//   3.33. Note that you'll need to switch the minus sign in that equation to a plus to account
	//   for the fact that the map's y-axis actually points downwards.)
	//   http://planning.cs.uiuc.edu/node99.html
    double sum_weights = 0.0;
    std::vector<double> new_weights;

    for (int i = 0; i < num_particles; i++) {
        // Transform observations from vehicle's coordinate system into the map's one
        Particle part = particles[i];
        std::vector<LandmarkObs> observations_map;

        for (int j = 0; j < observations.size(); j++) {
            double obs_x = observations[j].x;
            double obs_y = observations[j].y;

            double ang = -part.theta;

            double x = obs_x*cos(ang) + obs_y*sin(ang) + part.x;
            double y = -obs_x*sin(ang) + obs_y*cos(ang) + part.y;

            LandmarkObs landObs;
            landObs.x = x;
            landObs.y = y;

            observations_map.push_back(landObs);
        }

        //filter landmarks within sensor range from the particle
        std::vector<LandmarkObs> predicted;
        for (int k = 0; k < map_landmarks.landmark_list.size(); k++) {
            Map::single_landmark_s landmark = map_landmarks.landmark_list[k];

            double d = dist(part.x, part.y, landmark.x_f, landmark.y_f);

            if (d <= sensor_range) {
                LandmarkObs obs;
                obs.x = landmark.x_f;
                obs.y = landmark.y_f;
                obs.id = landmark.id_i;
                predicted.push_back(obs);
            }
        }

        //find which observation corresponds to which landmark
        dataAssociation(predicted, observations_map);

        double p = 1.0; //asumes at least one observation

        assert(observations_map.size() > 0); //if the particle contains no landamarks nearby, what to do?
        //it might mean the initialization was way off the map, or that the vehicle is eventually lost (run away from the
        // marked territory)

        for (int l = 0; l < observations_map.size(); l++) {
            LandmarkObs lobs = observations_map[l];
            Map::single_landmark_s associated_landmark = map_landmarks.landmark_list[lobs.id-1];
            assert (associated_landmark.id_i == lobs.id);

            double val = gauss(lobs.x, lobs.y, associated_landmark.x_f, associated_landmark.y_f, std_landmark[0], std_landmark[1]);

            p *= val;
        }

        new_weights.push_back(p);
        sum_weights += p;
    }

    for (int i = 0; i < num_particles; i++) {
        new_weights[i] /= sum_weights;
    }

    weights = new_weights;

}

void ParticleFilter::resample() {
    default_random_engine gen;
    discrete_distribution<> dd(weights.begin(), weights.end());

    std::vector<Particle> new_particles;
    for (int i = 0; i < num_particles; i++) {
        Particle p;
        int idx = dd(gen);
        p.x = particles[idx].x;
        p.y = particles[idx].y;
        p.theta = particles[idx].theta;
        p.id = i;

        new_particles.push_back(p);
    }

    particles = new_particles;

}

void ParticleFilter::write(std::string filename) {
	// You don't need to modify this file.
	std::ofstream dataFile;
	dataFile.open(filename, std::ios::app);
	for (int i = 0; i < num_particles; ++i) {
		dataFile << particles[i].x << " " << particles[i].y << " " << particles[i].theta << "\n";
	}
	dataFile.close();
}
<|endoftext|>


<commit_before>#ifndef _X_CLIENT_HPP
#define _X_CLIENT_HPP

#include <list>
#include <xcb/xcb.h>
#include <xcb/damage.h>

#include "data_types.hpp"
#include "x_event_handler_t.hpp"
#include "x_connection.hpp"

class x_client : public x_event_handler_t {
  public:
    friend std::ostream & operator<<(std::ostream &, const x_client &);
    friend bool operator==(const x_client &, const xcb_window_t &);
    friend bool operator==(const xcb_window_t &, const x_client &);

    x_client(x_connection & c, const xcb_window_t & window);
    ~x_client(void);

    bool operator==(const x_client & other)
    {
      return _window == other._window;
    }

    const rectangle &  rect(void) const;
    const xcb_window_t & window(void) const;
    const xcb_window_t & parent(void) const;
    const xcb_pixmap_t & name_window_pixmap(void) const;
          unsigned int   net_wm_desktop(void) const;

    bool handle(xcb_generic_event_t * ge);
    void update_geometry(void);

    void update_name_window_pixmap(void);

  private:
    x_connection & _c;

    rectangle _rectangle;
    unsigned int _net_wm_desktop;
    xcb_window_t _window;
    xcb_window_t _parent;
    xcb_pixmap_t _name_window_pixmap = XCB_NONE;
    xcb_pixmap_t _name_window_dummy = XCB_NONE;

    xcb_atom_t a_net_wm_desktop = _c.intern_atom("_NET_WM_DESKTOP");

    void make_dummy(void);
    void update_net_wm_desktop(void);
    void update_parent_window(void);
};

std::list<x_client>
make_x_clients(x_connection & c, const std::vector<xcb_window_t> & windows);

bool
operator==(const x_client &, const xcb_window_t &);

bool
operator==(const xcb_window_t &, const x_client &);

#endif
<commit_msg>Make x_client an observable<commit_after>#ifndef _X_CLIENT_HPP
#define _X_CLIENT_HPP

#include <list>
#include <xcb/xcb.h>
#include <xcb/damage.h>

#include "observer.hpp"
#include "data_types.hpp"
#include "x_event_handler_t.hpp"
#include "x_connection.hpp"

class x_client : public x_event_handler_t
               , public observable<x_client>
{
  public:
    friend std::ostream & operator<<(std::ostream &, const x_client &);
    friend bool operator==(const x_client &, const xcb_window_t &);
    friend bool operator==(const xcb_window_t &, const x_client &);

    x_client(x_connection & c, const xcb_window_t & window);
    ~x_client(void);

    bool operator==(const x_client & other)
    {
      return _window == other._window;
    }

    const rectangle &  rect(void) const;
    const xcb_window_t & window(void) const;
    const xcb_window_t & parent(void) const;
    const xcb_pixmap_t & name_window_pixmap(void) const;
          unsigned int   net_wm_desktop(void) const;

    bool handle(xcb_generic_event_t * ge);
    void update_geometry(void);

    void update_name_window_pixmap(void);

  private:
    x_connection & _c;

    rectangle _rectangle;
    unsigned int _net_wm_desktop;
    xcb_window_t _window;
    xcb_window_t _parent;
    xcb_pixmap_t _name_window_pixmap = XCB_NONE;
    xcb_pixmap_t _name_window_dummy = XCB_NONE;

    xcb_atom_t a_net_wm_desktop = _c.intern_atom("_NET_WM_DESKTOP");

    void make_dummy(void);
    void update_net_wm_desktop(void);
    void update_parent_window(void);
};

std::list<x_client>
make_x_clients(x_connection & c, const std::vector<xcb_window_t> & windows);

bool
operator==(const x_client &, const xcb_window_t &);

bool
operator==(const xcb_window_t &, const x_client &);

#endif
<|endoftext|>